0
0
JUnittesting~10 mins

Test execution time analysis in JUnit - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to measure the execution time of a test method using System.nanoTime().

JUnit
long startTime = System.nanoTime();
// test code here
long endTime = System.nanoTime();
long duration = endTime - [1];
System.out.println("Execution time in nanoseconds: " + duration);
Drag options to blanks, or click blank then click option'
ASystem.currentTimeMillis()
BendTime
Cduration
DstartTime
Attempts:
3 left
💡 Hint
Common Mistakes
Subtracting endTime from startTime, which results in negative duration.
Using System.currentTimeMillis() instead of System.nanoTime() for both times.
2fill in blank
medium

Complete the code to annotate a JUnit 5 test method that measures execution time.

JUnit
@[1]
void testMethodExecutionTime() {
    // test code
}
Drag options to blanks, or click blank then click option'
ABeforeEach
BAfterEach
CTest
DDisabled
Attempts:
3 left
💡 Hint
Common Mistakes
Using @BeforeEach or @AfterEach instead of @Test.
Using @Disabled which disables the test.
3fill in blank
hard

Fix the error in the code that tries to assert the test execution time is less than 1 second.

JUnit
long duration = endTime - startTime;
assertTrue(duration [1] 1_000_000_000, "Test took too long");
Drag options to blanks, or click blank then click option'
A>
B<
C==
D>=
Attempts:
3 left
💡 Hint
Common Mistakes
Using > which would assert the test took longer than 1 second.
Using == which is too strict and unlikely.
4fill in blank
hard

Fill both blanks to correctly calculate and print the execution time in milliseconds.

JUnit
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);
Drag options to blanks, or click blank then click option'
A-
B/
C*
D+
Attempts:
3 left
💡 Hint
Common Mistakes
Multiplying instead of dividing by 1,000,000.
Adding instead of subtracting start from end.
5fill in blank
hard

Fill both blanks to create a map of test names to their execution times in milliseconds, filtering only tests longer than 100 ms.

JUnit
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"));
Drag options to blanks, or click blank then click option'
A>
B/
C*
D<
Attempts:
3 left
💡 Hint
Common Mistakes
Using < instead of > in filter.
Multiplying instead of dividing to convert units.