Mjahangiry75
05/03/2022, 6:40 PMStateFlow
if I use stateIn
function then I can't test the stateFlow
using CoroutineTestRule
code in threadMjahangiry75
05/03/2022, 6:41 PM@OptIn(FlowPreview::class)
val state: StateFlow<SearchMovieState> =
searchQuery
.filter {
it.isNotBlank()
}
.transform {
emitAll(repository.searchMovieByTitle(it))
}
.debounce(700)
.map(::reduce)
.stateIn(viewModelScope, SharingStarted.Lazily, SearchMovieState.initial())
Test
@ExperimentalCoroutinesApi
class SearchMovieViewModelTest {
@ExperimentalCoroutinesApi
@get:Rule
val coroutineTestRule = CoroutinesTestRule()
private val repository: SubtitleRepository = mock()
private val viewModel = SearchMovieViewModel(repository)
@Test
fun `test search movie event`() = runTest {
val mockData = MockData.mockSearchMovieResult
whenever(repository.searchMovieByTitle("hello")).thenReturn(flowOf(mockData))
viewModel.search("hello")
val result = viewModel.state
.filter {
it.result.isNotEmpty()
}
.first()
result shouldNotBe null
result.result.size shouldBe 2
}
}