0
0
JUnittesting~5 mins

assertTimeout for performance in JUnit

Choose your learning style9 modes available
Introduction

We use assertTimeout to check if a piece of code finishes running within a set time. This helps us make sure our program is fast enough.

When you want to make sure a search function returns results quickly.
When testing if loading a page or data happens fast enough.
When checking if a calculation or process does not take too long.
When you want to avoid slow responses that can frustrate users.
Syntax
JUnit
assertTimeout(Duration.ofSeconds(timeoutInSeconds), () -> {
    // code to test
});

Duration.ofSeconds() sets the maximum allowed time.

The code to test goes inside the lambda () -> { }.

Examples
This test passes because the code sleeps only 1 second, less than 2 seconds allowed.
JUnit
assertTimeout(Duration.ofSeconds(2), () -> {
    Thread.sleep(1000);
});
Checks if the code runs within 500 milliseconds.
JUnit
assertTimeout(Duration.ofMillis(500), () -> {
    // some fast code
});
Sample Program

The first test passes because it finishes in 1 second (less than 2 seconds).

The second test fails because it takes 1.5 seconds, which is more than 1 second allowed.

JUnit
import static org.junit.jupiter.api.Assertions.assertTimeout;
import java.time.Duration;
import org.junit.jupiter.api.Test;

public class PerformanceTest {

    @Test
    void testFastMethod() throws InterruptedException {
        assertTimeout(Duration.ofSeconds(2), () -> {
            // Simulate fast task
            Thread.sleep(1000);
        });
    }

    @Test
    void testSlowMethod() throws InterruptedException {
        assertTimeout(Duration.ofSeconds(1), () -> {
            // Simulate slow task
            Thread.sleep(1500);
        });
    }
}
OutputSuccess
Important Notes

assertTimeout checks the total time the code takes to run.

If the code takes longer than the set time, the test fails.

Use Duration.ofMillis() or Duration.ofSeconds() to set time limits.

Summary

assertTimeout helps test if code runs fast enough.

It fails the test if the code takes too long.

Use it to keep your program responsive and efficient.