https://kotlinlang.org logo
#test
Title
# test
m

Merlin (they)

10/19/2023, 11:23 PM
Hey all, I'm slowly adding tests to my codebase and I'd like to write a unit test for this basic Int extension below. If I leave it as is, I get the error
Method 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
Copy 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
Copy 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)
	}
}
k

kevindmoore

10/20/2023, 3:27 PM
I'm not the best at tests but if you find yourself using Android components in unit tests, then I think you're doing it wrong. Unit tests should just be for testing logic etc that doesn't need Android. Use UI tests when you need resources etc
2 Views