Reputation: 361
Currently, I'm writing some integration tests and I need to assert that a call to a method blocked the calling thread for at least x seconds. The thing is I have method that will block forever and I need to assert that it has been blocked for at least x seconds. Is there any way to do that? The only other answer is about JUnit4 and we are using JUnit 5... In advance thank you for your answer.
Upvotes: 2
Views: 1184
Reputation: 361
In the end, I opted for a different strategy. You see my use case is to test if some JDBC Postgres transactions would block. Instead, I'll just wait that the transaction timeout to kick in and assert the time between the beginning of my test and when the timeout triggered. Thank you all for taking some valuable time to answer my question.
Upvotes: 0
Reputation: 376
You can use assertTimeout(Duration timeout, Executable executable)
for your problem. For more info, you should visit JUnit 5 User Guide.
@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), AssertionsDemo::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);
});
}
@Test
void timeoutExceededWithPreemptiveTermination() {
// The following assertion fails with an error message similar to:
// execution timed out after 10 ms
assertTimeoutPreemptively(ofMillis(10), () -> {
// Simulate task that takes more than 10 ms.
new CountDownLatch(1).await();
});
}
Upvotes: 4