我想模拟服务的方法,但是在不同的上下文中调用此方法,并且返回值为null(dp.search是挂起函数)。看一下我的代码:
@Test
fun `testing mocked method in coroutine`() = testScope.runBlockingTest {
val dp = Mockito.mock(DataProvider::class.java)
Mockito.`when`(dp.search("Any")).thenReturn(listOf())
val data = withContext(Dispatchers.Unconfined) { dp.search("Any")}
// but data is null
Assert.assertEquals(0, data.size)
}
试图检查类似以下两种情况:
首先不使用调度程序!只是调用暂停功能
@Test
fun `testing mocked method in coroutine`() = testScope.runBlockingTest {
val dp = Mockito.mock(DataProvider::class.java)
Mockito.`when`(dp.search("Any")).thenReturn(listOf())
val data = dp.search("Any")
// but data is correct
Assert.assertEquals(0, data.size)
}
比在定义好的上下文中进行嘲笑更好。 (但这不是解决方案。仅用于检查模拟是否有效)
@Test
fun `testing mocked method in coroutine`() = testScope.runBlockingTest {
val dp = Mockito.mock(DataProvider::class.java)
val data = withContext(Dispatchers.Unconfined) {
Mockito.`when`(dp.search("Any")).thenReturn(listOf())
dp.search("Any")
}
//data is correct but this is not a solution for me. search is called in another class
Assert.assertEquals(0, data.size)
}
我应该说这样的设置:
@ExperimentalCoroutinesApi
val testDispatcher = TestCoroutineDispatcher()
val testScope = TestCoroutineScope(testDispatcher)
@ExperimentalCoroutinesApi
@Before
fun initialize() {
Dispatchers.setMain(testDispatcher)
MockitoAnnotations.initMocks(this)
}
@ExperimentalCoroutinesApi
@After
fun tearDown() {
Dispatchers.resetMain()
testScope.cleanupTestCoroutines()
}