简体   繁体   English

使用 emitAll 对流进行 Android 单元测试

[英]Android unit testing for flow with emitAll

I have a function that return flow by emitAll我有一个通过 emitAll 返回流的函数

 fun handle(actions: MoviesActions): Flow<MoviesStates> = flow {
    when (actions) {
        is MoviesActions.LoadMovies -> {
            emit(MoviesStates.Loading)
            emitAll(moviesUseCase.execute())
        }
    }
}

And this the use case function这是用例功能

suspend fun execute(): Flow<MoviesStates> = flow {
    combine(f1, f2) { state1: MoviesStates, state2: MoviesStates ->
     
          // some code
        
    }.collect {
        emit(it)
    }
}

No problem in testing the first emission MoviesStates.Loading , the problem is when I try to test the flow which return from usecase by emitAll emitAll(moviesUseCase.execute()) , the test fails and I got this result测试第一个发射MoviesStates.Loading没有问题,问题是当我尝试通过 emitAll emitAll(moviesUseCase.execute())测试从用例返回的流时,测试失败,我得到了这个结果

java.util.NoSuchElementException: Expected at least one element java.util.NoSuchElementException:至少需要一个元素

this is my unit test这是我的单元测试

@Test
fun testLoadMovies() = runBlocking {
    whenever(useCase.execute()).thenReturn(flow {
        MoviesStates.EmptyList
    })

    val actual = viewModel.handle(MoviesActions.LoadMovies).drop(1).first()
    val expected = MoviesStates.EmptyList

    assertEquals(actual, expected)
}

So How can I test it correctly?那么如何正确测试呢?

Thanks to gpunto , this is the solution he suggested感谢gpunto ,这是他建议的解决方案

@Test
fun testLoadMovies() = runTest {
    whenever(useCase.execute()).thenReturn(flow {
         MoviesStates.EmptyList
    })

    useCase.execute().collectLatest { states ->
        val actual = viewModel.handle(MoviesActions.LoadMovies).drop(1).first()
        val expected = states 
        assertEquals(expected, actual)
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM