Measure and verify test execution time for a sample method
Preconditions (2)
✅ Expected Result: The test passes if the sample method executes within 1000 milliseconds, otherwise it fails
import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertTrue; public class ExecutionTimeTest { // Sample method to test public void sampleMethod() { // Simulate some work by sleeping for 500 milliseconds try { Thread.sleep(500); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } @Test public void testSampleMethodExecutionTime() { long startTime = System.nanoTime(); sampleMethod(); long endTime = System.nanoTime(); long durationInMillis = (endTime - startTime) / 1_000_000; assertTrue(durationInMillis <= 1000, "Execution time should be less than or equal to 1000 ms but was " + durationInMillis + " ms"); } }
This test measures how long sampleMethod() takes to run.
We use System.nanoTime() before and after the method call to get precise timing.
The difference is converted to milliseconds.
We then assert the duration is less than or equal to 1000 ms.
If the method runs longer, the test fails with a clear message.
This helps ensure performance expectations are met.
Now add data-driven testing to measure execution time for three different sample methods with varying sleep durations (200ms, 500ms, 800ms).
long start = System.nanoTime(); Thread.sleep(100); long end = System.nanoTime(); System.out.println((end - start) / 1_000_000 + " ms");
@Test
void testMethod() {
long start = System.nanoTime();
// test code
long end = System.nanoTime();
System.out.println(end - start);
}Pass the test and this pattern moves unknown