如何断言在JUnit 4测试中抛出某个异常?如何使用JUnit 4来习惯地测试某些代码抛出异常?我当然可以这样做:@Testpublic void testFooThrowsIndexOutOfBoundsException() {
boolean thrown = false;
try {
foo.doStuff();
} catch (IndexOutOfBoundsException e) {
thrown = true;
}
assertTrue(thrown);}我记得有注释或Assert.xyz或某物对于这类情况,这要少得多,更多的是JUnit的精神。
3 回答
胡子哥哥
TA贡献1825条经验 获得超6个赞
编辑Assertions.assertThrows()
ExpectedException
public class FooTest {
@Rule
public final ExpectedException exception = ExpectedException.none();
@Test
public void doStuffThrowsIndexOutOfBoundsException() {
Foo foo = new Foo();
exception.expect(IndexOutOfBoundsException.class);
foo.doStuff();
}}@Test(expected=IndexOutOfBoundsException.class)IndexOutOfBoundsExceptionfoo.doStuff()
米琪卡哇伊
TA贡献1998条经验 获得超6个赞
try {
methodThatShouldThrow();
fail( "My method didn't throw when I expected it to" );} catch (MyException expectedException) {}添加回答
举报
0/150
提交
取消
