Creating a Timed Test

Problem

You need to make sure that code executes within a given amount of time.

Solution

Decorate an existing JUnit Test with a JUnitPerf TimedTest.

Discussion

A TimedTest is a JUnit test decorator that measures the total elapsed time of a JUnit test and fails if the maximum time allowed is exceeded. A timed test tests time-critical code, such as a sort or search.

A TimedTest is constructed with an instance of a JUnit test, along with the maximum allowed execution time in milliseconds. Here is an example of a timed test that fails if the elapsed time of the TestSearchModel.testAsynchronousSearch( ) method exceeds two seconds:

public static Test suite(  ) {
    Test testCase = new TestSearchModel("testAsynchronousSearch");
    Test timedTest = new TimedTest(testCase, 2000);
    TestSuite suite = new TestSuite(  );
    suite.addTest(timedTest);
    return suite;
}

In the example above, the total elapsed time is checked once the method under test completes. If the total time exceeds two seconds, the test fails. Another option is for the test to fail immediately if the maximum allowed execution time is exceeded. Here is an example of a timed test that causes immediate failure:

public static Test suite(  ) {
    Test testCase = new TestSearchModel("testAsynchronousSearch");
    Test timedTest = new TimedTest(testCase, 2000, false);
    TestSuite suite = new TestSuite(  );
    suite.addTest(timedTest);
    return suite;
}

The constructor in the previous example is overloaded to allow for a third parameter. This parameter ...

Get Java Extreme Programming Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.