Skip to content

Instantly share code, notes, and snippets.

@voghDev
Last active July 13, 2025 04:26
Show Gist options
  • Save voghDev/8d874f71d2481a66d3c9155df2e21250 to your computer and use it in GitHub Desktop.
Save voghDev/8d874f71d2481a66d3c9155df2e21250 to your computer and use it in GitHub Desktop.
Quick workaround to mock a context.getResources().getStringArray(...), in Kotlin
@Mock
lateinit var mockContext: Context
@Mock
lateinit var mockResources: Resources
@Before
fun setUp() {
MockitoAnnotations.initMocks(this)
}
protected fun givenThatAllStringsAreMocked() {
whenever(mockContext.getString(anyInt())).thenReturn("-")
whenever(mockContext.resources).thenReturn(mockResources)
whenever(mockResources.getStringArray(anyInt())).thenReturn(arrayOf(
"-", "-", "-", "-", "-", "-", "-", "-"
))
}
@voghDev
Copy link
Author

voghDev commented Sep 29, 2017

Cleaner way to avoid mocking Context, or Resources

interface GetStringArray {
    fun getStringArray(id: Int) : List<String>
}

class GetStringArrayImpl(val appContext: Context) : GetStringArray {
    override fun getStringArray(id: Int) : List<String> {
        return appContext.resources.getStringArray(id)
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment