8.5 Creating a Timed Test for Varying Loads

8.5.1 Problem

You need to test throughput under varying load conditions.

8.5.2 Solution

Decorate your JUnit Test with a JUnitPerf LoadTest to simulate one or more concurrent users, and decorate the load test with a JUnitPerf TimedTest to test the performance of the load.

8.5.3 Discussion

So far we have seen how to create timed and load tests for existing JUnit tests. Now, let's delve into how JUnitPerf can test that varying loads do not impede performance. Specifically, we want to test that the application does not screech to a halt as the number of users increases. The design of JUnitPerf allows us to accomplish this task with ease. Example 8-3 shows how.

Example 8-3. Load and performance testing
package com.oreilly.javaxp.junitperf;

import junit.framework.Test;
import junit.framework.TestSuite;
import com.clarkware.junitperf.*;

public class TestPerfSearchModel {

    public static Test suite(  ) {
        Test testCase = new TestSearchModel("testAsynchronousSearch");
        Test loadTest = new LoadTest(testCase, 100);
        Test timedTest = new TimedTest(loadTest, 3000, false);

        TestSuite suite = new TestSuite(  );
        return suite;
    public static void main(String args[]) {
        junit.textui.TestRunner.run(suite(  ));

Remember that JUnitPerf was designed using the decorator pattern. Thus, we are able to decorate tests with other tests. This example decorates a JUnit test with a JUnitPerf load test. The load test is then decorated with a JUnitPerf timed test. Ultimately, the test executes 100 simultaneous users performing an asynchronous search and tests that it completes in less than 3 seconds. In other words, we are testing that the search algorithm handles 100 simultaneous searches in less than three seconds.

8.5.4 See Also

Recipe 8.3 shows how to create a JUnitPerf TimedTest. Recipe 8.4 shows how to create a JUnitPerf LoadTest. Recipe 8.6 shows how to write a stress test. Recipe 8.7 shows how to use Ant to execute JUnitPerf tests.