finish() 之后获取活动的结果;在 Android 单元测试中
我目前正在编写一些 Android 单元测试,虽然我已经让大多数事情按照我想要的方式工作,但有一件事让我有点困惑。
我正在测试的活动中有以下代码:
Intent result = new Intent();
result.putExtra("test", testinput.getText().toString());
setResult(Activity.RESULT_OK, result);
finish();
我试图弄清楚如何使用 Instrumentation (或其他)来读取活动的结果,或者在活动完成后获取意图。 有人可以帮忙吗?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以使用反射并直接从活动中获取值。
You can use reflection and grab the values directly from the Activity.
或者您也可以使用 Robolectric 并跟踪测试中的 Activity。然后,ShadowActivity 为您提供了轻松了解 Activity 是否正在完成以及检索其结果代码的方法。
举个例子,我的一个测试如下所示:
Or you could also use Robolectric and shadow the Activity under test. Then, ShadowActivity provides you with methods to easily know if an Activity is finishing and for retrieving its result code.
As an example, one of my tests looks like this:
您可以通过编写一个特殊的活动来做到这一点,该活动的唯一目的是启动您正在测试结果的活动并保存结果以供您断言正确性。
例如,您可以创建一个名为
ResultReceiverActivity
的活动。为其提供三个方法:getResultCode
、getResultData
和getReceivedRequestCode
,它们可用于验证测试的活动是否返回了正确的值。您将创建一个扩展ActivityInstrumentationTestCase2
的测试用例,通用参数为ResultReceiverActivity
。调用getActivity
将获取活动实例。当然,
ResultReceiverActivity
需要重写onActivityResult
,并且应该只将该方法参数的值存储在其字段中,如下所示:当然,您可能想要自定义活动
ResultReceiverActivity
启动,您可以通过在其onCreate
方法中使用getIntent
轻松完成此操作。在您的测试用例中,请在调用 getActivity 之前调用 setActivityIntent 以设置使用哪个 Intent 来启动 Activity。You can do this by writing a special activity whose only purpose is to start the activity you are testing for result and save the result for you to assert correctness on.
For example, you could create an activity named
ResultReceiverActivity
. Give it three methods:getResultCode
,getResultData
, andgetReceivedRequestCode
, which can be used to verify that the tested activity returned the right values. You would create a test case that extendsActivityInstrumentationTestCase2
and the generic parameter would beResultReceiverActivity
. CallinggetActivity
will get you the activity instance.ResultReceiverActivity
needs to overrideonActivityResult
, of course, and should just store the values of that methods parameter in its fields, like so:Of course, you may want to customize the activity that
ResultReceiverActivity
starts, and you can easily do that by usinggetIntent
in itsonCreate
method. In your test case, call setActivityIntent before calling getActivity to set which Intent is used to start the activity.我不确定单元测试是否有所不同,但您应该能够使用 onActivityResult ,如下所示: 启动活动。您只需使用 startActivityForResult(intent, requestCode) 启动 Activity,然后
在使用 startActivityForResult 的 Activity 中使用。
I'm not sure if it is different for unit tests, but you should be able to use onActivityResult as seen here: StartingActivities. You just start the Activity with startActivityForResult(intent, requestCode) and then use
back in the activity that used startActivityForResult.