wpf - Rx 响应式(Reactive)扩展 Observeondispatcher 单元测试错误 : The current thread has no Dispatcher associated with it

标签 wpf unit-testing system.reactive dispatcher observable

我想对包含如下注册的 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/

相关文章:

c# - 如何根据属性压缩 2 个序列(zip、join)

c# - 安装 Reactive Extensions 后动态使用 Newtonsoft Json 时出现 RuntimeBinderException

c# - 为什么用 Rx 处理并发这么容易?

WPF:在图像元素中使用特定的图标图像

python - 如何以可移植的方式将 tox 指向所有 python 版本(例如,无需对 tox.ini 中的路径进行硬编码)?

c# - Asp.Net MVC 5 测试 IoC + 依赖注入(inject)

unit-testing - 单元测试具有许多私有(private)方法的复杂类

C#/WPF : Why is tab not focusing properly

wpf - 设置 GridView 列的样式

wpf - 居中DatePicker控件