测试一个名为setResult的活动

sup*_*ell 16 testing android unit-testing android-activity

我正在为一个活动编写测试(我的测试类扩展了ActivityInstrumentationTestCase2),我已经编写了一些基本的测试并且工作正常.

但是我当它完成通过的setResult(resultCode为,意图我)我想用什么仪器得到我的活动来完成的事,然后检查它所在的setResult调用中传递返回额外的数据到调用活动活动.

是否有一些框架提供了这样做的方式?我一直没能找到任何东西,一种方法是子类的活动类和重写的setResult把它记住和揭露什么传递给的setResult(原来的setResult是最后的,所以你不能做到这一点无论) ,似乎应该有更好的方法.

Edu*_*ora 11

正如我在另一个问题中回答的那样,您也可以使用Robolectric并对正在测试的Activity进行阴影处理.然后,ShadowActivity为您提供了方法,可以轻松了解活动是否正在完成以及检索其结果代码.

举个例子,我的一个测试看起来像这样:

@Test
public void testPressingFinishButtonFinishesActivity() {
    mActivity.onCreate(null);
    ShadowActivity shadowActivity = Robolectric.shadowOf(mActivity);

    Button finishButton = (Button) mActivity.findViewById(R.id.finish_button);
    finishButton.performClick();

    assertEquals(DummyActivity.RESULT_CUSTOM, shadowActivity.getResultCode());
    assertTrue(shadowActivity.isFinishing());
}
Run Code Online (Sandbox Code Playgroud)

对于Robolectric 3+替换

ShadowActivity shadowActivity = Robolectric.shadowOf(mActivity);
Run Code Online (Sandbox Code Playgroud)

ShadowActivity shadow = Shadows.shadowOf(activity);
Run Code Online (Sandbox Code Playgroud)


Val*_*s R 6

从另一个类似的问题看我的答案:

您可以使用反射并直接从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);
  }
}
Run Code Online (Sandbox Code Playgroud)


Kon*_*uda 1

另一种方法是使用像 jmockit 这样的现代模拟框架 - 这样你就可以在没有模拟器的情况下模拟 android 类的行为等。你可以在我的单元测试中看到它的示例: https: //github.com/ko5tik/jsonserializer(以前的版本)针对与 android 捆绑在一起的 JSON 进行工作,并针对 GSON 进行实际工作,但模拟逻辑仍然存在)