0
0
JUnittesting~5 mins

Test execution time analysis in JUnit

Choose your learning style9 modes available
Introduction

We measure how long tests take to run to find slow tests and improve speed.

When you want to know if a test is taking too long to run.
When you want to compare test speeds before and after code changes.
When you want to find tests that slow down your whole test suite.
When you want to optimize your testing process for faster feedback.
Syntax
JUnit
long startTime = System.currentTimeMillis();
// run test code
long endTime = System.currentTimeMillis();
long duration = endTime - startTime;

Use System.currentTimeMillis() to get the current time in milliseconds.

Subtract start time from end time to get how long the test took.

Examples
This prints how many milliseconds the test took.
JUnit
long startTime = System.currentTimeMillis();
// test logic here
long endTime = System.currentTimeMillis();
System.out.println("Test took " + (endTime - startTime) + " ms");
This JUnit test measures and prints its own execution time.
JUnit
@Test
void exampleTest() {
    long start = System.currentTimeMillis();
    assertEquals(4, 2 + 2);
    long end = System.currentTimeMillis();
    System.out.println("Execution time: " + (end - start) + " ms");
}
Sample Program

This test checks if 2 + 3 equals 5 and measures how long the test takes. It prints the time and asserts the time is not negative.

JUnit
import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.Test;

public class ExecutionTimeTest {

    @Test
    void testAdditionExecutionTime() {
        long startTime = System.currentTimeMillis();
        int result = 2 + 3;
        assertEquals(5, result);
        long endTime = System.currentTimeMillis();
        long duration = endTime - startTime;
        System.out.println("Test execution time: " + duration + " ms");
        assertTrue(duration >= 0, "Execution time should be zero or positive");
    }
}
OutputSuccess
Important Notes

Execution time can vary depending on your computer speed and workload.

Very fast tests may show 0 ms because of millisecond precision.

Use this method to find slow tests and improve them.

Summary

Measure test time by recording start and end times.

Use execution time to find and fix slow tests.

Print or log times to see test speed during runs.