Merlin (they)
10/19/2023, 11:23 PMMethod getSystem in android.content.res.Resources not mocked
.
So I've tried using mockk
and mocking Resources both with mockk<Resources>()
or with mockkStatic
but then I get errors like Missing mocked calls inside every { ... } block: make sure the object inside the block is a mock
I'm very new to Android/Kotlin dev in general, so I'm probably doing this very wrong or doing something unnecessary, but I'll take any advice.
Should I even test this extension that seems pretty basic?
Should I be doing an instrumentation test and not a unit test?
If I should do this unit test, how do I mock it successfully?
Side note: what's the difference between this channel and #testing?
Extension Code
package com.package.messages.extensions
import android.content.res.Resources
import kotlin.math.roundToInt
val Int.dp: Int
get() = (this * Resources.getSystem().displayMetrics.density).roundToInt()
Attempted Test Code
import android.content.res.Resources
import android.util.DisplayMetrics
import io.mockk.every
import io.mockk.mockk
import io.mockk.mockkStatic
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Test
import kotlin.math.roundToInt
// TODO Fix test with mock
class IntTest {
@Test
fun testDpExtension() {
val expectedDp = 10
val mockResources = mockk<Resources>("mockResources")
val mockStaticResources = mockkStatic(Resources::class)
val mockDisplayMetrics = mockk<DisplayMetrics>("mockDisplayMetrics")
val mockStaticDisplayMetrics = mockkStatic(DisplayMetrics::class)
every { mockResources.getDisplayMetrics() } returns mockDisplayMetrics
every { mockDisplayMetrics.density } returns 1F
// Method getSystem in android.content.res.Resources not mocked
val expectedPixels = (expectedDp * Resources.getSystem().displayMetrics.density).roundToInt()
val actualDp = expectedDp.dp
assertEquals(expectedPixels, actualDp)
}
}
kevindmoore
10/20/2023, 3:27 PM