Application.class mock in Android UnitTest

爱⌒轻易说出口 提交于 2021-01-07 04:14:51

问题


I have an Application class.

open class AppController : MultiDexApplication() {

    companion object {

        @JvmStatic
        lateinit var instance: AppController
            private set

    }

    override fun onCreate() {
        super.onCreate()

        instance = this
    }

}

I use my code for extension. Int.kt

fun Int.pxToDp(): Int {
    return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_PX, this.toFloat(), AppControllerMaster.instance.applicationContext.resources.displayMetrics).toInt()
}

I need to use that in a unit test. when use that I get this error

kotlin.UninitializedPropertyAccessException: lateinit property instance has not been initialized

I need to create a mock or alternative AppController.class in my unit test.

I need to use it in UnitTest, not androidTest.

how can Application Crete or mock in UNITTEST?


回答1:


Refer http://robolectric.org/

Robolectric is a framework that brings fast and reliable unit tests to Android.
Tests run inside the JVM on your workstation in seconds




回答2:


I found an answer without using Robolectric.

I create a function extension in package com.example in class with the name ContextEX.kt

ContextEX.kt

fun Any.getContextEX(): Context {
    return AppController.instance
}

and change pxToDp extention.

change AppControllerMaster.instance.applicationContext to getContextEX().

fun Int.pxToDp(): Int {
    return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_PX, this.toFloat(), getContextEX().resources.displayMetrics).toInt()
}

and in the test, I mock Application class and context extension with Mockk library

val context: Context = spyk()

// Mock Context extension
mockkStatic("com.example.ContextEXKt") // notic: not ContextEX.kt

val metrics: DisplayMetrics = mockk()
val resources: Resources = mockk()

every {
   any<Any>().getContext()
}.answers {
   context
}

every {
   any<Any>().getContext().resources
}.answers {
   resources
}

every {
   any<Any>().getContext().resources.displayMetrics
}.answers {
   metrics
}


来源:https://stackoverflow.com/questions/64447822/application-class-mock-in-android-unittest

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