Can I set a BuildConfig flag that returns whether or not an apk is built with the `connectedAndroidTest` gradle task?
Asked Answered
R

1

17

I have parts of my app that I don't want to run if we're running Android unit tests, so I want to surround them with something like

if (!BuildConfig.TESTING) {
  // Code here that I don't want to run during tests.
}

Is it possible to populate this BuildConfig flag depending on whether the connectedAndroidTest gradle task is used? Is this a sane way of approaching this problem?

Racer answered 10/3, 2014 at 21:58 Comment(6)
AFAIK, what you want is not directly possible, as BuildConfig contents are determined by build type. Why aren't you just basing your decision on the build type?Latta
Build type such as DEBUG vs RELEASE? There is some code like things that report to our analytics server that we want running in both DEBUG and RELEASE mode, but not when running through tests.Racer
Then create a third build type for your unit tests. Or consider debug to be for the unit tests and create a third build type for whatever other role you are using for debug at present that requires analytics work.Latta
Please check this. It may be help you.Borries
Another option I've used in the past is to create an IsTest class in the test source package, and then use reflection to check if the class IsTest exists.Disquisition
Maybe you can create flavors and then just create two classes that are a bit different.Favorable
T
-1

This might be a little late, but oh well. Yes you can set BuildConfig fields through your app's gradle file, these will be initialized at build time. For example, I could save a debug flag through gradle like this:

buildTypes {
    release {
        buildConfigField "boolean", "debuggable", "false"

    }

    debug {
        buildConfigField "boolean", "debuggable", "true"
    }
}

And the through code I could access the value like so:

if (!BuildConfig.debuggable) {
        Log.i(TAG, "Application is not Debuggable");
}
Ticino answered 26/10, 2017 at 10:13 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.