Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android Espresso: Running multiple tests sequentially

I'm trying to run a series of tests using Espresso for Android. It appears that between runs the Activities are NOT being closed. Whatever the app state after one test, its left for the next test.

I need to run each of my tests from a fresh app start. In Robotium this is handled using solo.finishOpenedActivites() in the tearDown() method.
http://robotium.googlecode.com/svn/doc/com/robotium/solo/Solo.html#finishOpenedActivities()

How can this be accomplished with Espresso?

like image 820
SuperDeclarative Avatar asked Jun 10 '14 22:06

SuperDeclarative


1 Answers

The problem with the supplied fix on the bug report is, that this will only be executed on finish of the whole suite. If you want to have a clean activity stack after each test you need to manually do something. I wrote a little class that does pretty much the same as the fix on the above mentioned ticket, but can be executed at any point in time.

import android.app.Activity;
import android.os.Handler;
import android.os.Looper;
import com.google.android.apps.common.testing.testrunner.ActivityLifecycleMonitor;
import com.google.android.apps.common.testing.testrunner.ActivityLifecycleMonitorRegistry;
import com.google.android.apps.common.testing.testrunner.Stage;
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.List;


public final class ActivityFinisher implements Runnable {

    public static void finishOpenActivities() {
        new Handler(Looper.getMainLooper()).post(new ActivityFinisher());
    }

    private ActivityLifecycleMonitor activityLifecycleMonitor;

    public ActivityFinisher() {
        this.activityLifecycleMonitor = ActivityLifecycleMonitorRegistry.getInstance();
    }

    @Override
    public void run() {
        final List<Activity> activities = new ArrayList<Activity>();

        for (final Stage stage : EnumSet.range(Stage.CREATED, Stage.STOPPED)) {
            activities.addAll(activityLifecycleMonitor.getActivitiesInStage(stage));
        }

        for (final Activity activity : activities) {
            if (!activity.isFinishing()) {
                activity.finish();
            }
        }
    }
}
like image 175
Sebastian Gröbler Avatar answered Oct 02 '22 04:10

Sebastian Gröbler