安卓的UnitTestUnitTest

2023-09-06 00:05:05 作者:时光会咬人

需要一些建议。我有一个应用程序。而我需要做写一些的UnitTest。但我真的不知道要考什么。我已经测试设置和所有preferences,这很容易。还有什么通常人们测试?比方说,我有3个活动。最主要的是列表的活动,当你在列表项单击其正向您在第二份名单的活动......和列表项单击其正向你第三个活动。我想,也许我应该测试活动之间的切换?如何模拟点击列表项的UnitTest以及如何检查活动是开放与否?谢谢!

Need some advice. I have an App. And I need do write some UnitTest. But I really don't know what to test. I already test Settings and all preferences, that's easy. What else usually people test ? Lets say that I have 3 Activities. Main one is list activity, when you click on list item its forward you on a second List Activity...and on list item click its forward you on third Activity. I think maybe I should test the switching between activities ? How to simulate click on list item in UnitTest and how to check that activity was open or not ? Thanks !

推荐答案

Android提供测试类为你,你希望能够在你的单元测试一样面面俱到。 您可以单元测试你的Java组件,你的android架构的依赖组件,并且您的工作流程作为一个整体。

Android provides test classes for you to be able to be as exhaustive in your unit testing as you want to be. You can unit test your java components, your android-architecture dependant components, and your workflow as a whole.

在你的情况,以活动之间的测试序列,您可以使用InstrumentationTestCase类并扩展它,然后在你的测试,你应该使用下面的方法:

In your case, to test sequences between activities, you can use the InstrumentationTestCase class and extend it, and then in your tests, you should use the following methods:

// Prepare a monitor for your activity
Instrumentation instrumentation = getInstrumentation()
Instrumentation.ActivityMonitor monitor = instrumentation.addMonitor(YourClass.class.getName(), null, false);

// Start your activity manually
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setClassName(instrumentation.getTargetContext(), YourClass.class.getName());
        instrumentation.startActivitySync(intent);

// Get the started Activity
Activity currentActivity = getInstrumentation().waitForMonitor(monitor);

然后就可以卸下显示器,并添加另一台显示器为您希望赶在工作流序列中的下一个活动。有了这个程序,你可以通过编程进行交互,并验证通过多种活动的动作序列。

Then you can remove the monitor and add another monitor for the next activity you expect to catch in the workflow sequence. With this sequence you can programatically interact and verify sequences of actions that go through multiple activities.