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