Bird
Raised Fist0
JUnittesting~20 mins

assertThrows usage in JUnit - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
AssertThrows Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
What is the output of this JUnit test using assertThrows?
Consider the following JUnit 5 test method. What will be the result of running this test?
JUnit
import static org.junit.jupiter.api.Assertions.assertThrows;
import org.junit.jupiter.api.Test;

class Calculator {
    int divide(int a, int b) {
        return a / b;
    }
}

public class CalculatorTest {
    @Test
    void testDivideByZero() {
        Calculator calc = new Calculator();
        assertThrows(ArithmeticException.class, () -> calc.divide(10, 0));
    }
}
ATest passes because ArithmeticException is thrown as expected.
BTest fails because no exception is thrown.
CTest fails with a compilation error due to wrong assertThrows usage.
DTest passes but throws NullPointerException instead.
Attempts:
2 left
💡 Hint
Remember assertThrows expects the exception class and a lambda that triggers the exception.
❓ assertion
intermediate
2:00remaining
Which assertThrows usage correctly verifies NullPointerException?
You want to test that calling method process(null) throws NullPointerException. Which option uses assertThrows correctly?
JUnit
class Processor {
    void process(String input) {
        if (input == null) throw new NullPointerException("Input is null");
    }
}
AassertThrows(() -> processor.process(null), NullPointerException.class);
BassertThrows(NullPointerException.class, () -> processor.process(null));
CassertThrows(NullPointerException.class, processor.process(null));
DassertThrows(NullPointerException.class, () -> processor.process());
Attempts:
2 left
💡 Hint
assertThrows takes the exception class first, then a lambda expression.
🔧 Debug
advanced
2:00remaining
Why does this assertThrows test fail to catch the exception?
Examine the test below. Why does it fail even though divide(10, 0) throws ArithmeticException?
JUnit
import static org.junit.jupiter.api.Assertions.assertThrows;
import org.junit.jupiter.api.Test;

class Calculator {
    int divide(int a, int b) {
        return a / b;
    }
}

public class CalculatorTest {
    @Test
    void testDivideByZero() {
        Calculator calc = new Calculator();
        assertThrows(ArithmeticException.class, calc.divide(10, 0));
    }
}
AThe test fails because assertThrows requires a try-catch block inside.
BThe test fails because ArithmeticException is not thrown by divide method.
CThe test fails because the exception class is incorrect.
DThe test fails because assertThrows expects a lambda, but a method call is passed instead.
Attempts:
2 left
💡 Hint
Check the second argument to assertThrows carefully.
🧠 Conceptual
advanced
2:00remaining
What does assertThrows return and how can it be used?
In JUnit 5, assertThrows returns the caught exception. How can this feature be used in tests?
ATo verify exception message or properties by inspecting the returned exception object.
BTo suppress the exception so the test continues without failure.
CTo automatically retry the test if the exception is thrown.
DTo convert checked exceptions into unchecked exceptions.
Attempts:
2 left
💡 Hint
Think about why you might want to keep the exception object after catching it.
❓ framework
expert
2:00remaining
Which assertThrows usage correctly tests a checked exception in a method?
Given a method that throws IOException, which assertThrows usage correctly tests it?
JUnit
import java.io.IOException;

class FileReader {
    void readFile(String path) throws IOException {
        if (path == null) throw new IOException("Path is null");
    }
}
AassertThrows(IOException.class, () -> fileReader.readFile(null));
BassertThrows(IOException.class, () -> fileReader.readFile(null)); // with throws declaration on test method
CassertThrows(IOException.class, () -> { fileReader.readFile(null); });
DassertThrows(IOException.class, () -> fileReader.readFile(null)); // without throws declaration on test method
Attempts:
2 left
💡 Hint
Checked exceptions must be handled or declared. Lambdas in assertThrows must handle checked exceptions properly.

Practice

(1/5)
1. What is the primary purpose of assertThrows in JUnit testing?
easy
A. To check if a specific exception is thrown by a code block
B. To verify the return value of a method
C. To measure the execution time of a method
D. To assert that no exceptions are thrown

Solution

  1. Step 1: Understand the role of assertThrows

    assertThrows is used to test if a particular exception occurs when running a piece of code.
  2. Step 2: Compare with other assertions

    Other assertions check values or states, but assertThrows specifically checks for exceptions.
  3. Final Answer:

    To check if a specific exception is thrown by a code block -> Option A
  4. Quick Check:

    assertThrows = Exception check [OK]
Hint: assertThrows checks exceptions thrown by code [OK]
Common Mistakes:
  • Confusing assertThrows with assertEquals
  • Using assertThrows to check return values
  • Expecting assertThrows to measure performance
2. Which of the following is the correct syntax to use assertThrows in JUnit 5?
easy
A. assertThrows(Exception.class, () -> methodCall());
B. assertThrows(() -> methodCall(), Exception.class);
C. assertThrows(methodCall(), Exception.class);
D. assertThrows(Exception.class, methodCall());

Solution

  1. Step 1: Recall assertThrows method signature

    The correct syntax is assertThrows(Exception.class, Executable) where Executable is a lambda or method reference.
  2. Step 2: Analyze options

    assertThrows(Exception.class, () -> methodCall()); matches the correct syntax: exception class first, then lambda expression.
  3. Final Answer:

    assertThrows(Exception.class, () -> methodCall()); -> Option A
  4. Quick Check:

    assertThrows(Exception.class, lambda) = correct syntax [OK]
Hint: Exception class first, then lambda in assertThrows [OK]
Common Mistakes:
  • Swapping parameters order
  • Passing method call instead of lambda
  • Omitting lambda expression
3. What will be the result of this JUnit 5 test code?
assertThrows(IllegalArgumentException.class, () -> {
  throw new IllegalArgumentException("Invalid argument");
});
medium
A. Test passes but ignores the exception message
B. Test fails because no exception is thrown
C. Test fails due to a syntax error
D. Test passes because the expected exception is thrown

Solution

  1. Step 1: Check the exception thrown

    The lambda throws IllegalArgumentException, which matches the expected exception class.
  2. Step 2: Understand assertThrows behavior

    assertThrows passes if the expected exception is thrown during execution.
  3. Final Answer:

    Test passes because the expected exception is thrown -> Option D
  4. Quick Check:

    Thrown exception matches expected = pass [OK]
Hint: assertThrows passes if expected exception is thrown [OK]
Common Mistakes:
  • Thinking test fails if exception is thrown
  • Confusing exception message with test result
  • Assuming syntax error without checking code
4. Identify the error in this JUnit 5 test snippet:
assertThrows(NullPointerException.class, () -> {
  String s = null;
  s.length();
});
medium
A. Exception class should be RuntimeException.class
B. Lambda syntax is incorrect
C. No error; test will pass as NullPointerException is thrown
D. s.length() does not throw NullPointerException

Solution

  1. Step 1: Analyze the code inside lambda

    Calling s.length() on a null string throws NullPointerException.
  2. Step 2: Check assertThrows parameters

    Expected exception is NullPointerException.class, matching the thrown exception.
  3. Final Answer:

    No error; test will pass as NullPointerException is thrown -> Option C
  4. Quick Check:

    NullPointerException thrown and expected = pass [OK]
Hint: NullPointerException thrown matches expected exception [OK]
Common Mistakes:
  • Assuming s.length() throws different exception
  • Thinking lambda syntax is wrong
  • Confusing exception class with superclass
5. Consider this test method:
void testDivideByZero() {
  ArithmeticException thrown = assertThrows(ArithmeticException.class, () -> {
    int result = 10 / 0;
  });
  assertEquals("/ by zero", thrown.getMessage());
}

What does this test verify beyond just exception throwing?
hard
A. It verifies the method returns zero
B. It verifies the exception message is exactly "/ by zero"
C. It verifies no exception is thrown
D. It verifies the exception type is RuntimeException

Solution

  1. Step 1: Understand assertThrows return value

    assertThrows returns the thrown exception object, here stored in thrown.
  2. Step 2: Analyze the assertEquals check

    The test checks that the exception message equals "/ by zero", verifying the exact error message.
  3. Final Answer:

    It verifies the exception message is exactly "/ by zero" -> Option B
  4. Quick Check:

    Exception message checked = It verifies the exception message is exactly "/ by zero" [OK]
Hint: assertThrows returns exception to check message [OK]
Common Mistakes:
  • Thinking it checks return value of division
  • Assuming exception type is RuntimeException
  • Ignoring the message assertion
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