I have a function which uses a field in DisplayMetrics
of Resources
of Context
class:
fun getIconForDevice(context: Context, iconUrl: String): String {
val metrics = context.resources.displayMetrics
var suffix = ""
//below checks MUST be in this increasing order or it may failed
if (metrics.densityDpi <= DisplayMetrics.DENSITY_MEDIUM)
suffix = "-m"
else if (metrics.densityDpi <= DisplayMetrics.DENSITY_HIGH)
suffix = "-h"
else if (metrics.densityDpi <= DisplayMetrics.DENSITY_XHIGH)
suffix = "-xh"
else if (metrics.densityDpi <= DisplayMetrics.DENSITY_XXHIGH || metrics.densityDpi > DisplayMetrics.DENSITY_XXHIGH)
suffix = "-xxh"
val pasvand = iconUrl.substring(iconUrl.lastIndexOf("."))
val str = iconUrl.substring(0, iconUrl.lastIndexOf(".")) + suffix + pasvand
return str
}
In order to test it, I need to mock Context
and metrics.densityDpi
to give it a value.
I'm using Mockk (1.9.3) library to do that.
@Test
fun getIconForDevice_ReturnsUrlWithXxhForXxhDisplay() {
val context: Context = mockk(relaxed = true)
every { context.resources.displayMetrics.densityDpi } returns 450
assertEquals(IconHelper.getIconForDevice(context,
"https://website.com/image.png"), "https://website.com/image-xxh.png")
}
Running the test following error stacktrace is given:
java.lang.ClassCastException: java.lang.Integer cannot be cast to android.util.DisplayMetrics
at ...Resources.getDisplayMetrics(Resources.java)
at ....IconHelper.getIconForDevice(IconHelper.kt:39)
at ...IconHelperTest.getIconForDevice_ReturnsUrlWithXxhForXxhDisplay(IconHelperTest.kt:30)
The first link refers to val metrics = context.resources.displayMetrics
line of the actual function
So how can I mock such a nested field in mockk?
context.resources.displayMetrics.densityDpi