Skip to content

Instantly share code, notes, and snippets.

@realdadfish
Last active October 22, 2015 10:39
Show Gist options
  • Save realdadfish/3ff8585288ba831059e5 to your computer and use it in GitHub Desktop.
Save realdadfish/3ff8585288ba831059e5 to your computer and use it in GitHub Desktop.
A pair of hamcrest matchers to check for activity results / intent data.
/**
* A pair of hamcrest matchers that expose the result code and intent data of activities.
*
* Usage:
*
* @RunWith(AndroidJUnit4.class)
* public class YourActivityTest extends ActivityTestBase {
* @Rule
* public final ActivityTestRule<YourActivity> mActivityTestRule = new ActivityTestRule<>(YourActivity.class);
*
* @Test
* public void testFinishing() {
* // do something that triggers your activity to finish with a result code
* assertThat(mActivityTestRule.getActivity().isFinishing(), is(true));
* assertThat(mActivityTestRule.getActivity(), hasActivityResultCode(Activity.RESULT_OK));
* }
* }
*
* License: Apache Software License, v2
* Author: Thomas Keller <[email protected]>
*/
public class ActivityResultMatchers {
private ActivityResultMatchers() {
}
/**
* Checks whether an activity has a specific result code set
*
* @param resultCode
* @return
*/
public static TypeSafeMatcher<Activity> hasActivityResultCode(final int resultCode) {
return new TypeSafeMatcher<Activity>(Activity.class) {
private static final String FIELD_NAME = "mResultCode";
@Override
public void describeTo(Description description) {
description.appendText("matches activity with result code ");
description.appendValue(resultCode);
}
@Override
protected boolean matchesSafely(Activity item) {
try {
Field field = Activity.class.getDeclaredField(FIELD_NAME);
field.setAccessible(true);
return field.getInt(item) == resultCode;
} catch (Exception e) {
throw new IllegalStateException("cannot find or access " + FIELD_NAME + " on Activity", e);
}
}
};
}
/**
* Checks whether an activity has a specific result intent set
*
* @param intentMatcher
* @return
*/
public static TypeSafeMatcher<Activity> hasActivityResultIntent(final Matcher<Intent> intentMatcher) {
return new TypeSafeMatcher<Activity>(Activity.class) {
private static final String FIELD_NAME = "mResultData";
@Override
public void describeTo(Description description) {
description.appendText("matches activity with intent: ");
intentMatcher.describeTo(description);
}
@Override
protected boolean matchesSafely(Activity item) {
try {
Field field = Activity.class.getDeclaredField(FIELD_NAME);
field.setAccessible(true);
return intentMatcher.matches(field.get(item));
} catch (Exception e) {
throw new IllegalStateException("cannot find or access " + FIELD_NAME + " on Activity", e);
}
}
};
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment