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 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access