assertThrows usage in JUnit - Build an Automation Script
import static org.junit.jupiter.api.Assertions.assertThrows; import org.junit.jupiter.api.Test; class Calculator { int squareRoot(int number) { if (number < 0) { throw new IllegalArgumentException("Negative input not allowed"); } return (int) Math.sqrt(number); } } public class CalculatorTest { @Test void testSquareRootThrowsExceptionForNegativeInput() { Calculator calculator = new Calculator(); IllegalArgumentException exception = assertThrows(IllegalArgumentException.class, () -> { calculator.squareRoot(-5); }); // Optional: verify exception message org.junit.jupiter.api.Assertions.assertEquals("Negative input not allowed", exception.getMessage()); } }
This test uses assertThrows from JUnit 5 to check that the squareRoot method throws an IllegalArgumentException when called with a negative number.
The lambda expression () -> calculator.squareRoot(-5) is passed to assertThrows. This means the code inside the lambda is executed and JUnit checks if the expected exception is thrown.
If the exception is thrown, the test passes. We also capture the exception object to verify its message matches the expected text. This helps ensure the exception is thrown for the right reason.
The test method name clearly describes what is being tested, which is a good practice.
Now add data-driven testing with 3 different negative inputs to verify the exception is thrown each time
Practice
assertThrows in JUnit testing?Solution
Step 1: Understand the role of assertThrows
assertThrowsis used to test if a particular exception occurs when running a piece of code.Step 2: Compare with other assertions
Other assertions check values or states, butassertThrowsspecifically checks for exceptions.Final Answer:
To check if a specific exception is thrown by a code block -> Option AQuick Check:
assertThrows = Exception check [OK]
- Confusing assertThrows with assertEquals
- Using assertThrows to check return values
- Expecting assertThrows to measure performance
assertThrows in JUnit 5?Solution
Step 1: Recall assertThrows method signature
The correct syntax isassertThrows(Exception.class, Executable)where Executable is a lambda or method reference.Step 2: Analyze options
assertThrows(Exception.class, () -> methodCall()); matches the correct syntax: exception class first, then lambda expression.Final Answer:
assertThrows(Exception.class, () -> methodCall()); -> Option AQuick Check:
assertThrows(Exception.class, lambda) = correct syntax [OK]
- Swapping parameters order
- Passing method call instead of lambda
- Omitting lambda expression
assertThrows(IllegalArgumentException.class, () -> {
throw new IllegalArgumentException("Invalid argument");
});Solution
Step 1: Check the exception thrown
The lambda throwsIllegalArgumentException, which matches the expected exception class.Step 2: Understand assertThrows behavior
assertThrows passes if the expected exception is thrown during execution.Final Answer:
Test passes because the expected exception is thrown -> Option DQuick Check:
Thrown exception matches expected = pass [OK]
- Thinking test fails if exception is thrown
- Confusing exception message with test result
- Assuming syntax error without checking code
assertThrows(NullPointerException.class, () -> {
String s = null;
s.length();
});Solution
Step 1: Analyze the code inside lambda
Callings.length()on a null string throwsNullPointerException.Step 2: Check assertThrows parameters
Expected exception isNullPointerException.class, matching the thrown exception.Final Answer:
No error; test will pass as NullPointerException is thrown -> Option CQuick Check:
NullPointerException thrown and expected = pass [OK]
- Assuming s.length() throws different exception
- Thinking lambda syntax is wrong
- Confusing exception class with superclass
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?
Solution
Step 1: Understand assertThrows return value
assertThrows returns the thrown exception object, here stored inthrown.Step 2: Analyze the assertEquals check
The test checks that the exception message equals "/ by zero", verifying the exact error message.Final Answer:
It verifies the exception message is exactly "/ by zero" -> Option BQuick Check:
Exception message checked = It verifies the exception message is exactly "/ by zero" [OK]
- Thinking it checks return value of division
- Assuming exception type is RuntimeException
- Ignoring the message assertion
Ready to prove it?
Pass the test and this pattern moves unknown
