0
0
JUnittesting~5 mins

assertTimeout for performance in JUnit - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is assertTimeout used for in JUnit?

assertTimeout checks if a block of code finishes execution within a specified time limit. It helps test performance by ensuring methods run fast enough.

Click to reveal answer
beginner
How do you specify the time limit in assertTimeout?

You specify the time limit using a Duration object, like Duration.ofSeconds(2), which means the code must finish within 2 seconds.

Click to reveal answer
beginner
What happens if the code inside assertTimeout takes longer than the specified duration?

The test fails with a timeout exception, indicating the code did not meet the performance requirement.

Click to reveal answer
intermediate
Write a simple example of assertTimeout in JUnit to test a method processData() runs within 1 second.
assertTimeout(Duration.ofSeconds(1), () -> {
    processData();
});
Click to reveal answer
intermediate
Can assertTimeout return a value from the tested code block?

Yes, assertTimeout can return the result of the code block if you use the variant that returns a value, allowing further assertions on the result.

Click to reveal answer
What does assertTimeout(Duration.ofSeconds(2), () -> method()) check?
AMethod finishes within 2 seconds
BMethod throws an exception within 2 seconds
CMethod runs exactly 2 seconds
DMethod runs longer than 2 seconds
If the tested code exceeds the timeout in assertTimeout, what is the test result?
ATest passes
BTest is skipped
CTest fails
DTest retries automatically
Which Java class is used to specify the timeout duration in assertTimeout?
ADuration
BTimeUnit
CTimer
DTimeout
Can assertTimeout be used to test asynchronous code performance?
AYes, directly
BYes, but requires special handling
CNo, it only tests exceptions
DNo, it only works with synchronous code
What is the difference between assertTimeout and assertTimeoutPreemptively?
AOnly <code>assertTimeout</code> supports durations
B<code>assertTimeout</code> interrupts the code on timeout, <code>assertTimeoutPreemptively</code> waits
CBoth behave the same
D<code>assertTimeoutPreemptively</code> interrupts the code on timeout, <code>assertTimeout</code> waits
Explain how assertTimeout helps in performance testing with JUnit.
Think about how you check if a method runs fast enough.
You got /4 concepts.
    Describe the difference between assertTimeout and assertTimeoutPreemptively.
    One stops the code immediately, the other waits for it to finish.
    You got /4 concepts.