0
0
JUnittesting~15 mins

Test execution time analysis in JUnit - Build an Automation Script

Choose your learning style9 modes available
Measure and verify test execution time for a sample method
Preconditions (2)
Step 1: Create a test method for the sample method
Step 2: Record the start time before calling the sample method
Step 3: Call the sample method
Step 4: Record the end time after the method call
Step 5: Calculate the elapsed time by subtracting start time from end time
Step 6: Assert that the elapsed time is less than or equal to 1000 milliseconds
✅ Expected Result: The test passes if the sample method executes within 1000 milliseconds, otherwise it fails
Automation Requirements - JUnit 5
Assertions Needed:
Assert that the execution time is less than or equal to 1000 milliseconds
Best Practices:
Use System.nanoTime() for precise time measurement
Use assertions from org.junit.jupiter.api.Assertions
Keep test methods small and focused
Avoid hardcoded sleep or waits in tests
Use descriptive test method names
Automated Solution
JUnit
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.

Common Mistakes - 4 Pitfalls
Using System.currentTimeMillis() instead of System.nanoTime()
Hardcoding Thread.sleep() in tests to simulate delays
Not converting nanoseconds to milliseconds for assertion
Not providing a clear assertion message
Bonus Challenge

Now add data-driven testing to measure execution time for three different sample methods with varying sleep durations (200ms, 500ms, 800ms).

Show Hint