我有一个与存储库对话并发出多个数据的用例,如下所示-
class MyUseCase(private val myRepoInterface: MyRepoInterface) : MyUseCaseInterface {
override fun performAction(action: MyAction) = flow {
emit(MyResult.Loading)
emit(myRepoInterface.getData(action))
}
}同样的单元测试如下所示-
class MyUseCaseTest {
@get:Rule
val instantExecutorRule = InstantTaskExecutorRule()
@Mock
private lateinit var myRepoInterface: MyRepoInterface
private lateinit var myUseCaseInterface: MyUseCaseInterface
@Before
fun setUp() {
MockitoAnnotations.initMocks(this)
myUseCaseInterface = MyUseCase(myRepoInterface)
}
@After
fun tearDown() {
}
@Test
fun test_myUseCase_returnDataSuccess() {
runBlocking {
`when`(myRepoInterface.getData(MyAction.GetData))
.thenReturn(MyResult.Data("data"))
// Test
val flow = myUseCaseInterface.performAction(MyAction.GetData)
flow.collect { data ->
Assert.assertEquals(data, MyResult.Loading)
Assert.assertEquals(data, MyResult.Data("data"))
}
}
}
}在运行测试之后,我得到这个错误-
java.lang.AssertionError:
Expected : MyResult$Loading@4f32a3ad
Actual : MyResult.Data("data")如何测试发出多个东西的用例?
发布于 2020-03-31 17:19:17
您可以使用toList运算符创建列表。然后,您可以在该列表上断言:
@Test
fun test_myUseCase_returnDataSuccess() = runBlockingTest {
//Prepare your test here
//...
val list = myUseCaseInterface.performAction(MyAction.GetData).toList()
assertEquals(list, listOf(MyResult.Loading, MyResult.Data("data")))
}https://stackoverflow.com/questions/60946460
复制相似问题