February 01, 2005Testing asynchronous codeA user recently submitted his problem on the TestNG mailing-list: he needed to send asynchronous messages (this part hardly ever failed) and then wanted to use TestNG to make sure that the response to these messages was well received. As I was considering adding asynchronous support to TestNG, it occurred to me that it was actually very easy to achieve:
private boolean m_success = false;
@Configuration(beforeTestClass = true)
public void sendMessage() {
// send the message, specify the callback
}
private void callback() {
// if we receive the correct result, m_success = true
}
@Test(timeOut = 10000)
public void waitForAnswer() {
while (! m_success) {
Thread.sleep(1000);
}
}
In this test, the message is sent as part of the initialization of the test with @Configuration, guaranteeing that this code will be executed before the test methods are invoked (and since we are specifying beforeTestClass = true, this code will only be executed once: when an instance of the test class is created). After this, TestNG will invoke the waitForAnswer() test method which will be doing some partially busy wait (tthis is just for clarity: messaging systems typically give you better ways to wait for the reception of a message). The loop will exit as soon as the callback has received the right message, but in order not to block TestNG forever, we specify a time-out in the @Test annotation. This code can be adapted to more sophisticated needs:
Comments
If you use Object.wait(long)/notify() instead of Thread.sleep(long), the test can complete without always waiting the full 1000 ms. You could also interrupt the thread, but the wait/notify approach is cleaner. Posted by: Bob Lee at February 2, 2005 09:03 AMIf you use Object.wait(long)/notify() instead of Thread.sleep(long), the test can complete without always waiting the full 1000 ms. You could also interrupt the thread, but the wait/notify approach is cleaner. Posted by: Bob Lee at February 2, 2005 09:37 AMEven better, use FutureTask. Posted by: Brian Goetz at February 17, 2005 12:59 PMPost a comment
|