Wednesday, February 17, 2010

Unittesting an asynchronous process with a latch

This week I wanted to write some tests to test the correct handling of a JMS message. The first service method was easy because the service send a reply, so I could check the reply to see if the message was handled and if the handling was correct. But the second service method was more difficult, because the service did not send a reply. Mmm ... how can you unittest an asynchronous process?

I googled a bit and found a reference to a CountDownLatch. Apparently a Java 5 Concurrency class. Looking at the source of this class, I thought it was something I could use, but of course I wanted to have the result of the async method available in the test so I can verify the result. In the API of the AbstractQueuedSynchronizer, which is used by the CountDownLatch, is a BooleanLatch example which looked like a good starting point for what I needed. From this example I created a FunctionResultLatch.