Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Espresso: How can I test that the activity finished with result RESULT_OK

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.

like image 563
W.K.S Avatar asked Nov 18 '15 11:11

W.K.S


2 Answers

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);
}
like image 97
Eric Liu Avatar answered Oct 12 '22 14:10

Eric Liu


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.

like image 28
Roberto Leinardi Avatar answered Oct 12 '22 15:10

Roberto Leinardi