Bird
Raised Fist0
JUnittesting~20 mins

assertTimeout for performance in JUnit - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Timeout Mastery Badge
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
What is the result of this JUnit test using assertTimeout?
Consider the following JUnit 5 test code snippet. What will be the test execution result?
JUnit
import static org.junit.jupiter.api.Assertions.assertTimeout;
import java.time.Duration;
import org.junit.jupiter.api.Test;

public class PerformanceTest {
    @Test
    void testFastOperation() {
        assertTimeout(Duration.ofMillis(100), () -> {
            Thread.sleep(50);
        });
    }
}
ATest fails because the operation exceeds the 100 milliseconds timeout.
BTest fails because Thread.sleep throws InterruptedException.
CTest passes because the operation completes within 100 milliseconds.
DTest is skipped due to missing @Timeout annotation.
Attempts:
2 left
💡 Hint
assertTimeout checks if the code block finishes within the given duration.
❓ assertion
intermediate
2:00remaining
Which assertion correctly fails if the code block exceeds 200 milliseconds?
You want to fail a test if a code block takes longer than 200 milliseconds. Which JUnit assertion achieves this?
AassertTimeoutPreemptively(Duration.ofMillis(200), () -> { Thread.sleep(250); });
BassertTimeout(Duration.ofMillis(200), () -> { Thread.sleep(100); });
CassertTimeout(Duration.ofMillis(200), () -> { Thread.sleep(150); });
DassertTimeoutPreemptively(Duration.ofMillis(200), () -> { Thread.sleep(150); });
Attempts:
2 left
💡 Hint
assertTimeoutPreemptively interrupts the code if it exceeds the timeout.
🔧 Debug
advanced
2:00remaining
Why does this assertTimeout test fail even if the code is slow?
Analyze the following test code and explain why it fails, even if the code block takes longer than 1 second.
JUnit
import static org.junit.jupiter.api.Assertions.assertTimeout;
import java.time.Duration;
import org.junit.jupiter.api.Test;

public class SlowTest {
    @Test
    void testSlowOperation() {
        assertTimeout(Duration.ofSeconds(1), () -> {
            Thread.sleep(1500);
        });
    }
}
AassertTimeoutPreemptively should be used to fail immediately on timeout, not assertTimeout.
BassertTimeout waits for the code to finish and then checks duration, so test fails after completion.
CThread.sleep throws an exception that is caught by assertTimeout, so test passes.
DThe test is missing @Timeout annotation, so timeout is ignored.
Attempts:
2 left
💡 Hint
assertTimeout waits for the code block to finish before checking the elapsed time and fails if it exceeds the timeout.
🧠 Conceptual
advanced
2:00remaining
What is the key difference between assertTimeout and assertTimeoutPreemptively in JUnit?
Choose the statement that best describes the difference between assertTimeout and assertTimeoutPreemptively.
AassertTimeout waits for the code block to finish before checking timeout; assertTimeoutPreemptively interrupts the code if timeout is exceeded.
BassertTimeoutPreemptively waits for completion; assertTimeout interrupts the code on timeout.
CBoth assertions behave the same and do not interrupt the code block.
DassertTimeoutPreemptively only works with asynchronous code; assertTimeout works with synchronous code.
Attempts:
2 left
💡 Hint
One assertion interrupts the code on timeout, the other does not.
❓ framework
expert
3:00remaining
How to correctly use assertTimeoutPreemptively with a method that throws checked exceptions?
Given a method that throws InterruptedException, which is the correct way to use assertTimeoutPreemptively in JUnit 5 to test its performance?
JUnit
public void longRunningMethod() throws InterruptedException {
    Thread.sleep(300);
}
AassertTimeoutPreemptively(Duration.ofMillis(500), () -> longRunningMethod());
BassertTimeoutPreemptively(Duration.ofMillis(500), () -> { longRunningMethod(); });
CassertTimeoutPreemptively(Duration.ofMillis(500), () -> { longRunningMethod() throws InterruptedException; });
DassertTimeoutPreemptively(Duration.ofMillis(500), () -> { try { longRunningMethod(); } catch (InterruptedException e) { throw new RuntimeException(e); } });
Attempts:
2 left
💡 Hint
Checked exceptions must be handled or declared in lambda expressions.

Practice

(1/5)
1. What is the main purpose of assertTimeout in JUnit testing?
easy
A. To test if exceptions are thrown correctly
B. To check if a block of code finishes execution within a specified time limit
C. To verify the correctness of output values
D. To compare two objects for equality

Solution

  1. Step 1: Understand the role of assertTimeout

    assertTimeout is used to ensure that a piece of code completes within a given time limit.
  2. Step 2: Differentiate from other assertions

    Other assertions check correctness or exceptions, but assertTimeout focuses on performance timing.
  3. Final Answer:

    To check if a block of code finishes execution within a specified time limit -> Option B
  4. Quick Check:

    assertTimeout checks execution time = C [OK]
Hint: assertTimeout checks speed, not correctness or exceptions [OK]
Common Mistakes:
  • Confusing assertTimeout with assertEquals
  • Thinking assertTimeout checks output correctness
  • Assuming assertTimeout tests exception throwing
2. Which of the following is the correct syntax to use assertTimeout in JUnit 5 to test a method processData() with a 2-second limit?
easy
A. assertTimeout(Duration.ofSeconds(2), () -> processData());
B. assertTimeout(2, processData());
C. assertTimeout(2000, () -> processData());
D. assertTimeout(Duration.seconds(2), processData());

Solution

  1. Step 1: Recall correct Duration usage

    JUnit 5 uses Duration.ofSeconds(2) to specify 2 seconds.
  2. Step 2: Confirm lambda syntax

    The code block must be passed as a lambda: () -> processData().
  3. Final Answer:

    assertTimeout(Duration.ofSeconds(2), () -> processData()); -> Option A
  4. Quick Check:

    Duration.ofSeconds + lambda = A [OK]
Hint: Use Duration.ofSeconds and lambda for assertTimeout [OK]
Common Mistakes:
  • Passing method call directly instead of lambda
  • Using integer instead of Duration object
  • Wrong Duration method like Duration.seconds
3. Given the code below, what will be the test result?
assertTimeout(Duration.ofMillis(500), () -> {
    Thread.sleep(300);
    Thread.sleep(250);
});
medium
A. Test passes because total sleep is 550ms which is less than 500ms
B. Test passes because each sleep is less than 500ms
C. Test fails because total sleep is 550ms which exceeds 500ms
D. Test fails due to syntax error in lambda

Solution

  1. Step 1: Calculate total sleep time

    Thread sleeps 300ms + 250ms = 550ms total.
  2. Step 2: Compare with timeout limit

    Timeout is 500ms, so 550ms exceeds the limit causing failure.
  3. Final Answer:

    Test fails because total sleep is 550ms which exceeds 500ms -> Option C
  4. Quick Check:

    Total sleep 550ms > 500ms timeout = B [OK]
Hint: Sum all delays and compare to timeout [OK]
Common Mistakes:
  • Ignoring cumulative sleep time
  • Assuming each sleep is checked separately
  • Thinking test passes if individual sleeps are under limit
4. Identify the error in this JUnit 5 test using assertTimeout:
assertTimeout(Duration.ofSeconds(1), processData());
medium
A. processData() must return a boolean
B. Duration.ofSeconds should be Duration.seconds
C. assertTimeout requires a timeout in milliseconds
D. Missing lambda expression to defer execution

Solution

  1. Step 1: Check how code block is passed

    assertTimeout expects a lambda or executable to delay running until assertion.
  2. Step 2: Identify missing lambda

    Here, processData() is called immediately, not deferred by lambda.
  3. Final Answer:

    Missing lambda expression to defer execution -> Option D
  4. Quick Check:

    assertTimeout needs lambda to delay execution = A [OK]
Hint: Always wrap code in lambda for assertTimeout [OK]
Common Mistakes:
  • Calling method directly instead of lambda
  • Using wrong Duration method
  • Expecting assertTimeout to accept milliseconds as int
5. You want to test a method calculate() that sometimes takes longer but should not exceed 3 seconds. Which approach correctly uses assertTimeout to fail the test if calculate() exceeds 3 seconds, and also returns the method's result for further checks?
hard
A. var result = assertTimeout(Duration.ofSeconds(3), () -> { return calculate(); });
B. assertTimeout(Duration.ofSeconds(3), () -> { calculate(); });
C. assertTimeout(Duration.ofSeconds(3), () -> { return calculate(); });
D. var result = assertTimeout(Duration.ofSeconds(3), calculate());

Solution

  1. Step 1: Understand assertTimeout return value

    assertTimeout returns the value from the lambda if it completes in time.
  2. Step 2: Use lambda with return and assign result

    To capture calculate() result, lambda must return it and assign to a variable.
  3. Step 3: Check syntax correctness

    var result = assertTimeout(Duration.ofSeconds(3), () -> { return calculate(); }); uses lambda with return and assigns to result, matching requirements.
  4. Final Answer:

    var result = assertTimeout(Duration.ofSeconds(3), () -> { return calculate(); }); -> Option A
  5. Quick Check:

    Return value + assign result + timeout = D [OK]
Hint: Use lambda with return and assign to capture result [OK]
Common Mistakes:
  • Not returning value inside lambda
  • Not assigning assertTimeout result
  • Using lambda without return for non-void methods
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard