Step #2: Initializing Our Repository

Next, replace the current implementation of RosterListFragmentTest with this:

package com.commonsware.todo.ui.roster

import androidx.test.platform.app.InstrumentationRegistry
import com.commonsware.todo.repo.ToDoDatabase
import com.commonsware.todo.repo.ToDoModel
import com.commonsware.todo.repo.ToDoRepository
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.runBlocking
import org.junit.Before
import org.koin.core.context.loadKoinModules
import org.koin.dsl.module

class RosterListFragmentTest {
  private lateinit var repo: ToDoRepository
  private val items = listOf(
    ToDoModel("this is a test"),
    ToDoModel("this is another test"),
    ToDoModel("this is... wait for it... yet another test")
  )

  @Before
  fun setUp() {
    val context = InstrumentationRegistry.getInstrumentation().targetContext
    val db = ToDoDatabase.newTestInstance(context)
    val appScope = CoroutineScope(SupervisorJob())

    repo = ToDoRepository(db.todoStore(), appScope)

    loadKoinModules(module {
      single { repo }
    })

    runBlocking { items.forEach { repo.save(it) } }
  }
}

As with ToDoRepositoryTest, we are creating our own ToDoRepository instance. That way, we can have a fresh one for each test run, and we do not need to worry about the results of a previous test affecting the next test. However, there is one small problem: the activity and fragments know nothing about this test repository. They will want to use the one supplied by Koin.

So, via loadKoinModules(), we replace the repository that Koin normally would return with a fresh instance. loadKoinModules() works in conjunction with the single() to replace the true singleton ToDoRepository with this replacement instance.

We then populate our test repository with three model objects, using save() on the repository, wrapped in runBlocking() to have that work happen on the current thread.


Prev Table of Contents Next

This book is licensed under the Creative Commons Attribution-ShareAlike 4.0 International license.