如何将 Android SingleLaunchActivityTestCase 转换为 ActivityTestRule?(仪器单元测试) [英] How to convert Android SingleLaunchActivityTestCase to ActivityTestRule? (Instrumentation unit test)

查看:26
本文介绍了如何将 Android SingleLaunchActivityTestCase 转换为 ActivityTestRule?(仪器单元测试)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

SingleLaunchActivityTestCase 的文档说此类现已弃用,应替换为 ActivityTestRule.但这是如何做到的?

SingleLaunchActivityTestCase 允许 Activity 启动一次并保持打开状态;然后在这段时间内可以运行多个测试,然后关闭 Activity.ActivityTestRule 似乎没有这个功能 - 它总是为每个 @Test 方法重新启动 Activity.

SingleLaunchActivityTestCase allowed an Activity to launch once and keep it open; then multiple tests can run during this time, then the Activity is closed. ActivityTestRule does not seem to have this functionality - it always relaunches the Activity for each @Test method.

那么是否有可能让 ActivityTestRule 启动一次 Activity 并使其保持打开状态,以及如何确保 context(来自 activityTestRule.getActivity()) 对于每个 @Test 函数不为空?

So is it possible to make ActivityTestRule launch an Activity once and keep it open, and how do I ensure the context (from activityTestRule.getActivity()) is not null for each @Test function?

示例代码此处.

推荐答案

使用 默认情况下不启动活动的构造函数(将 launchActivity 参数设置为 ).然后使用 launchActivity() 在您的设置中,但不是在每个测试方法中.这样你就可以自己启动一次,但每次测试都会在同一个实例上运行.

Use the constructor that does not start the activity by default (setting the launchActivity argument to false). Then use launchActivity() in your setup, but not in each test method. This way you will start it up once yourself, but each test will operate on the same instance.

您可能还希望在测试课程结束时明确完成活动以进行清理.

You'll probably want to also explicitly finish the activity at the end of the test class, for cleanup.

注意:这通常不是测试的最佳实践,因为测试可能相互依赖(这不是一个好主意),或者根据它们运行的​​顺序提供不正确的结果,等等.在这种情况下,状态从一个测试持续到下一个.

Note: This isn't generally a best practice for testing though, since tests could depend on each other (which isn't a good idea), or provide incorrect results depending on the order they run, etc. since the activity state is persisted from one test to the next in this case.

这篇关于如何将 Android SingleLaunchActivityTestCase 转换为 ActivityTestRule?(仪器单元测试)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆