dimanche 5 février 2017

Activity.finish() does not work as expected in espresso

I am implementing a UI Test in an android App using espresso to test a particular Activity. The Activity is called SomeActivity and it is started from the MainActivity which is the launching Activity of the App:

Intent intent = new Intent(this, SomeActivity.class);
startActivityForResult(intent, SomeActivity.REQUEST_CODE_STRING);

The test works properly until I perform a click on a Button Save which should save the data and finish the SomeActivity leading the App to previous Activity namely the MainActivity. The relevant code is:

Button button = (Button) findViewById(R.id.save_button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (validateView()) {
                    saveData();
                    finish();
                }
            }
        });

I check with debugging that the above code is executed and finish() is called, however it sends the App to background and does not let the previous Activity (MainActivity) come up again. The relevant code of the test is:

@RunWith(AndroidJUnit4.class)
@LargeTest
public class SomeActivityTest {

    @Rule
    public ActivityTestRule<MainActivity> mainActivityRule = new ActivityTestRule<>(
            MainActivity.class);

    @Rule
    public ActivityTestRule<SomeActivity> someActivityRule = new ActivityTestRule<>(
            SomeActivity.class);


    @Test
    public void testTransitionToMainActivity() {
       ...
        onView(withId(R.id.save_button)).perform(click());
        Thread.sleep(200);
        onView(withId(R.id.toolbar)).check(matches(isDisplayed()));
        onView(withId(R.id.toolbar_title)).check(matches(withText(R.string.mainActivityTitle)));    
    }
}

The test fails on the last line since it does not get the App to previous Activity and therefore the Toolbar does not have the title of the MainActivity. I check with debugging, that the method onActivityResult() in the MainActivity is not called. Is anything wrong with above test? How can I test the transition to previous Activity?

Aucun commentaire:

Enregistrer un commentaire