Search code examples
javaunit-testingtestingjunitjunit4

Assert an Exception is Thrown in


I have this Junit test in my project

public class CalculatorBookingTest {

    private CalculatorBooking calculatorBooking;

    @Rule
    public ExpectedException expectedException = ExpectedException.none();

    @Before
    public void setUp() {
        calculatorBooking = new CalculatorBooking();
    }

    @Test
    public void shouldThrowAnException_When_InputIsNull() {
        calculatorBooking.calculate(null, null, 0, null);
        expectedException.expect(CalculationEngineException.class);
        expectedException.expectMessage("Error");
    }

}

but when I run the test, the Exception is Thrown but nevertheless the test fail


Solution

  • You need to first tell JUnit that the method is expected to throw the exception. Then when it's thrown - it knows that the test passes. In your code you put expect() after the exception is thrown - so the execution doesn't even go that far. The right way:

    @Test
    public void shouldThrowAnException_When_InputIsNull() {
        expectedException.expect(CalculationEngineException.class);
        expectedException.expectMessage("Error");
        calculatorBooking.calculate(null, null, 0, null);
    }