开发者

testing that an activity called setResult

I'm writing tests for an activity (my test class extends ActivityInstrumentationTestCase2), I've got some basic tests written and working fine.

However my activity when it completes returns extra data to the calling activity via setResult(resultcode, Intent i) What I'd like to do using instrumentation get m开发者_StackOverflow中文版y activity to finish, then check what it passed in the setResult call.

Is there some framework provided way of doing this? i haven't been able to find anything yet, one approach would be to subclass the activity class and override setResult to have it remember & expose what was passed to setResult (turns out setResult is final, so you can't do this either), it seems like there should be a better way.


As I answered in another questiom, 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:

@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());
}

For Robolectric 3+ replace

ShadowActivity shadowActivity = Robolectric.shadowOf(mActivity);

with

ShadowActivity shadow = Shadows.shadowOf(activity);


See my answer from another similar question:

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);
  }
}


Another approach would be to use modern mocking framework like jmockit - this way you can simulate behavior of android classes without emulator etc. You can see sample of it in my unit tests: https://github.com/ko5tik/jsonserializer ( previous versions worked against JSON bundled with android, and actual against GSON, but mocking logic is still there )

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜