There are a number of operators that are timer based, and I although I don't have a concrete example, would think it common to create new operators that utilise timers. So how would you go about writing a test that runs synchronously for these operators?
As an example, how could I go about unit testing an operator such as BufferWithTime?
The most accessible way to do the test would be 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);
In addition you can also use a bunch of types from System.Reactive.Testing.dll
, which makes things even easier but takes a dependency on Microsoft.VisualStudio.QualityTools.UnitTestFramework.dll
which in turn has a dependency on System.Web.dll
(not available in the 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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With