我想对包含如下注册的 View 模型进行单元测试:
public SampleViewModel(IUnityContainer container)
{
...
Observable.FromEventPattern<PropertyChangedEventArgs>(gridViewModel, "PropertyChanged")
.**ObserveOnDispatcher()**
.Subscribe(_ => this.Update());
...
}
当我运行单元测试时,它告诉我“ 当前线程没有与之关联的调度程序。”到达此代码时。
一种解决方案是使用调度程序,但我不想修改 Viewmodel。
有没有办法让单元测试通过这个语句而不报错?
最佳答案
我建议您提供自己的IScheduler
实现到 ObserveOn(IScheduler)
而不是使用 ObserveOnDispatcher()
运算符(operator)。我使用了加载 DispatcherFrame
的技术或 Dispatcher
但问题是您仍在使用 Dispatcher。最终我发现你只是“从悬崖上掉下来”,尤其是当你涉及到长时间运行的后台线程时。遵循“单元测试中没有线程”的指导方针,不要让调度程序靠近您的 ViewModel!您的单元测试将运行得更快。
处理这个问题的一个更好的方法是注入(inject)一个接口(interface)来访问你的 Dispatcher Scheduler(通过 IScheduler
接口(interface))。这允许您替换公开 TestScheduler
的实现。 .您现在可以在单元测试中控制时间。您可以控制和验证将哪些操作编码到每个调度程序。
这是一篇关于 2009 年初使用 Dispatcher 调用的“单元”测试 WPF 的非常古老的(Rx 之前)帖子。当时这似乎是一个好主意。
https://leecampbell.com/2009/02/17/responsive-wpf-user-interfaces-part-5/
有关使用 Rx 和 TestScheduler
进行测试的更多信息在我在 Rx 上的其他站点中找到
http://introtorx.com/Content/v1.0.10621.0/16_TestingRx.html
关于wpf - Rx 响应式(Reactive)扩展 Observeondispatcher 单元测试错误 : The current thread has no Dispatcher associated with it,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18914544/