有没有比这更优雅的方式在 Android 中执行断言抛出异常?
public void testGetNonExistingKey() {
try {
alarm.getValue("NotExistingValue");
fail( );
} catch (ElementNotFoundException e) {
}
}
这样的东西不起作用?!
@Test(expected=ElementNotFoundException .class)
谢谢,马克
最佳答案
您使用的是 junit4 测试运行器吗?如果您正在运行 junit3 测试运行器,@Test 注释将不起作用。检查您使用的版本。
其次,在代码中检查异常的推荐方法是使用规则(在 junit 4.7 中引入)。
@Rule
public ExpectedException exception = ExpectedException.none();
@Test
public void throwsIllegalArgumentExceptionIfIconIsNull() {
// do something
exception.expect(IllegalArgumentException.class);
exception.expectMessage("Icon is null, not a file, or doesn't exist.");
new DigitalAssetManager(null, null);
}
可以继续使用@Test(expected=IOException.class),但是上面的好处是如果在调用exception.expect之前抛出异常,那么测试就会失败。
关于android - 如何测试 assert 在 Android 中抛出异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7552587/