BuildConfigField模拟在Kotlin中进行单元测试 [英] BuildConfigField mock for unit test in Kotlin

查看:159
本文介绍了BuildConfigField模拟在Kotlin中进行单元测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试尽可能多地覆盖 Kotlin Android库,并且遇到有关自定义BuildConfig变量(通常称为buildConfigField)的问题.

I'm trying to cover as much as possible a Kotlin Android library and I'm encountering an issue about custom BuildConfig variable, better known as buildConfigField.

我想模拟该变量以同时测试truefalse值.

I would like to mock this variable to test both true and false values.

android {
    defaultConfig {
        buildConfigField "boolean", "ENABLE_LOG", "false"
    }
    flavorDimensions "log"
    productFlavors {
        loggable {
            buildConfigField "boolean", "ENABLE_LOG", "true"
            dimension "log"
        }
        notloggable {
            dimension "log"
        }
    }
}

要测试的Kotlin函数的提取:

fun buildClient(): MyClient {
    var myClientBuilder : MyClient.Builder = MyClient.Builder();

    if (BuildConfig.ENABLE_LOG) {
        val interceptor = LoggingInterceptor();
        interceptor.setLevel(LoggingInterceptor.Level.ALL);
        myClientBuilder.addInterceptor(interceptor);
    }

    return myClientBuilder.build()
}

单元测试:

@Test
fun buildClient_enableLog_oneInterceptor() {
    // GIVEN
    Mockito.mock(BuildConfig::class.java)
    Mockito.doReturn(true).`when`(BuildConfig.ENABLE_LOG)

    // WHEN
    val myClient = myService!!.buildClient()

    // THEN
    assertNotNull(myClient)
    assertNotNull(myClient.interceptors())
    assertEquals(1, myClient.interceptors().size)
}

我尝试了不同的方法,但从未成功. 如果有人已经完成了这项工作,那么它可以对我有很大帮助(我猜还有其他人).

I tried different things and it never works. If someone have already done this work, it can help me a lot (and others I guess).

谢谢

推荐答案

默认情况下,所有测试都针对调试构建类型运行.您可以使用模块级build.gradle文件中的testBuildType属性将其更改为另一种构建类型.例如,如果您想针对您的"staging"进行测试,构建类型,请按以下代码片段所示编辑文件.

By default, all tests run against the debug build type. You can change this to another build type by using the testBuildType property in your module-level build.gradle file. For example, if you want to run your tests against your "staging" build type, edit the file as shown in the following snippet.

android { ... testBuildType登台" } 但这导致其他选项失败

android { ... testBuildType "staging" } but this is causing other options to fail

这篇关于BuildConfigField模拟在Kotlin中进行单元测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆