3

@Test(expected = SomeException.class)在 JUnit 4 中,您可以使用注释声明预期的异常。但是,当使用 Theories 进行测试时,@Theory注释没有预期的属性。

测试理论时声明预期异常的最佳方法是什么?

4

2 回答 2

6

我更喜欢使用ExpectedException 规则

import org.junit.rules.ExpectedException;

<...>

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

@Theory
public void throwExceptionIfArgumentIsIllegal(Type type) throws Exception {
    assumeThat(type, equalTo(ILLEGAL));
    thrown.expect(IllegalArgumentException.class);
    //perform actions
}
于 2012-10-24T13:35:26.530 回答
1

您也可以使用普通的assert. 您可以在旧版本的 JUnit(4.9 之前)上使用它。

@Test
public void exceptionShouldIncludeAClearMessage() throws InvalidYearException {
    try {
        taxCalculator.calculateIncomeTax(50000, 2100);
        fail("calculateIncomeTax() should have thrown an exception.");
    } catch (InvalidYearException expected) {
        assertEquals(expected.getMessage(),
                     "No tax calculations available yet for the year 2100");
    }
}
于 2012-12-06T16:51:38.663 回答