[ACCEPTED]-maven - fail build when unit test takes too long-build-process

Accepted answer
Score: 15

If all your tests extend some base class, I 8 think you can stick @Rule in there which will 7 apply to all the @Test in the child class.


import org.junit.rules.Timeout;
public abstract class BaseTestConfiguration {
    @Rule public Timeout testTimeout = new Timeout(60000); // 60k ms = 1 minute

public class ThingTests extends BaseTestConfiguration {
    public void testThis() {
        /*will fail if not done in 1 minute*/
    public void testThat() {
        /*will fail if not done in 1 minute*/

We 6 found this to be easiest rather than messing 5 with AspectJ or secret configuration directives. Devs 4 are more likely to figure out the Java parts 3 than all the secret XML this and that. You 2 can put @Before @After and any number of other junit 1 directives in the base class too.

Score: 7

In maven surefire, you can use forkedProcessTimeoutInSeconds, along with 4 forkMode=once.

This will kill the forked jvm if it takes 3 too long. If you want to do this per test, you 2 can forkMode=pertest or forkMode=always 1 (which does it for each class).

Score: 4

Why don't add a timeout on a per test basis. I 4 assume you're programming in Java, so in 3 JUnit you can do something like this:

 @Test(timeout=100) public void testQuickly()

If 2 the test doesn't end after 100 milliseconds, it 1 will fail.

Score: 1

Have you tried specifying the timeout for 7 the test through @Test(timeout=xx)? Find 6 the official api documentation here: http://junit.sourceforge.net/javadoc/org/junit/Test.html


You 5 can also consider using the timeout property 4 for the TestNg suite, you will have to move 3 all your tests to TestNg though, but this 2 will allow you to specify timeouts for groups.

This 1 is the official api documentation: http://testng.org/javadoc/org/testng/xml/XmlSuite.html#setTimeOut(java.lang.String)

Score: 0

I once had the same requirement, and since 3 I was using TestNG, I used the "group feature".

If you're 2 stuck with JUnit, try using the tests suite 1 (http://stackoverflow.com/questions/817135/grouping-junit-tests)

Score: 0

Try to use the junit Ant task with the timeout 3 parameter.


Another thing you can 2 do is to use aspectj with someting like 1 that:

public aspect TestTimeoutChecker {
    long TIMEOUT = 60000;

    pointcut invokeEvent() :
        execution(@Test * *(..));

    Object around() : invokeEvent() {

        long start = System.currentTimeMillis();
        Object object = proceed();
        long took = System.currentTimeMillis() - start;
        if (took > TIMEOUT) {
            throw new RuntimeException("timeout! it took:" + took);
        return object;

More Related questions