How to test with Menu
in a unit test? One can definitely use mocking:
val mockMenuItem = mock<MenuItem>()
val myMockedMenu = mock<Menu> {
when {findItem(any())} doReturn mockMenuItem
}
But you still get NullPointerException
here and there, for example when testing BottomNavigationView
that has its internal implementation of Menu
and MenuItem
. Urgh.
Maybe RoboMenu
from Robolectric
? Makes creating fake easier, for example:
class FakeMenu(val menuItem: MenuItem): RoboMenu() {
val idLookedUp = mutableListOf<Int>()
override fun findItem(id: Int): MenuItem? {
idLookedUp.add(id) // keep the Ids so we can compare later
return menuItem
}
}
With this we can then use something like assertThat()
from Truth
val myFakeMenu = FakeMenu(fakeMenuItem)
... // some test conditions
assertThat(myFakeMenu.idLookedUp).isExactly(listOf(R.menu.menu_item1, R.menu.menu_item9))
versus Mockito’s verify()
syntax.
// how do I check which IDs were looked up without using a Capture?
verify(mockMenu, times(2)).findItem(any())
However, is this a valid use of RoboMenu
? Don’t know. If you know the definite answer, please let me know!