我是 ReactiveUI 的新手。我有以下简单的设置:可以指定 csv 文件的路径,并将其中包含的数据点显示给用户(使用 oxyplot)。 现在我正在尝试测试以下订阅:
public GraphViewModel(IScreen hostScreen)
{
HostScreen = hostScreen;
setupGraphFormatting();
// Data Loading if path is valid
this.WhenAnyValue(viewModel => viewModel.PathToDataCsv)
.ObserveOn(RxApp.MainThreadScheduler)
.Throttle(TimeSpan.FromMilliseconds(500), RxApp.TaskpoolScheduler)
.Select(csvPath => csvPath?.Trim('"'))
.Where(csvPath => !string.IsNullOrEmpty(csvPath) && File.Exists(csvPath))
.Subscribe(csvPath =>
{
csvPath = csvPath?.Trim('"');
updatePlotModel(csvPath);
}, exception => {});
/* additional Code*/
}
以下是相应的单元测试:
这里是需要翻译的内容:
[Test]
public void If_PathToDataCsv_has_a_valid_value()
{
new TestScheduler().With(scheduler =>
{
string pathToValidCsvFile = "data.log";
var viewModel = new GraphViewModel(null);
scheduler.AdvanceByMs(1000);
viewModel.PathToDataCsv = pathToValidCsvFile;
scheduler.AdvanceByMs(1000);
viewModel.PlotModel.Series.Count.Should().Be(6);
});
}
我的第一次实现WhenAnyValue时,没有对任何调度程序进行特定设置(在节流和缺乏ObserverOn的情况下):
public GraphViewModel(IScreen hostScreen)
{
HostScreen = hostScreen;
setupGraphFormatting();
// Data Loading if path is valid
this.WhenAnyValue(viewModel => viewModel.PathToDataCsv)
.Throttle(TimeSpan.FromMilliseconds(500))
.Select(csvPath => csvPath?.Trim('"'))
.Where(csvPath => !string.IsNullOrEmpty(csvPath) && File.Exists(csvPath))
.Subscribe(csvPath =>
{
csvPath = csvPath?.Trim('"');
updatePlotModel(csvPath);
}, exception => {});
/* additional Code*/
}
但是我的单元测试失败了。我以为TestScheduler在Throttle后台使用,我什么也不用做。我是做错了还是这样做是正确的:如果我想使用TestScheduler/TimeTravel™,我必须像我所做的那样指定调度程序?
编辑以响应Glenn Watson的答案: 好的,现在清楚了:所涉及的方法(Throttle、ObserverOn)当然不使用ReactiveUI的Schedulers,因为它们是来自Reactive Extensions Framework的方法。因此,在单元测试中,除非我告诉这些方法使用RxApp Schedulers,否则无法由ReactiveUI隐式替换它们...