我有一个用例,它与存储库进行对话并发出多个数据,如下所示-
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")
我如何测试发出多个事件的用例?
答案 0 :(得分:4)
您可以使用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")))
}