Android unit testing flow with multiple emit

Viewed 2331

I have my use case that talks to repository and emits multiple data as below -

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

    override fun performAction(action: MyAction) = flow {
        emit(MyResult.Loading)
        emit(myRepoInterface.getData(action))
    }
}

The unit test for the same looks like this below -

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"))
            }
        }
    }
}

After running the test I get this error -

java.lang.AssertionError: 
Expected : MyResult$Loading@4f32a3ad
Actual   : MyResult.Data("data")

How do I test the use case that emits multiple things?

1 Answers

You can create a list with the toList operator. Then you can assert on that list:

@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")))
}
Related