断言抛出异常

Assert an Exception is Thrown in

我的项目中有这个 Junit 测试

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");
    }

}

但是当我 运行 测试时,异常被抛出但是测试失败了

你可以这样做:

@Test(expected = CalculationEngineException.class)
public void shouldThrowAnException_When_InputIsNull() {
    calculatorBooking.calculate(null, null, 0, null);
}

来自 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.

expectedException.expect 放在将抛出异常的调用之前。

@Test
public void shouldThrowAnException_When_InputIsNull() {
    expectedException.expect(CalculationEngineException.class);
    expectedException.expectMessage("Error");

    calculatorBooking.calculate(null, null, 0, null);

}

你需要先告诉JUnit这个方法应该抛出异常。然后当它被抛出时——它知道测试通过了。在您的代码中,您在抛出异常后放置 expect() - 因此执行甚至不会走那么远。正确做法:

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