【发布时间】:2018-10-23 13:36:48
【问题描述】:
我是 ReactiveUI 的新手,正在尝试测试如下所示的视图模型:
public interface IService
{
Task<SessionModel> GetData(string id);
}
/// Provides a group of schedulers available to be used
public interface ISchedulers
{
IScheduler Default { get; }
IScheduler Dispatcher { get; }
}
public class MyVm : ReactiveObject
{
IService service;
public MyVm(ISchedulers schedulers, IService service)
{
this.service = service;
this.session = this.WhenAnyValue(x => x.SessionId)
.SelectMany(SearchSession)
.ObserveOn(schedulers.Default)
.ToProperty(this, x => x.Session);
}
private async Task<SessionModel> SearchSession(string id)
{
return await this.service.GetData(id);
}
private string sessionId;
public string SessionId
{
get => sessionId;
set => this.RaiseAndSetIfChanged(ref sessionId, value);
}
readonly ObservableAsPropertyHelper<SessionModel> session;
public SessionModel Session
{
get { return session.Value; }
}
}
public class SessionModel { }
我正在模拟返回虚拟数据的服务调用,但不确定我需要对 TestScheduler 做什么才能让 SelectMany 工作。
这是一个测试类,展示了我将如何为视图模型创建测试。目标是最终能够检查模型是否已设置:
[TestClass]
public class MyVmTests
{
[TestMethod]
public void CreateClass
{
var subject = new MyVm(/*pass in mocks*/);
subject.SessionId="test";
Assert.IsNotNull(subject.Session);
}
}
【问题讨论】:
-
ISchedulers是什么? -
它提供了可能的调度器列表供可观察者使用。它在测试中被模拟返回
TestScheduler。在实际代码中它返回System.Reactive.Concurrency.Scheduler.Default。 -
我更新了你的代码,我假设你有。您可以添加您要测试的内容吗?
-
添加了测试类。
-
我似乎无法在不添加更多单词的情况下添加更多代码。请注意,SessionId 将被正确定义为使用
RaiseAndSetIfChanged
标签: unit-testing tdd system.reactive reactiveui