Setting timeout for test methods

Junit offers us the option to set timeout for test methods. If a test methods doesnt complete within specified time limit, an exception is thrown failing the test case. The use case scenario where this
feature can be used is for example testing the performance of a method. The below code shows you how to use this feature.

Class to be tested


package Package3;

public class Class1 {
    public void method1() throws InterruptedException {
        Thread.sleep(500);
    }

    public void method2() throws InterruptedException {
        Thread.sleep(1000);
    }
}

Test Class


package Package3;

import org.junit.Before;
import org.junit.Test;

public class Class1Test {
    private Class1 class1;

    @Before
    public void setUp() {
        this.class1 = new Class1();
    }

    @Test(timeout=600)
        public void testMethod1() throws InterruptedException {
        class1.method1();
    }

    @Test(timeout=600)
        public void testMethod2() throws InterruptedException {
        class1.method2();
    }
}

I want both methods in Class1 to complete within 600 milliseconds. So I annotate the corresponding test methods with the below annotation
@Test(timeout=600)

But method2 takes more than 600 milliseconds to complete as a result an exception is thrown. Below is the screenshot of the result.

Untitled

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s