具有多个发射的 Android 单元测试流程

Ma2*_*340 7 junit android android-livedata kotlin-coroutines

我的用例与存储库通信并发出多个数据,如下所示 -

class MyUseCase(private val myRepoInterface: MyRepoInterface) : MyUseCaseInterface {

    override fun performAction(action: MyAction) = flow {
        emit(MyResult.Loading)
        emit(myRepoInterface.getData(action))
    }
}
Run Code Online (Sandbox Code Playgroud)

相同的单元测试如下所示 -

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"))
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

运行测试后我收到此错误 -

java.lang.AssertionError: 
Expected : MyResult$Loading@4f32a3ad
Actual   : MyResult.Data("data")
Run Code Online (Sandbox Code Playgroud)

如何测试发出多种事物的用例?

Gle*_*val 5

您可以使用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")))
}
Run Code Online (Sandbox Code Playgroud)