Reputation: 421
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
Upvotes: 0
Views: 56
Reputation: 6216
You could do something like:
@Test(expected = CalculationEngineException.class)
public void shouldThrowAnException_When_InputIsNull() {
calculatorBooking.calculate(null, null, 0, null);
}
From Junit doc :
The Test annotation supports two optional parameters. The first, expected, declares that a test method should throw an exception. If it doesn't throw an exception or if it throws a different exception than the one declared, the test fails.
Upvotes: 2
Reputation: 15308
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);
}
Upvotes: 0
Reputation: 17890
Place expectedException.expect
before the call that will throw the exception.
@Test
public void shouldThrowAnException_When_InputIsNull() {
expectedException.expect(CalculationEngineException.class);
expectedException.expectMessage("Error");
calculatorBooking.calculate(null, null, 0, null);
}
Upvotes: 0