Tuesday 6 July 2021

Junit5: Timeout: Specify timeout for a test method of all the test methods in a class

@Timeout is used to define a timeout for a method or all testable methods within one class and its @Nested classes.

 

Example

@Timeout(42)

@Timeout(value = 42, unit = MILLISECONDS)

 

Values must be in the following, case-insensitive format: <number> [ns|μs|ms|s|m|h|d]. The space between the number and the unit may be omitted. If you do not specify any unit, then it will be in seconds.

 

Value

Equivalent annotation

42

@Timeout(42)

42 ns

@Timeout(value = 42, unit = NANOSECONDS)

42 μs

@Timeout(value = 42, unit = MICROSECONDS)

42 ms

@Timeout(value = 42, unit = MILLISECONDS)

42 s 

@Timeout(value = 42, unit = SECONDS)

42 m 

@Timeout(value = 42, unit = MINUTES)

42 h 

@Timeout(value = 42, unit = HOURS)

42 d 

@Timeout(value = 42, unit = DAYS)

 

TimeoutTest.java

package com.sample.app;

import java.util.concurrent.TimeUnit;

import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.Timeout;

public class TimeoutTest {

  @Timeout(value = 3, unit = TimeUnit.SECONDS)
  @Test
  void successTest() throws InterruptedException {
    TimeUnit.SECONDS.sleep(2);
  }
  
  @Timeout(value = 3, unit = TimeUnit.SECONDS)
  @Test
  void failTest() throws InterruptedException {
    TimeUnit.SECONDS.sleep(20);
  }

}

@Timeout(value = 3, unit = TimeUnit.SECONDS)

@Test

void failTest() throws InterruptedException {

  TimeUnit.SECONDS.sleep(20);

}

 

As you see above snippet, I set the method ‘failTest’ to sleep for 20 seconds, but set the timeout for 3 seconds only. When this method unable to finish the test within 3 seconds, junit throws ‘TimeoutException’ and do not wait for 20 seconds.

java.util.concurrent.TimeoutException: failTest() timed out after 3 seconds
  at org.junit.jupiter.engine.extension.TimeoutInvocation.createTimeoutException(TimeoutInvocation.java:70)
  at org.junit.jupiter.engine.extension.TimeoutInvocation.proceed(TimeoutInvocation.java:59)
  at org.junit.jupiter.engine.extension.TimeoutExtension.intercept(TimeoutExtension.java:149)
  at org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestableMethod(TimeoutExtension.java:140)
  at org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestMethod(TimeoutExtension.java:84)
  at org.junit.jupiter.engine.execution.ExecutableInvoker$ReflectiveInterceptorCall.lambda$ofVoidMethod$0(ExecutableInvoker.java:115)

You can download all the applications from this link.

https://github.com/harikrishna553/junit5/tree/master/junit5-examples

 

  

Previous                                                    Next                                                    Home

No comments:

Post a Comment