In this article, we will learn about assertTimeout() static method which belongs to JUnit 5 org.junit.jupiter.api.Assertions Class. Note that in JUnit 5 all JUnit 4 assertion methods are moved to org.junit.jupiter.api.Assertions class.
There are many overloaded version of assertTimeout() methods present in org.junit.jupiter.api.Assertions class.
Let me list out tools and technologies that I have used to develop JUnit 5 assertTimeout Example.
Tools and Technologies Used
- Eclipse photon (only this eclipse version supports JUnit 5)
- Maven
- JUnit 5
- JDK 8 or later
assertTimeout(Duration timeout, ThrowingSupplier supplier) method asserts that execution of the supplied supplier completes before the given timeout is exceeded.
assertTimeout Method Example
package com.javaguides.junit5.assertions;
import static org.junit.Assert.assertEquals;
import static java.time.Duration.ofMillis;
import static java.time.Duration.ofMinutes;
import static org.junit.jupiter.api.Assertions.assertTimeout;
import org.junit.jupiter.api.Test;
/**
* JUnit5AssertTimeOutExample
* @author javaguides.net
*
*/
public class JUnit5AssertTimeOutExample {
private static String greeting() {
return "Hello, World!";
}
@Test
void timeoutNotExceeded() {
// The following assertion succeeds.
assertTimeout(ofMinutes(2), () -> {
// Perform task that takes less than 2 minutes.
});
}
@Test
void timeoutNotExceededWithResult() {
// The following assertion succeeds, and returns the supplied object.
String actualResult = assertTimeout(ofMinutes(2), () -> {
return "a result";
});
assertEquals("a result", actualResult);
}
@Test
void timeoutNotExceededWithMethod() {
// The following assertion invokes a method reference and returns an object.
String actualGreeting = assertTimeout(ofMinutes(2), JUnit5AssertTimeOutExample::greeting);
assertEquals("Hello, World!", actualGreeting);
}
@Test
void timeoutExceeded() {
// The following assertion fails with an error message similar to:
// execution exceeded timeout of 10 ms by 91 ms
assertTimeout(ofMillis(10), () -> {
// Simulate task that takes more than 10 ms.
Thread.sleep(100);
});
}
}
Output
Reference
https://junit.org/junit5/docs/current/api/org/junit/jupiter/api/Assertions.html
Comments
Post a comment