Complete the code to measure the execution time of a test method using System.nanoTime().
long startTime = System.nanoTime(); // test code here long endTime = System.nanoTime(); long duration = endTime - [1]; System.out.println("Execution time in nanoseconds: " + duration);
The duration is calculated by subtracting the start time from the end time. So, duration = endTime - startTime; is correct.
Complete the code to annotate a JUnit 5 test method that measures execution time.
@[1]
void testMethodExecutionTime() {
// test code
}The @Test annotation marks a method as a test method in JUnit 5.
Fix the error in the code that tries to assert the test execution time is less than 1 second.
long duration = endTime - startTime; assertTrue(duration [1] 1_000_000_000, "Test took too long");
The assertion should check that the duration is less than 1 second (1,000,000,000 nanoseconds), so the operator is <.
Fill both blanks to correctly calculate and print the execution time in milliseconds.
long start = System.nanoTime(); // test code long end = System.nanoTime(); long durationMs = (end [1] start) [2] 1_000_000; System.out.println("Execution time in ms: " + durationMs);
First, subtract start from end to get duration in nanoseconds, then divide by 1,000,000 to convert to milliseconds.
Fill both blanks to create a map of test names to their execution times in milliseconds, filtering only tests longer than 100 ms.
Map<String, Long> slowTests = testTimes.entrySet().stream()
.filter(e -> e.getValue() [1] 100_000_000)
.collect(Collectors.toMap(
e -> e.getKey(),
e -> e.getValue() [2] 1_000_000,
(a, b) -> a,
LinkedHashMap::new));
slowTests.forEach((name, time) -> System.out.println(name + ": " + time + " ms"));Filter tests with execution time greater than 100 ms, then convert nanoseconds to milliseconds by dividing by 1,000,000.