Created
December 24, 2010 14:50
-
-
Save follesoe/754310 to your computer and use it in GitHub Desktop.
Unit testing event-based asynchronous code
This file contains hidden or 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
[Test] | |
public void TestCalculations() | |
{ | |
// A simple web service offering basic aritmetich operations | |
Service service = new Service(); | |
// Test data... | |
int a = 10; | |
int b = 10; | |
// Variables to track is a asyn call completed. | |
bool addCompleted = false; | |
bool substractCompleted = false; | |
// Used to signal the waiting test thread that a async operation have completed. | |
ManualResetEvent manualEvent = new ManualResetEvent(false); | |
// Async callback events are anonomous and are in the same scope as the test code, | |
// and therefore have access to the manualEvent variable. | |
service.AddCompleted += delegate(object sender, AddCompletedEventArgs args) | |
{ | |
// Some basic assertions on the code. | |
Assert.AreEqual(a + b, args.Result); | |
addCompleted = true; | |
// Signal the waiting NUnit thread that we're ready to move on. | |
manualEvent.Set(); | |
}; | |
service.SubstractCompleted += delegate(object sender, SubstractCompletedEventArgs args) | |
{ | |
Assert.AreEqual(a - b, args.Result); | |
substractCompleted = true; | |
manualEvent.Set(); | |
}; | |
// Call the add method asyncronous. | |
service.AddAsync(a, b); | |
// Block the current thread untill the callback event signals | |
// or the call times out (1500 ms). | |
manualEvent.WaitOne(1500, false); | |
// Check if we completed the async call, or fail the test if we timed out. | |
Assert.IsTrue(addCompleted); | |
// Set the event to non-signaled before making next async call. | |
manualEvent.Reset(); | |
service.SubstractAsync(a, b); | |
manualEvent.WaitOne(1500, false); | |
Assert.IsTrue(substractCompleted); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment