O'Reilly logo

Java Extreme Programming Cookbook by Brian M. Coyner, Eric M. Burke

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required