1

我正在尝试测试 Android 应用程序中不同阶段的行为。考虑到官方文档BuildTypes,我在模块中使用不同的 Gradlebuild.gradle来定义每个阶段所需的设置。

每个buildType块都包含一个字符串,该字符串具有相似的键STAGE_NAME和每个阶段的不同值,例如test_stageuat_stage

这些值在应用程序中被访问,以相应BuildConfig.STAGE_NAME地更改一些参数,如 API 端点。

但问题是,似乎没有官方方法可以对每个阶段的结果行为进行单元测试。

Android 文档提到了一种更改测试buildType的方法,该方法明确定义了buildType用于测试的测试,但我想知道是否有另一种方法来测试结果行为。

模块的 build.gradle 文件:

android {
    buildTypes {
        release {
            ...
        }
        debug {
            applicationIdSuffix ".debug"
            buildConfigField "String", "STAGE_NAME", "\"debugStage\""
            ...
        }
        testStage {
            initWith(debug)
            buildConfigField "String", "STAGE_NAME", "\"testStage\""
            ...
        }
        uatStage {
            initWith(debug)
            buildConfigField "String", "STAGE_NAME", "\"uatStage\""
            ...
        }
    }
}

示例 Retrofit 接口,它应该通过访问STAGE_NAME并找出应该使用哪些URL 来为每个阶段使用不同的 API URL API_URL

interface FakeService {
    @GET("stuff")
    suspend fun getStuff(): List<Stuff>?

    ...
    
    companion object {

        // Different urls which should be used for each stage:
        private const val URL_DEBUG = "https://debug_api.example.com/"
        private const val URL_TEST = "https://test_api.example.com/
        private const val URL_UAT = "https://uat_api.example.com/"
        private const val URL_PROD = "https://prod_api.example.com/"

        // This is where we access the STAGE_NAME to figure out which stage url should be used
        val API_URL_TO_USE = getUrl(BuildConfig.STAGE_NAME)
        
        fun getUrl(stageName: String?): String {
            return when (stageName) {
                "debugStage" -> URL_DEBUG
                "testStage" -> URL_TEST
                "uatStage" -> URL_QA
                else -> URL_PROD
            }
        }
    }
}

例如,在这个改造界面中,我想测试getUrl函数的行为,以确保它为每个阶段返回正确的 URL。

更新: 看了这个问题之后,我想知道也许一种测试方法,可能是嘲笑BuildConfig. 但由于STAGE_NAME只有在成功构建后才可用,因此无法正常模拟。

4

0 回答 0