0
0
JUnittesting~5 mins

assertThrows for exceptions in JUnit - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is the purpose of assertThrows in JUnit?

assertThrows checks if a specific exception is thrown by a block of code during a test. It helps verify that error handling works as expected.

Click to reveal answer
beginner
How do you use assertThrows to test that a method throws IllegalArgumentException?
assertThrows(IllegalArgumentException.class, () -> {
    methodThatShouldThrow();
});

This runs methodThatShouldThrow() and passes if it throws IllegalArgumentException.

Click to reveal answer
intermediate
What does assertThrows return and how can it be used?

assertThrows returns the thrown exception object. You can use it to check the exception message or other properties.

Exception e = assertThrows(Exception.class, () -> { ... });
assertEquals("Error message", e.getMessage());
Click to reveal answer
intermediate
Why is assertThrows better than using try-catch in tests?

assertThrows makes tests cleaner and clearer by directly expressing the expected exception. It avoids manual try-catch blocks and reduces boilerplate code.

Click to reveal answer
beginner
Can assertThrows check for multiple exception types at once?

No, assertThrows checks for one specific exception type per call. To test multiple exceptions, write separate assertThrows calls for each.

Click to reveal answer
What does assertThrows verify in a JUnit test?
AThat no exceptions are thrown
BThat a specific exception is thrown
CThat a method returns true
DThat a method completes within time
Which of the following is the correct syntax to test for NullPointerException using assertThrows?
AassertThrows(() -> method(), NullPointerException.class);
BassertThrows(method(), NullPointerException.class);
CassertThrows(NullPointerException.class, () -> method());
DassertThrows(NullPointerException, method());
What can you do with the exception object returned by assertThrows?
ACheck its message or properties
BIgnore it
CChange its type
DThrow it again automatically
If the tested code does NOT throw the expected exception, what happens to the test with assertThrows?
AThe test fails
BThe test passes
CThe test is skipped
DThe test throws a runtime error
Is it possible to test multiple exceptions in one assertThrows call?
AYes, by using a wildcard exception
BYes, by listing exceptions separated by commas
CYes, by using an array of exceptions
DNo, test each exception separately
Explain how to use assertThrows to verify that a method throws an exception and how to check the exception message.
Think about how you write the lambda and what assertThrows returns.
You got /3 concepts.
    Describe why using assertThrows is preferred over try-catch blocks in JUnit tests.
    Consider readability and test clarity.
    You got /3 concepts.