I’m using Reactive Extensions for .NET (Rx) to expose events as IObservable<T>. I want to create an unit test where I assert that a particular event is fired. Here is a simplified version of the class I want to test:
public sealed class ClassUnderTest : IDisposable {
Subject<Unit> subject = new Subject<Unit>();
public IObservable<Unit> SomethingHappened {
get { return this.subject.AsObservable(); }
}
public void DoSomething() {
this.subject.OnNext(new Unit());
}
public void Dispose() {
this.subject.OnCompleted();
}
}
Obviously my real classes are more complex. My goal is to verify that performing some actions with the class under test leads to a sequence of events signaled on the IObservable. Luckily the classes I want to test implement IDisposable and calling OnCompleted on the subject when the object is disposed makes it much easier to test.
Here is how I test:
// Arrange
var classUnderTest = new ClassUnderTest();
var eventFired = false;
classUnderTest.SomethingHappened.Subscribe(_ => eventFired = true);
// Act
classUnderTest.DoSomething();
// Assert
Assert.IsTrue(eventFired);
Using a variable to determine if an event is fired isn’t too bad, but in more complex scenarios I may want to verify that a particular sequence of events are fired. Is that possible without simply recording the events in variables and then doing assertions on the variables? Being able to use a fluent LINQ-like syntax to make assertions on an IObservable would hopefully make the test more readable.
This answer has been updated to the now released version 1.0 of Rx.
Official documentation is still scant but Testing and Debugging Observable Sequences on MSDN is a good starting place.
The test class should derive from
ReactiveTestin theMicrosoft.Reactive.Testingnamespace. The test is based around aTestSchedulerthat provides virtual time for the test.The
TestScheduler.Schedulemethod can be used to queue up activities at certain points (ticks) in virtual time. The test is executed byTestScheduler.Start. This will return anITestableObserver<T>that can be used for asserting for instance by using theReactiveAssertclass.TestScheduler.Scheduleis used to schedule a call toDoSomethingat time 20 (measured in ticks).Then
TestScheduler.Startis used to perform the actual test on the observableSomethingHappened. The lifetime of the subscription is controlled by the arguments to the call (again measured in ticks).Finally
ReactiveAssert.AreElementsEqualis used to verify thatOnNextwas called at time 20 as expected.The test verifies that calling
DoSomethingimmediately fires the observableSomethingHappened.