개발하는 두더지

Module with the Main dispatcher had failed to initialize. 본문

Java,Android

Module with the Main dispatcher had failed to initialize.

덜지 2019. 12. 4. 14:19

Module with the Main dispatcher had failed to initialize. For tests Dispatchers.setMain from kotlinx-coroutines-test module can be used

JUnit 에서 Coroutine 을 사용하면서 위와 같은 에러메시지가 발생했다.

  1. 코루틴 테스트 라이브러리 추가

testImplementation "org.jetbrains.kotlinx:kotlinx-coroutines-test:$coroutinesVersion"
androidTestImplementation "org.jetbrains.kotlinx:kotlinx-coroutines-test:$coroutinesVersion"

   

    2. 코루틴 Rule 생성

@ExperimentalCoroutinesApi
class MainCoroutineRule : TestWatcher(), TestCoroutineScope by TestCoroutineScope() {
    override fun starting(description: Description?) {
        super.starting(description)
        Dispatchers.setMain(this.coroutineContext[ContinuationInterceptor] as CoroutineDispatcher)
    }

    override fun finished(description: Description?) {
         super.finished(description)
         Dispatchers.resetMain()
    }

 

    3. 테스트 코드에 Rule 선언

@ExperimentalCoroutinesApi
@get:Rule
var mainCoroutineRule = MainCoroutineRule()

 

    4. 필요한 곳에서 사용

@After
fun releaseViewModel() = mainCoroutineRule.runBlockingTest {
     tasksViewModel.deleteAllTasks()
}

@Test
fun loadAllTasksFromRepository_loadingTogglesAndDataLoaded() {
    mainCoroutineRule.pauseDispatcher()

    tasksViewModel.setFiltering(TasksFilterType.ALL_TASKS)

    tasksViewModel.loadTasks(true)

    assertThat(LiveDataTestUtil.getValue(tasksViewModel.dataLoading)).isTrue()

    mainCoroutineRule.resumeDispatcher()

    assertThat(LiveDataTestUtil.getValue(tasksViewModel.dataLoading)).isFalse()

    assertThat(LiveDataTestUtil.getValue(tasksViewModel.items)).hasSize(3)
}

Comments