Gim*_*mbl 47 testing junit android
我正在尝试使用内置的Android Junit测试框架编写一些测试.我遇到了一个测试问题,我期待抛出异常.在JUnit中,测试方法的注释将是:
@Test(expected = ArithmeticException.class)
但是,在Android中,此测试因ArithmeticException而失败.
我知道Android实现只是JUnit 3的一个子集,甚至不允许注释@Test(必须是@SmallTest,@ MediumTest或@LargeTest,并且这些都不允许'expected = ..'参数),但这似乎是一个相当重要的测试,如果它没有这个功能,似乎严重缺乏Android测试框架.
注意: 我通过将JUnit jar添加到项目中并通过向我的测试方法添加注释来测试它.对我来说,为什么注释会被完全忽略是有道理的,因为Android框架(runner?)不是在寻找那个注释而只是忽略它.基本上,我只是在框架内寻找"正确"的方式来做到这一点.
小智 66
这种测试的标准junit 3成语是:
public void testThatMethodThrowsException()
{
try
{
doSomethingThatShouldThrow();
Assert.fail("Should have thrown Arithmetic exception");
}
catch(ArithmeticException e)
{
//success
}
}
Run Code Online (Sandbox Code Playgroud)
san*_*tar 31
现在JUnit4可以通过Android SDK获得(参考android-test-kit)
更新:它现在正式登陆d.android.com:
AndroidJUnitRunner是Android的一个新的非捆绑式测试运行器,它是Android支持测试库的一部分,可以通过Android支持存储库下载.新的跑步者包含了GoogleInstrumentationTestRunner的所有改进,并添加了更多功能:
- JUnit4支持
- Instrumentation Registry用于访问Instrumentation,Context和Bundle Arguments
- 测试过滤器@SdkSupress和@RequiresDevice
- 测试超时
- 测试结果
- RunListener支持挂钩到测试运行生命周期
- 活动监控机制ActivityLifecycleMonitorRegistry
因此,使用预期注释的JUnit4样式的异常测试:
@Test(expected= IndexOutOfBoundsException.class)
public void empty() {
new ArrayList<Object>().get(0);
}
Run Code Online (Sandbox Code Playgroud)
或预期的例外规则:
@Rule
public ExpectedException thrown = ExpectedException.none();
@Test
public void shouldTestExceptionMessage() throws IndexOutOfBoundsException {
List<Object> list = new ArrayList<Object>();
thrown.expect(IndexOutOfBoundsException.class);
thrown.expectMessage("Index: 0, Size: 0");
list.get(0); // execution will never get past this line
}
Run Code Online (Sandbox Code Playgroud)
也是可能的.
有关如何设置测试支持库的更多详细信息,请参阅官方文档.
| 归档时间: |
|
| 查看次数: |
19095 次 |
| 最近记录: |