In my application, when the user clicks on a "Register" button, the RegisterActivity is launched. Once the user fills in the form, the details are posted to a web service and if registration succeeds, RegisterActivity finishes with RESULT_OK. This is summarized in the code sample below:
public void submitRegistration() {
    showProgressDialog(R.string.registration, R.string.please_wait);  
    
    getWebApi().register(buildRegistrationFromUI(), new Callback<ApiResponse>() {
        @Override
        public void success(ApiResponse apiResponse, Response response) {     
            hideProgressDialog();
            setResult(RESULT_OK);
            finish();
        }
        @Override
        public void failure(RetrofitError error) {
            hideProgressDialog();
            showErrorDialog(ApiError.parse(error));
        }
    });
}
Using Espresso, how can I check that the activity finished with setResult(RESULT_OK)?
Please note: I do NOT want to create a mock intent. I want to check the intent result status.
All the setResult(...) method does is to change the values of fields in the Activity class
 public final void setResult(int resultCode, Intent data) {
    synchronized (this) {
        mResultCode = resultCode;
        mResultData = data;
    }
}
So we can use Java Reflection to access the mResultCode field to test if the value has indeed been set to RESULT_OK.
@Rule
public ActivityTestRule<ContactsActivity> mActivityRule = new ActivityTestRule<>(
        ContactsActivity.class);
@Test
public void testResultOk() throws NoSuchFieldException, IllegalAccessException {
    Field f = Activity.class.getDeclaredField("mResultCode"); //NoSuchFieldException
    f.setAccessible(true);
    int mResultCode = f.getInt(mActivityRule.getActivity());
    assertTrue("The result code is not ok. ", mResultCode == Activity.RESULT_OK);
}
You can simply use an ActivityTestRule and get the Activity result like this:
assertThat(rule.getActivityResult(), hasResultCode(Activity.RESULT_OK));
assertThat(rule.getActivityResult(), hasResultData(IntentMatchers.hasExtraWithKey(PickActivity.EXTRA_PICKED_NUMBER)));
Full example available here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With