Cookienator
Cookienator

Reputation: 647

Android - Espresso testing - Close and app and then re-open it?

In my espresso test, I close the app by using "device.pressBack()". I then want to re-open the app, in a certain Activity, but I'm not quite sure how to do that, since I don't even have a context at this point. Does anybody have an idea?

Upvotes: 4

Views: 11494

Answers (4)

Activity test rule is deprecated. You can do this using the following code.

activityScenarioRule.scenario.close() 
ActivityScenario.launch(YourActivity::class.java, null)

Upvotes: 0

DINESH KUMAR
DINESH KUMAR

Reputation: 143

This will close your app and re-open again.

First, execute code bellow. To navigate back into the last activity.

            pressBackUnconditionally();

Then execute the next code. It will close your application or activity

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

            activityRule.finishActivity();

Finally, open application/activity using below code

 activityRule.launchActivity(new Intent());

A full snippet here below

        pressBackUnconditionally();
        activityRule.finishActivity();
        activityRule.launchActivity(new Intent());

Upvotes: 1

ycesar
ycesar

Reputation: 440

After you close your app, a NoActivityResumedException exception is thrown so you will have to catch it.

After that, relaunch your activity by using an ActivityTestRule of type MyActivity as Cookienator have said.

@Rule
public ActivityTestRule<MyActivity> myActivityTestRule = new ActivityTestRule<>(MyActivity.class, true, false)

myActivityTestRule.launchActivity(null);

Upvotes: -1

Cookienator
Cookienator

Reputation: 647

OK, got it. You define a rule in your test class:

@Rule
public ActivityTestRule<MyActivity> myActivityTestRule = new ActivityTestRule<>(MyActivity.class, true, false);

Then, after you used device.pressback(), you can use this to open that specific Activity in your app:

myActivityTestRule.launchActivity(null);

Upvotes: 3

Related Questions