0
0
JUnittesting~5 mins

assertThrows usage 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 error handling.

Click to reveal answer
beginner
How do you write a basic assertThrows statement in JUnit 5?

Use assertThrows(ExceptionClass.class, () -> { /* code that throws */ }); to test if the exception occurs.

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

It returns the thrown exception object, allowing you to check its message or properties for more detailed assertions.

Click to reveal answer
intermediate
Why is assertThrows preferred over try-catch blocks in tests?

assertThrows makes tests cleaner and clearer by directly expressing the expected exception without manual try-catch handling.

Click to reveal answer
beginner
Can assertThrows be used to test checked and unchecked exceptions?

Yes, it works for both checked exceptions (like IOException) and unchecked exceptions (like NullPointerException).

Click to reveal answer
What is the correct way to use assertThrows to check for a NullPointerException?
AassertThrows(NullPointerException.class, () -> methodThatThrows());
BassertThrows(() -> methodThatThrows(), NullPointerException.class);
CassertThrows(methodThatThrows(), NullPointerException.class);
DassertThrows(NullPointerException, methodThatThrows());
What does assertThrows return after catching the exception?
AThe method return value
BA boolean true
CThe exception object thrown
DNothing (void)
Which of these is NOT a benefit of using assertThrows in tests?
AAutomatically fixes bugs
BDirectly checks for exceptions
CCleaner test code
DAvoids manual try-catch
Can assertThrows be used to test if no exception is thrown?
AYes, it passes if no exception is thrown
BYes, but only for checked exceptions
CNo, it ignores exceptions
DNo, it fails if no exception is thrown
Which JUnit version introduced assertThrows?
AJUnit 4
BJUnit 5
CJUnit 3
DJUnit 6
Explain how to use assertThrows to test that a method throws an IllegalArgumentException.
Think about the syntax: assertThrows(ExceptionClass.class, executable)
You got /3 concepts.
    Why is using assertThrows better than a try-catch block in JUnit tests?
    Consider how test code looks with and without assertThrows
    You got /4 concepts.