Define buildConfigField for androidTest
Asked Answered
M

3

13

I'm defining a particular field in the BuildConfig for getting the URL during runtime. So, for each build type, I use a different string:

    prod {
        buildConfigField "String", "BASE_URL", "\"abc.com\""
    }

    debug {
        buildConfigField "String", "BASE_URL", "\"efg.com\""
    }

Is it possible to define a different URL while running the android tests? I tried putting this setting under sourceSets->androidTest, but it's not accepted.

Milfordmilhaud answered 25/11, 2015 at 5:25 Comment(0)
B
4

You have to pass it as a parameter to connectedAndroidTest task.

android {
    ...
    buildTypes {
        prod {
            buildConfigField "String", "BASE_URL", "\"${getBaseUrl("abc.com")}\""
        }
        debug {
            buildConfigField "String", "BASE_URL", "\"${getBaseUrl("efg.com")}\""
        }
    }
}

def getBaseUrl(String fallback) {
    return project.hasProperty("base_url") ? project.getProperties().get("base_url") : fallback
}

Then passing parameters via -P:

./gradlew connectedDebugAndroidTest -Pbase_url="xxx.com"
./gradlew connectedProdAndroidTest  -Pbase_url="yyy.com"
Belindabelisarius answered 6/4, 2017 at 14:47 Comment(1)
Good solution, thank you. The function can be simplified to return project.getOrDefault().get("base_url", fallback)Pinup
C
0

Add custom BuildConfig.java to your.app.package in test/androidTest dir.

Android Studio marks it red but works.

Calais answered 5/10, 2016 at 16:55 Comment(0)
I
0

For anyone who needs that, Use this function to check tests build

boolean isUnitTestBuild() {
    Gradle gradle = getGradle()
    String tskReqStr = gradle.getStartParameter().getTaskRequests().toString()
    Pattern pattern = Pattern.compile("test(\\w*)(Release|Debug)")
    Matcher matcher = pattern.matcher(tskReqStr)

    return matcher.find()
}
Interviewee answered 31/8, 2022 at 22:31 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.