I am trying to Mock my Room Database with Mockito so that I can test the complicated algorithms in my Repository. I am getting a slew of different errors no matter what direction I step in.
First I tried just Mocking the overall database object, this created a null interface exception.
To solve this problem, I used the Room's static object builder. (This is an instrumented unit test, so I have access to underlying Android dependencies)
import org.mockito.*
import org.mockito.Mockito.`when`
import org.mockito.Mockito.anyDouble
class BasicReposTest {
@get:Rule
val activityRule = ActivityTestRule(MainActivity::class.java)
@get:Rule
val mockitoRule: MockitoRule = MockitoJUnit.rule()
@Mock
lateinit var mockedDb : AppDatabase
@Before
fun setTheDatabase() {
val context = ApplicationProvider.getApplicationContext<Context>()
mockedDb = Room.inMemoryDatabaseBuilder(
context, AppDatabase::class.java).build()
}
@Test
fun doesReposRequestBounds() {
`when`(mockedDb.momentDao().findMomentsByBound(ArgumentMatchers.anyDouble(), ArgumentMatchers.anyDouble(),
anyDouble(), ArgumentMatchers.anyDouble())).thenReturn(momentList)
//Request first set of moments
repos.queryMapMoments(bounds, 20.toFloat())
//Do we get a list of moments sent to livedata?
assertTrue(mappedMoments.value!!.size >= momentList.size)
val list : List<Moment> = mappedMoments.value!!
for (value in list) {
System.out.println("D " + "RequestMomentsFromDatabaseByBoundsTest " + "MID = " + value.mId )
}
}
With this, I receive a misused matcher exception... +++++++++++++++++++++++++++++++++++++++++++++++++++++++++
org.mockito.exceptions.misusing.InvalidUseOfMatchersException: Misplaced or misused argument matcher detected here:
-> at com.example.barrechat108.RepositoryTests.doesReposRequestBounds(RepositoryTests.kt:138) -> at com.example.barrechat108.RepositoryTests.doesReposRequestBounds(RepositoryTests.kt:138) -> at com.example.barrechat108.RepositoryTests.doesReposRequestBounds(RepositoryTests.kt:139) -> at com.example.barrechat108.RepositoryTests.doesReposRequestBounds(RepositoryTests.kt:139)`
You cannot use argument matchers outside of verification or stubbing. ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
When testing you can construct your room database as an in memory database. So everything stored will only last until the process is closed. So nothing will persist, perfect for tests!
Code:
Room.inMemoryDatabaseBuilder(context, TestDatabase::class.java).build()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With