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 {

    public void method2() throws InterruptedException {

Test Class

package Package3;

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

public class Class1Test {
    private Class1 class1;

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

        public void testMethod1() throws InterruptedException {

        public void testMethod2() throws InterruptedException {

I want both methods in Class1 to complete within 600 milliseconds. So I annotate the corresponding test methods with the below annotation

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




Leave a Reply

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

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

Google photo

You are commenting using your Google 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 )

Connecting to %s