在完成()之后从活动中获取结果;在 Android 单元测试中 [英] Get result from an activity after finish(); in an Android unit test

查看:13
本文介绍了在完成()之后从活动中获取结果;在 Android 单元测试中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在编写一些 Android 单元测试,虽然我已经按照我想要的方式完成了大部分工作,但有一件事让我感到有些困惑.

I'm currently writing some Android unit tests, and while I've gotten most things to work the way I want, one thing has left me kind of stumped.

我的活动中有以下代码进行测试:

I have the following code in my activity under test:

Intent result = new Intent();
result.putExtra("test", testinput.getText().toString());
setResult(Activity.RESULT_OK, result);
finish();

我试图弄清楚如何使用 Instrumentation(或其他)来读取活动的结果,或者在活动完成后获得意图.任何人都可以帮忙吗?

I'm trying to figure out how to use Instrumentation (or whatever) to be able to read the result of the activity, or get at the intent after the activity is finished. Can anyone help?

推荐答案

您可以使用反射并直接从 Activity 中获取值.

You can use reflection and grab the values directly from the Activity.

protected Intent assertFinishCalledWithResult(int resultCode) {
  assertThat(isFinishCalled(), is(true));
  try {
    Field f = Activity.class.getDeclaredField("mResultCode");
    f.setAccessible(true);
    int actualResultCode = (Integer)f.get(getActivity());
    assertThat(actualResultCode, is(resultCode));
    f = Activity.class.getDeclaredField("mResultData");
    f.setAccessible(true);
    return (Intent)f.get(getActivity());
  } catch (NoSuchFieldException e) {
    throw new RuntimeException("Looks like the Android Activity class has changed it's   private fields for mResultCode or mResultData.  Time to update the reflection code.", e);
  } catch (Exception e) {
    throw new RuntimeException(e);
  }
}

这篇关于在完成()之后从活动中获取结果;在 Android 单元测试中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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