Android UnitTest中的Application.class模拟 [英] Application.class mock in Android UnitTest
问题描述
我有一个Application类.
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
}
}
我使用我的代码进行扩展.Int.kt
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
我需要在单元测试中创建一个模拟或替代AppController.class.
I need to create a mock or alternative AppController.class in my unit test.
我需要在UnitTest中使用它,而不是androidTest.
I need to use it in UnitTest, not androidTest.
如何在UNITTEST中应用Crete或模拟?
how can Application Crete or mock in UNITTEST?
推荐答案
我没有使用Robolectric就找到了答案.
I found an answer without using Robolectric.
我在类com.example包中的类ContextEX.kt中创建了一个功能扩展
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
}
并更改pxToDp范围.
and change pxToDp extention.
将 AppControllerMaster.instance.applicationContext
更改为 getContextEX()
.
fun Int.pxToDp(): Int {
return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_PX, this.toFloat(), getContextEX().resources.displayMetrics).toInt()
}
在测试中,我使用Mockk库模拟了Application类和上下文扩展
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
}
这篇关于Android UnitTest中的Application.class模拟的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!