Is it possible to find out if an Android application runs as part of an instrumentation test

前端 未结 8 1125
孤独总比滥情好
孤独总比滥情好 2021-01-04 11:01

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 star

相关标签:
8条回答
  • 2021-01-04 11:24

    This work for me because no actual device is running

    public static boolean isUnitTest() {
        return Build.BRAND.startsWith(Build.UNKNOWN) && Build.DEVICE.startsWith(Build.UNKNOWN) && Build.DEVICE.startsWith(Build.UNKNOWN) && Build.PRODUCT.startsWith(Build.UNKNOWN);
    }
    
    0 讨论(0)
  • You can try this

    if (isRunningTest == null) {
            isRunningTest = false;
            StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();
            List<StackTraceElement> list = Arrays.asList(stackTrace);
            for (StackTraceElement element : list) {
                if (element.getClassName().startsWith("androidx.test.runner.MonitoringInstrumentation")) {
                    isRunningTest = true;
                    break;
                }
            }
        }
    
    0 讨论(0)
  • Since API Level 29, the static ActivityManager.isRunningInUserTestHarness() method is available.

    But for API below 29:

    Developers can add their own custom property:

    subprojects {
        tasks.withType(Test).all {
            systemProperty "is-test-run", "true"
        }
    }
    

    which then needs to be checked somehow:

    public static boolean isTestRun() {
         return "true".equals(System.getProperty("is-test-run", "false"));
    }
    
    0 讨论(0)
  • 2021-01-04 11:28

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

    public boolean isUnitTest() {
            String device = Build.DEVICE;
            String product = Build.PRODUCT;
            if (device == null) {
                device = "";
            }
    
            if (product == null) {
                product = "";
            }
            return device.equals("robolectric") && product.equals("robolectric");
        }
    
    0 讨论(0)
  • 2021-01-04 11:32

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

    0 讨论(0)
  • 2021-01-04 11:41

    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)

    private boolean isTesting() {
        try {
            Class.forName("com.company.SomeTestClass");
            return true;
        } catch (ClassNotFoundException e) {
            return false;
        }
    }
    
    0 讨论(0)
提交回复
热议问题