How do you unit test Rx statements that use timers?

There are several timer-based statements, and although I don't have a specific example, it would be common to create new statements that use timers. So, how are you going to write a test that runs synchronously for these statements?

As an example, how can I switch to unit testing of an operator such as BufferWithTime?

+6
source share
1 answer

The most affordable way to do this is to use TestScheduler :

 var source = new Subject<int>(); var scheduler = new TestScheduler(); var outputValues = new List<IList<int>>(); source .BufferWithTime(TimeSpan.FromTicks(500), scheduler) .Subscribe(x => outputValues.Add(x)); scheduler.RunTo(1); source.OnNext(1); scheduler.RunTo(100); source.OnNext(2); scheduler.RunTo(200); source.OnNext(3); scheduler.RunTo(501); source.OnNext(4); scheduler.RunTo(1001); Assert.AreEqual(2, outputValues.Count); Assert.AreEqual(3, outputValues[0].Count); Assert.AreEqual(1, outputValues[1].Count); 

Alternatively, you can also use the type group from System.Reactive.Testing.dll , which makes things even easier, but requires a dependency on Microsoft.VisualStudio.QualityTools.UnitTestFramework.dll , which in turn depends on System.Web.dll (not available in client profile).

 // using System.Reactive.Testing; // using System.Reactive.Testing.Mocks; var scheduler = new TestScheduler(); var source = scheduler.CreateColdObservable( new Recorded<Notification<int>>(0, new Notification<int>.OnNext(1)), new Recorded<Notification<int>>(100, new Notification<int>.OnNext(2)), new Recorded<Notification<int>>(400, new Notification<int>.OnNext(3)), new Recorded<Notification<int>>(500, new Notification<int>.OnNext(4)) ) .BufferWithTime(TimeSpan.FromTicks(500), scheduler); var observer = new MockObserver<IList<int>>(scheduler); source.Subscribe(observer); scheduler.RunTo(1001); Assert.AreEqual(2, observer.Count); Assert.AreEqual(3, observer[0].Value.Value.Count); Assert.AreEqual(1, observer[1].Value.Value.Count); 
+8
source

Source: https://habr.com/ru/post/1342999/


All Articles