Wednesday 4 July 2018

Junit: @Timeout rule: Time out for all unit tests

In my previous posts, I explained how to set time out for a specific unit test case using @Test annotation. Apart from this junit provides Timeout rule, it is used to set the timeout for all the test cases.

Example
@Rule
public Timeout globalTimeout = new Timeout(20, TimeUnit.MILLISECONDS);

Above statement sets the timeout to 20 milliseconds for all test cases.

TestApp.java
package com.sample.test;

import java.util.concurrent.TimeUnit;

import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.Timeout;

public class TestApp {
 @Rule
 public Timeout globalTimeout = new Timeout(20, TimeUnit.MILLISECONDS);

 @Test
 public void testCase1() throws InterruptedException {
  Thread.sleep(10);
 }
 
 @Test
 public void testCase2() throws InterruptedException {
  Thread.sleep(20);
 }
 
 @Test
 public void testCase3() throws InterruptedException {
  Thread.sleep(30);
 }
}

When you ran above application, you can observe testCase3 is failed in the report.



Previous                                                 Next                                                 Home

No comments:

Post a Comment