0
0
JUnittesting~5 mins

Checking exception type hierarchy in JUnit - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What does it mean to check exception type hierarchy in testing?
It means verifying that the thrown exception is of the expected type or a subtype, ensuring the test catches the correct error class.
Click to reveal answer
beginner
How can you check for a specific exception type in JUnit 5?
Use the assertThrows method with the expected exception class and a lambda that runs the code that should throw the exception.
Click to reveal answer
intermediate
Why is it important to check the exception type hierarchy rather than just the base exception?
Because catching only the base exception might hide specific errors; checking the exact type or subtype ensures precise error handling and test accuracy.
Click to reveal answer
intermediate
Example: What exception type will assertThrows catch if the thrown exception is a subclass of the expected exception?
assertThrows will pass if the thrown exception is the expected type or any subclass of it, because it checks the exception type hierarchy.
Click to reveal answer
beginner
How to write a JUnit 5 test that verifies a method throws IOException or any subclass of IOException?
Use assertThrows(IOException.class, () -> methodThatThrows()); This passes if the thrown exception is IOException or any subclass like FileNotFoundException.
Click to reveal answer
In JUnit 5, which method is used to check if a specific exception or its subclass is thrown?
AassertTrue
BassertEquals
CassertThrows
DassertNull
If a method throws FileNotFoundException, which is a subclass of IOException, what happens when you assertThrows(IOException.class, ...)?
ATest fails because exception types must match exactly
BTest fails because IOException is a superclass
CTest passes only if FileNotFoundException is caught explicitly
DTest passes because FileNotFoundException is a subclass of IOException
Why should you avoid catching only the base Exception class in tests?
AIt can hide specific exceptions and make tests less precise
BIt makes tests run slower
CIt causes syntax errors
DIt is required to catch only base Exception
Which JUnit 5 feature helps you check the exception message along with the type?
AassertTrue
BassertThrows returns the exception object for further checks
CassertEquals
DassertNull
What happens if the tested code does not throw any exception but assertThrows expects one?
AThe test fails because no exception was thrown
BThe test passes
CThe test is skipped
DThe test throws a compilation error
Explain how to use JUnit 5 to check that a method throws a specific exception or any of its subclasses.
Think about how assertThrows works with exception types.
You got /4 concepts.
    Why is it important to consider exception type hierarchy when writing tests for exceptions?
    Consider how Java exception classes relate to each other.
    You got /4 concepts.