android开发分享Android的JUnittesting…如何期待一个例外

我试图编写一些testing使用内置的Android Junittesting框架。 我遇到了一个testing问题,我期待抛出一个exception。 在JUnit中,testing方法的注释是:

@Test(expected = ArithmeticException.class)

但是,在android中,这个testing失败并出现ArithmeticException。

我明白,Android实现只是JUnit 3的一个子集,甚至不允许注解@Test(必须是@SmallTest,@MediumTest或@LargeTest,而且这些参数都不允许使用'expected = ..'参数) ,但这似乎是一个相当重要的testing,似乎像androidtesting框架将严重缺乏,如果它没有这个function。

注意:我通过将JUnit jar添加到项目并添加注释到我的testing方法来testing。 这对我来说是有道理的,为什么注释会被完全忽略,因为android框架(runner?)没有查找那个注释,只是忽略它。 基本上我只是在框架内寻找“正确”的方式来做到这一点。

    这种testing的标准答案是:

     public void testThatMethodThrowsException() { try { doSomethingThatShouldThrow(); Assert.fail("Should have thrown Arithmetic exception"); } catch(ArithmeticException e) { //success } } 

    现在JUnit4可以通过Android SDK(参考android-test-kit )

    更新 :现在在d.android.com上正式发布 :

    AndroidJUnitRunner是Android的一个新的非捆绑testing运行器,它是Android支持testing库的一部分,可以通过Android支持库下载。 新的跑步者包含了GoogleInstrumentationTestRunner的所有改进,并添加了更多function:

    所以, JUnit4风格的使用预期注释的exceptiontesting :

     @Test(expected= IndexOutOfBoundsException.class) public void empty() { new ArrayList<Object>().get(0); } 

    或预期的例外规则:

     @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 } 

    也是可能的。

    有关如何设置testing支持库的更多详细信息,请参阅官方文档 。

    以上就是android开发分享Android的JUnittesting…如何期待一个例外相关内容,想了解更多android开发(异常处理)及android游戏开发关注计算机技术网(www.ctvol.com)!)。

      本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

      ctvol管理联系方式QQ:251552304

      本文章地址:https://www.ctvol.com/addevelopment/512604.html

      (0)
      上一篇 2020年11月27日
      下一篇 2020年11月27日

      精彩推荐