Mar*_*ark 9 junit android exception
是否有更优雅的方式在Android中执行断言抛出异常呢?
public void testGetNonExistingKey() {
try {
alarm.getValue("NotExistingValue");
fail( );
} catch (ElementNotFoundException e) {
}
}
Run Code Online (Sandbox Code Playgroud)
像这样的东西不起作用?!
@Test(expected=ElementNotFoundException .class)
Run Code Online (Sandbox Code Playgroud)
谢谢,马克
您使用的是 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);
}
Run Code Online (Sandbox Code Playgroud)
可以继续使用@Test(expected=IOException.class),但是上面的好处是如果在调用exception.expect之前抛出异常,那么测试就会失败。
| 归档时间: |
|
| 查看次数: |
6240 次 |
| 最近记录: |