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?

Matthew
  • 6,356
  • 9
  • 47
  • 59
  • 2
    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? – CommonsWare Mar 10 '14 at 22:10
  • 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. – Matthew Mar 10 '14 at 22:14
  • 2
    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. – CommonsWare Mar 10 '14 at 22:18
  • 1
    Please [check this.](https://developer.android.com/studio/test/index.html#change_the_test_build_type) It may be help you. – Sanjay Kakadiya May 30 '17 at 12:22
  • 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. – gyoda Jul 14 '17 at 16:18
  • Maybe you can create flavors and then just create two classes that are a bit different. – Hoochwo Aug 29 '17 at 14:46

1 Answers1

-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");
}
riadrifai
  • 1,108
  • 2
  • 13
  • 26