Robolectric进行Android单元测试

a 夏天 提交于 2019-12-03 15:48:10

Robolectric进行Android单元测试

测试驱动android开发

在安卓模拟器或者真机上跑测试用例速度很慢。构建、部署、启动app,通常需要花费一分钟或者更久。这不是TDD(测试驱动开发)模式.Robolectric提供一种更好的方式。

可能你一直尝试在java IDE中使用junit或者testng直接跑测试用例,但是一直报java.lang.RuntimeException: Stub!异常。

这个异常是因为在jdk中没有android运行环境。而现在Robolectric这款android单元测试工具,模拟了android sdk中的jar包,可以直接在jvm中运行测试用例,这样就大大节省了时间。一个Robolectric测试用例如下:

    // Test class for MyActivity    @RunWith(RobolectricTestRunner.class)    public class MyActivityTest {    @Test    public void clickingButton_shouldChangeResultsViewText() throws Exception {    Activity activity = Robolectric.buildActivity(MyActivity.class).create().get();    Button pressMeButton = (Button) activity.findViewById(R.id.press_me_button);    TextView results = (TextView) activity.findViewById(R.id.results_text_view);    pressMeButton.performClick();    String resultsText = results.getText().toString();    assertThat(resultsText, equalTo("Testing Android Rocks!"));    }    }

SDK,Resource和Native Method模拟

继续阅读→

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!