Reputation: 12232
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?
Upvotes: 0
Views: 1933
Reputation: 12232
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
}
Upvotes: 1
Reputation: 226
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
Upvotes: 1