0
0
JUnittesting~15 mins

assertThrows for exceptions in JUnit - Build an Automation Script

Choose your learning style9 modes available
Verify that dividing by zero throws ArithmeticException
Preconditions (2)
Step 1: Call divide(10, 0)
Step 2: Check that ArithmeticException is thrown
✅ Expected Result: The test passes only if ArithmeticException is thrown when dividing by zero
Automation Requirements - JUnit 5
Assertions Needed:
Verify that ArithmeticException is thrown when divide(10, 0) is called
Best Practices:
Use assertThrows method from JUnit 5
Use lambda expression to call the method that should throw
Keep test method names descriptive
Avoid catching exceptions manually in the test
Automated Solution
JUnit
import static org.junit.jupiter.api.Assertions.assertThrows;
import org.junit.jupiter.api.Test;

public class CalculatorTest {

    public int divide(int a, int b) {
        return a / b;
    }

    @Test
    void testDivideByZeroThrows() {
        assertThrows(ArithmeticException.class, () -> divide(10, 0));
    }
}

The test class CalculatorTest contains a simple divide method that divides two integers.

The test method testDivideByZeroThrows uses assertThrows from JUnit 5 to check that calling divide(10, 0) throws an ArithmeticException.

The lambda () -> divide(10, 0) is passed to assertThrows so JUnit can run it and catch the exception.

This approach is clean and avoids try-catch blocks in the test, making the test easy to read and maintain.

Common Mistakes - 3 Pitfalls
Using try-catch block manually instead of assertThrows
Passing method call directly instead of lambda to assertThrows
Asserting wrong exception type
Bonus Challenge

Now add data-driven testing with 3 different inputs that throw ArithmeticException

Show Hint