LoginSignup
1
0

【Android】Kotlinのテストコードを書いていてエラーになった時の話【Kotlin】

Posted at

エラー内容

Exception in thread "Test worker @coroutine#1" java.lang.IllegalStateException: Module with the Main dispatcher had failed to initialize. For tests Dispatchers.setMain from kotlinx-coroutines-test module can be used

やったこと

上のエラーを翻訳をかけた感じ、ざっくりいうと
kotlinx-coroutines-test モジュールの Dispatchers.setMain が必要とのこと。

kotlinx-coroutines-test で検索をかけてみると

このライブラリが出てきたので追加してみた。

build.gradle(Module :app)
dependencies {
    testImplementation 'org.jetbrains.kotlinx:kotlinx-coroutines-test:1.8.0'


    
    }

テストコード内では、以下をテストしたいコードよりも前に追加

    @Before
    fun setUp() {
        Dispatchers.setMain(Dispatchers.Unconfined)
    }

    @After
    fun tearDown() {
        Dispatchers.resetMain()
        mainThreadSurrogate.close()
    }

これで実行したところIllegalStateExceptionのエラーは出なくなり、テストが実行できた。

そもそもテストコードを実行するのに先ほど追加したライブラリーが必要みたいです。

参考

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0