Skip to content Skip to sidebar Skip to footer

Is It Possible To Find Out If An Android Application Runs As Part Of An Instrumentation Test

Is there a runtime check for an application to find out if it runs as part of an instrumentation test? Background: Our application performs a database sync when starting. But that

Solution 1:

A much simpler solution is check for a class that would only be present in a test classpath, works with JUnit 4 (unlike the solution using ActivityUnitTestCase) and doesn't require to send custom intents to your Activities / Services (which might not even be possible in some cases)

privatebooleanisTesting() {
    try {
        Class.forName("com.company.SomeTestClass");
        returntrue;
    } catch (ClassNotFoundException e) {
        returnfalse;
    }
}

Solution 2:

Since API Level 11, the ActivityManager.isRunningInTestHarness() method is available. This might do what you want.

Solution 3:

If you are using Robolectric, you can do something like this:

publicbooleanisUnitTest() {
        String device = Build.DEVICE;
        String product = Build.PRODUCT;
        if (device == null) {
            device = "";
        }

        if (product == null) {
            product = "";
        }
        return device.equals("robolectric") && product.equals("robolectric");
    }

Solution 4:

If you're using ActivityUnitTestCase, you could set a custom Application object with setApplication, and have a flag in there to switch database sync on or off? There's an example of using a custom Application object on my blog:

http://www.paulbutcher.com/2011/03/mock-objects-on-android-with-borachio-part-3/

Solution 5:

You can pass an intent extra to your activity indicating it's under test.

1) In your test, pass "testMode" extra to your activity:

publicvoidsetUp()throws Exception {
    super.setUp();

    IntentactivityIntent=newIntent();
    activityIntent.putExtra("testMode", true);
    setActivityIntent(activityIntent);
}

2) In your activity, check for testMode:

Bundleextras= getIntent().getExtras();
if (extras != null && extras.getBoolean("testMode")) {
    // disable your database sync
}

Post a Comment for "Is It Possible To Find Out If An Android Application Runs As Part Of An Instrumentation Test"