BuildConfigField mock for unit test in Kotlin

╄→尐↘猪︶ㄣ 提交于 2019-12-23 11:05:25

问题


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.

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

Extract from Gradle file :

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

Extract of the Kotlin function to be tested :

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()
}

Unit test :

@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).

Thanks

来源:https://stackoverflow.com/questions/52181057/buildconfigfield-mock-for-unit-test-in-kotlin

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!