Recommended way to test Scheduler/Throttle

时光总嘲笑我的痴心妄想 提交于 2019-12-06 07:28:19

Short answers:

  1. Yes, by making sure you're using CurrentThreadScheduler.Instance when running under test
  2. Instead of using CurrentThreadScheduler, use a TestScheduler and manually advance it

The longer answer is that you need to ensure your unit tests can control the scheduler being used by your System Under Test (SUT). By default, you'll generally want to use CurrentThreadScheduler.Instance to make things happen "instantly" without any need to advance the scheduler manually. But when you want to write tests that do validate timing, you use a TestScheduler instead.

If, as you seem to be, you're using RxApp.*Scheduler, take a look at the With extension method, which can be used like this:

(new TestScheduler()).With(sched => {
    // write test logic here, and RxApp.*Scheduler will resolve to the chosen TestScheduler
});

I tend to avoid using the RxApp ambient context altogether for the same reason I avoid all ambient contexts: they're shared state and can cause trouble as a consequence. Instead, I inject an IScheduler (or two) into my SUT as a dependency.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!