使用JUnit Theory时会出现异常

Jon*_*nas 3 java testing junit exception-handling junit4

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

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

Jon*_*nas 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
}
Run Code Online (Sandbox Code Playgroud)