What if you could catch every error your code throws without watching it yourself?
Why assertThrows for exceptions in JUnit? - Purpose & Use Cases
Imagine you have a program that should stop and show an error when something goes wrong, like dividing by zero. You try to check this by running the program and watching carefully if it crashes. You do this again and again for every little mistake.
Doing this by hand is slow and easy to miss errors. You might forget to check some cases or not notice the exact error. It's like trying to catch a small bug in a big messy room without a flashlight.
The assertThrows method in JUnit helps you catch these errors automatically. It runs the code and checks if the right error happens. If it does, the test passes. If not, it fails. This saves time and makes sure you never miss a problem.
try { divide(5, 0); fail("Expected exception not thrown"); } catch (ArithmeticException e) { // test passes }
assertThrows(ArithmeticException.class, () -> divide(5, 0));
It lets you quickly and clearly check that your program handles errors correctly, making your code safer and more reliable.
For example, when building a calculator app, you want to be sure it stops and warns users if they try to divide by zero. Using assertThrows tests this automatically every time you change the code.
Manual error checking is slow and easy to miss mistakes.
assertThrows automates checking for expected errors.
This makes tests faster, clearer, and more reliable.
Practice
assertThrows in JUnit testing?Solution
Step 1: Understand the role of
assertThrowsassertThrowsis designed to check if a certain exception occurs when running some code.Step 2: Compare with other options
Options B, C, and D describe different test functions unrelated to exception checking.Final Answer:
To check if a specific exception is thrown by a block of code -> Option AQuick Check:
assertThrows checks exceptions = A [OK]
- Confusing assertThrows with assertEquals
- Thinking assertThrows measures performance
- Using assertThrows to skip tests
assertThrows in JUnit 5?Solution
Step 1: Recall the method signature
The correct syntax isassertThrows(Exception.class, executable)where executable is a lambda or method reference.Step 2: Check each option
assertThrows(Exception.class, () -> methodCall()); matches the correct order and lambda usage. Options A, B, and D have wrong argument order or missing lambda.Final Answer:
assertThrows(Exception.class, () -> methodCall()); -> Option AQuick Check:
Exception class first, then lambda = C [OK]
- Swapping the order of arguments
- Passing method call instead of lambda
- Omitting the lambda expression
import static org.junit.jupiter.api.Assertions.assertThrows;
@Test
void testDivideByZero() {
assertThrows(ArithmeticException.class, () -> {
int result = 10 / 0;
});
}Solution
Step 1: Analyze the code inside assertThrows
The code divides 10 by 0, which throws an ArithmeticException at runtime.Step 2: Check if exception matches expected
assertThrows expects ArithmeticException.class, which matches the thrown exception.Final Answer:
Test passes because ArithmeticException is thrown -> Option DQuick Check:
Exception thrown matches expected = A [OK]
- Assuming no exception is thrown
- Confusing exception types
- Thinking test fails on exception
assertThrows:@Test
void testNullPointer() {
assertThrows(NullPointerException, () -> {
String s = null;
s.length();
});
}Solution
Step 1: Check the exception argument
The exception class must be passed asNullPointerException.class, not just the class name.Step 2: Verify lambda and exception thrown
The lambda syntax is correct and the code throws NullPointerException as expected.Final Answer:
Missing .class after NullPointerException -> Option CQuick Check:
Exception class needs .class suffix = B [OK]
- Omitting .class after exception
- Miswriting lambda syntax
- Assuming exception not thrown
parseNumber(String s) throws NumberFormatException only when the input is not a valid number. Which of these tests correctly uses assertThrows to check this behavior?Solution
Step 1: Understand the method behavior
parseNumber should throw NumberFormatException for invalid strings like "abc" but not for valid numbers like "123".Step 2: Evaluate each test case
assertThrows(NumberFormatException.class, () -> parseNumber("abc")); tests invalid input "abc" correctly. assertThrows(NumberFormatException.class, () -> parseNumber("123")); tests valid input, so no exception expected. assertThrows(Exception.class, () -> parseNumber(null)); uses a different exception and null input. assertThrows(NumberFormatException.class, () -> parseNumber(123)); passes an integer instead of string, causing compile error.Final Answer:
assertThrows(NumberFormatException.class, () -> parseNumber("abc")); -> Option BQuick Check:
Test invalid input throws NumberFormatException = D [OK]
- Testing valid input expecting exception
- Passing wrong argument types
- Using wrong exception class
Ready to prove it?
Pass the test and this pattern moves unknown
