我有一個類,它將協程調度程式作為我要測驗的引數。在我的測驗中,我用來@Before在每次測驗運行之前設定我的課程
@OptIn(ExperimentalCoroutinesApi::class)
@Before
fun setup() = runTest {
.....
val dispatcher = StandardTestDispatcher(testScheduler)
scheduleService = ScheduleService(dispatcher)
}
我有一個我正在嘗試運行的測驗,它有一個SharedFlow我想檢查它的值,所以我也使用runTest那個測驗
@OptIn(ExperimentalCoroutinesApi::class)
@Test
fun testFullScheduleCreation() = runTest{
......
val data = scheduleService.scheduleChangedListener.first()
}
當我嘗試運行測驗時出現錯誤
檢測到使用不同的調度程式。如果您需要使用多個測驗協程調度器,請創建一個 TestCoroutineScheduler 并將其傳遞給它們中的每一個。
該錯誤是因為我使用了@Before但我不確定如何在不將該設定方法中的所有代碼復制到每個測驗的情況下修復該錯誤
uj5u.com熱心網友回復:
有幾種方法可以在測驗之間共享調度程式。最簡單的方法是呼叫Dispatchers.setMain(...)您的設定。如果主調度程式設定為 a TestDispatcher,該runTest函式將使用它進行所有后續測驗。
@Before
fun setup() {
val dispatcher = StandardTestDispatcher()
scheduleService = ScheduleService(dispatcher)
Dispatchers.setMain(dispatcher)
}
如果您使用這種方法,您還應該呼叫Dispatchers.resetMain()一個測驗拆解函式。
如果您更喜歡手動操作,也可以將調度程式傳遞給runTest.
lateinit var dispatcher: TestDispatcher
@Before
fun setup() {
dispatcher = StandardTestDispatcher()
scheduleService = ScheduleService(dispatcher)
}
@Test
fun myTest() = runTest(dispatcher) {
...
}
作為替代方案,您還可以呼叫scope.runTest以使用包含調度程式的共享范圍。
lateinit var scope: TestScope
@Before
fun setup() {
val dispatcher = StandardTestDispatcher()
scope = TestScope(dispatcher)
scheduleService = ScheduleService(dispatcher)
}
@Test
fun myTest() = scope.runTest {
...
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/525285.html
上一篇:約束布局未正確約束
