"testBuildType" 可以在 Android 项目的 build.gradle 文件中有条件吗?

Can "testBuildType" be conditional in build.gradle file of Android project?

我的应用程序有 2 种构建类型:调试和发布。

我想对两种构建类型执行测试。

但目前只测试了一种构建类型。默认情况下它是调试构建类型,但这可以重新配置: android{ ... 测试构建类型 "release" }

我想在不更改 gradle 文件的情况下一一执行 connectedDebugAndroidTestconnectedReleaseAndroidTest

是否可以使 "testBuildType" 成为条件? 因此,根据 gradle 任务中的构建变体(connectedDebugAndroidTest 和 connectedReleaseAndroidTest),它将对该构建执行测试。

我不确定,但这对我有用。如果你想在应用程序中根据构建变量(调试和发布)执行代码,那么你可以使用以下代码。

这是 Activity java 文件。

public void printMessage()
{
    if (BuildConfig.DEBUG)
    {
        //App is in debug mode
    }
    else
    {
        //App is released
    }
}

如果您想签入 build.gradle 文件,请按照以下代码执行。

First way

buildTypes {
    debug {
      buildConfigField "String", "SERVER_URL", '"http://test.this-is-so-fake.com"'
    }

    release {
      buildConfigField "String", "SERVER_URL", '"http://prod.this-is-so-fake.com"'
    }

    mezzanine.initWith(buildTypes.release)

    mezzanine {
        buildConfigField "String", "SERVER_URL", '"http://stage.this-is-so-fake.com"'
    }
}

Second way

android {
    testBuildType obtainTestBuildType()
}

def obtainTestBuildType() {
    def result = "debug";

    if (project.hasProperty("testBuildType")) {
        result = project.getProperties().get("testBuildType")
    }

    result
}

有关详细信息,请查看 this, this and this Whosebug 答案。

我希望你能得到你的解决方案。