0
0
JUnittesting~15 mins

assertThrows usage in JUnit - Build an Automation Script

Choose your learning style9 modes available
Verify that a method throws the expected exception
Preconditions (2)
Step 1: Call the method with a negative input value
Step 2: Verify that the method throws IllegalArgumentException
✅ Expected Result: The test should pass only if IllegalArgumentException is thrown when the method is called with negative input
Automation Requirements - JUnit 5
Assertions Needed:
assertThrows to verify IllegalArgumentException is thrown
Best Practices:
Use lambda expression inside assertThrows
Check exception message if relevant
Keep test method names descriptive
Automated Solution
JUnit
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.

Common Mistakes - 3 Pitfalls
Using try-catch block instead of assertThrows
Not using a lambda expression inside assertThrows
Not verifying the exception message
Bonus Challenge

Now add data-driven testing with 3 different negative inputs to verify the exception is thrown each time

Show Hint