Created
January 28, 2011 13:26
-
-
Save grumpydev/800251 to your computer and use it in GitHub Desktop.
Using Rx to help Async testing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// The class under test (a "device") has one background thread which monitors the (fake) serial port for incoming | |
// data and places it on a queue for a second background thread to pickup, process and respond to. | |
// | |
// Normally I'd have to test this with Thread.Sleep, which is not only ugly, but also slows down every test as the | |
// sleep time would have to be long enough so machines under heavy load didn't fail. | |
// | |
// With Rx I can setup an observable on my fake serial port "Data Written" event and tell it to wait up to 5 seconds | |
// to receive and event of the correct type. Then I can simply pull those chunks of data out of the enumerable | |
// it produces and assert on them as normal. | |
// | |
// Other than a little bit of Rx plumbing the test is pretty much the same as a non-async test would be, and still | |
// remains quite readable. | |
[TestMethod] | |
public void Device_Sends_Login_Confirm_Message_When_Handset_Sends_Login_Request_Message() | |
{ | |
var inputBytes = (byte[])(new HardwareMessage(MessageType.LoginRequest, 1, new Parameters() | |
{ | |
Parameter0 = 1, | |
Parameter1 = 2, | |
Parameter2 = 3, | |
})); | |
var dataWritten = (from evt in Observable.FromEvent<DataWrittenEventArgs>(_SerialPort, "DataWritten") | |
where ((HardwareMessage)evt.EventArgs.Data).MessageType == MessageType.ConfirmLogin | |
select evt.EventArgs.Data).Take(1).Timeout(new TimeSpan(0, 0, 5)); | |
_SerialPort.Buffer = inputBytes; | |
var output = dataWritten.ToEnumerable().ToArray(); | |
var hardwareMessage = (HardwareMessage)output[0]; | |
Assert.AreEqual(MessageType.ConfirmLogin, hardwareMessage.MessageType); // Do any assertions required | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment