Simple performance testing with Spring

May 18, 2010

Spring's @Timed annotation provides a convenient way to write JUnit tests which fail if they take too long. Consider the example Adder class:

Adder.java:

public class Adder {

    public int add(int num1, int num2) {
        return num1 + num2;
    }

    public int addSlowly(int num1, int num2) throws InterruptedException {
        Thread.sleep(100);
        return num1 + num2;
    }
}

This class is tested using the TimedTest and associated Spring context:

TimedTest.java:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
public class TimedTest {

    @Autowired
    Adder adder;

    @Test
    @Timed(millis = 10)
    public void testAdd() {
        assertEquals(42, adder.add(40, 2));
    }

    @Test
    @Timed(millis = 10)
    public void testAddSlowly() throws InterruptedException {
        assertEquals(42, adder.addSlowly(40, 2));
    }
}

TimedTest-context.xml:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

    <bean class="Adder" />

</beans>

In TimedTest, the testAddSlowly() test will take over 100 ms to execute. It is annotated with @Timed(millis = 10), which will cause the test to fail if it takes over 10 ms to execute.

Spring's @Timed annotation is similar in behavior to JUnit's @Test(timeout=...) configuration, but differs in that it times the total execution time of a test, including set up, tear down, and applicable repetition.