【发布时间】:2023-01-28 12:54:01
【问题描述】:
我正在尝试使用 junit4 测试房间数据库,当我开始运行测试时我正在使用流和协程我得到kotlinx.coroutines.test.UncompletedCoroutinesError: After waiting for 60000 ms, the test coroutine is not completing, there were active child jobs: [DispatchedCoroutine{Active}@773f274]
我之前尝试过使用 runBlocking 和 runBlockingTest 和 runTest
测试类->
@RunWith(AndroidJUnit4::class) // Annotate with @RunWith
class TaskDatabaseTest {
@get:Rule
var instatExecutorRule = InstantTaskExecutorRule()
private lateinit var database: TaskDatabase
private lateinit var dao: TaskDao
private val testCoroutineDispatcher = StandardTestDispatcher()
private val testCoroutineScope = TestScope(testCoroutineDispatcher)
@Before
fun setup() {
Dispatchers.setMain(testCoroutineDispatcher)
database = Room.inMemoryDatabaseBuilder(
ApplicationProvider.getApplicationContext(),
TaskDatabase::class.java
).allowMainThreadQueries().build()
dao = database.taskDao()
}
@After
fun tearDown() {
database.close()
}
@Test
fun insert() = testCoroutineScope.runTest {
// Arrange
val task = Task("do exercise", id = 1)
dao.insert(task)
val tasks = dao.getTasksSortedByName("", false).toList()
assertThat(tasks).contains(task)
}}
【问题讨论】:
标签: android kotlin junit android-room kotlin-coroutines