Monday, February 2, 2009

How to impose a timeout in JUnit tests

Ever had the need to check if a method is taking too long to complete? You can follow the instinctive path, get the System.currentTimeMillis() before and after the execution of the method and assert their difference is smaller than the acceptable value.

Or... you can save time and rely on JUnit to stop the test thread and fail the test (a TimeoutException is thrown), simply passing the desired timeout value to the @Test annotation:
public void testWithTimeout() {

No comments: