【发布时间】:2012-10-24 13:35:26
【问题描述】:
在 JUnit 4 中,您可以使用 @Test(expected = SomeException.class) 注释声明预期的异常。但是,当使用 Theories 进行测试时,@Theory 注释不具有 expected 属性。
在测试 Theories 时声明预期异常的最佳方式是什么?
【问题讨论】:
标签: java testing exception-handling junit junit4
在 JUnit 4 中,您可以使用 @Test(expected = SomeException.class) 注释声明预期的异常。但是,当使用 Theories 进行测试时,@Theory 注释不具有 expected 属性。
在测试 Theories 时声明预期异常的最佳方式是什么?
【问题讨论】:
标签: java testing exception-handling junit junit4
我更喜欢使用ExpectedException rule:
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
}
【讨论】:
您也可以使用普通的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");
}
}
【讨论】: