LiveData使ってるクラスのテストをSpekで書こうとするとよく出てくるエラー。
エラー内容
Method getMainLooper in android.os.Looper not mocked. See http://g.co/androidstudio/not-mocked for details.
テスト用のTaskExecutorを用意する
class TestArchTaskExecutor : TaskExecutor() {
override fun executeOnDiskIO(runnable: Runnable) {
runnable.run()
}
override fun isMainThread(): Boolean {
return true
}
override fun postToMainThread(runnable: Runnable) {
runnable.run()
}
}
SpekのGroupBodyに拡張関数を追加
fun GroupBody.applyTestTaskExecutor(executor: TaskExecutor = TestArchTaskExecutor()) {
beforeGroup {
ArchTaskExecutor.getInstance().setDelegate(executor)
}
afterGroup {
ArchTaskExecutor.getInstance().setDelegate(null)
}
}
テストでSpekのBodyで拡張関数を呼び出す
internal object ViewModelTest : Spek({
applyTestTaskExecutor()
Feature("...") {}
}