使用 StateFlow 和协程的单元测试 viewModel
Unit testing viewModel that uses StateFlow and Coroutines
Kotlin 1.4.21
我有一个非常简单的 ViewModel,它使用协程和 stateFlow。但是,单元测试将失败,因为 stateFlow 似乎没有得到更新。
我认为是因为测试将在 stateFlow
更新之前完成。
expected not to be empty
这是我正在测试的 ViewModel
class TrendingSearchViewModel @Inject constructor(
private val loadTrendingSearchUseCase: LoadTrendingSearchUseCase,
private val coroutineDispatcher: CoroutineDispatcherProvider
) : ViewModel() {
private val trendingSearchMutableStateFlow = MutableStateFlow<List<String>>(emptyList())
val trendingSearchStateFlow = trendingSearchMutableStateFlow.asStateFlow()
fun getTrendingSearch() {
viewModelScope.launch(coroutineDispatcher.io()) {
try {
trendingSearchMutableStateFlow.value = loadTrendingSearchUseCase.execute()
} catch (exception: Exception) {
Timber.e(exception, "trending ${exception.localizedMessage}")
}
}
}
}
这是我的实际测试class,我尝试了不同的方法让它工作
class TrendingSearchViewModelTest {
private val loadTrendingSearchUseCase: LoadTrendingSearchUseCase = mock()
private val coroutineDispatcherProvider = CoroutineDispatcherProviderImp()
private lateinit var trendingSearchViewModel: TrendingSearchViewModel
@Before
fun setUp() {
trendingSearchViewModel = TrendingSearchViewModel(
loadTrendingSearchUseCase,
coroutineDispatcherProvider
)
}
@Test
fun `should get trending search suggestions`() {
runBlocking {
// Arrange
val trending1 = UUID.randomUUID().toString()
val trending2 = UUID.randomUUID().toString()
val trending3 = UUID.randomUUID().toString()
whenever(loadTrendingSearchUseCase.execute()).thenReturn(listOf(trending1, trending2, trending3))
val job = launch {
trendingSearchViewModel.trendingSearchStateFlow.value
}
// Act
trendingSearchViewModel.getTrendingSearch()
// Assert
val result = trendingSearchViewModel.trendingSearchStateFlow.value
assertThat(result).isNotEmpty()
job.cancel()
}
}
}
这是我在测试中模拟的用例:
class LoadTrendingSearchUseCaseImp @Inject constructor(
private val searchCriteriaProvider: SearchCriteriaProvider,
private val coroutineDispatcherProvider: CoroutineDispatcherProvider
) : LoadTrendingSearchUseCase {
override suspend fun execute(): List<String> {
return withContext(coroutineDispatcherProvider.io()) {
searchCriteriaProvider.provideTrendingSearch().trendingSearches
}
}
}
以防万一,这是我的界面:
interface CoroutineDispatcherProvider {
fun io(): CoroutineDispatcher = Dispatchers.IO
fun default(): CoroutineDispatcher = Dispatchers.Default
fun main(): CoroutineDispatcher = Dispatchers.Main
fun immediate(): CoroutineDispatcher = Dispatchers.Main.immediate
fun unconfined(): CoroutineDispatcher = Dispatchers.Unconfined
}
class CoroutineDispatcherProviderImp @Inject constructor() : CoroutineDispatcherProvider
我认为 Jack Wharton 的这个库 https://github.com/cashapp/turbine 将来在您需要更复杂的场景时会有很大帮助。
我认为正在发生的事情是您在片段中调用 .collect { }
并且确保流程已启动。检查终端运算符定义:流上的终端运算符正在暂停函数启动流的集合。 https://kotlinlang.org/docs/flow.html#terminal-flow-operators
sharedFlow 并非如此,它可能被配置为急切启动。
所以要解决您的问题,您可以拨打
val job = launch {
trendingSearchViewModel.trendingSearchStateFlow.collect()
}
这对我有用:
@Test
fun `should get trending search suggestions`() {
runBlockingTest {
// Arrange
val trending1 = UUID.randomUUID().toString()
val trending2 = UUID.randomUUID().toString()
val trending3 = UUID.randomUUID().toString()
val listOfTrending = listOf(trending1, trending2, trending3)
whenever(loadTrendingSearchUseCase.execute()).thenReturn(listOfTrending)
/* List to collect the results */
val listOfEmittedResult = mutableListOf<List<String>>()
val job = launch {
trendingSearchViewModel.trendingSearchStateFlow.toList(listOfEmittedResult)
}
// Act
trendingSearchViewModel.getTrendingSearch()
// Assert
assertThat(listOfEmittedResult).isNotEmpty()
verify(loadTrendingSearchUseCase).execute()
job.cancel()
}
}
Kotlin 1.4.21
我有一个非常简单的 ViewModel,它使用协程和 stateFlow。但是,单元测试将失败,因为 stateFlow 似乎没有得到更新。
我认为是因为测试将在 stateFlow
更新之前完成。
expected not to be empty
这是我正在测试的 ViewModel
class TrendingSearchViewModel @Inject constructor(
private val loadTrendingSearchUseCase: LoadTrendingSearchUseCase,
private val coroutineDispatcher: CoroutineDispatcherProvider
) : ViewModel() {
private val trendingSearchMutableStateFlow = MutableStateFlow<List<String>>(emptyList())
val trendingSearchStateFlow = trendingSearchMutableStateFlow.asStateFlow()
fun getTrendingSearch() {
viewModelScope.launch(coroutineDispatcher.io()) {
try {
trendingSearchMutableStateFlow.value = loadTrendingSearchUseCase.execute()
} catch (exception: Exception) {
Timber.e(exception, "trending ${exception.localizedMessage}")
}
}
}
}
这是我的实际测试class,我尝试了不同的方法让它工作
class TrendingSearchViewModelTest {
private val loadTrendingSearchUseCase: LoadTrendingSearchUseCase = mock()
private val coroutineDispatcherProvider = CoroutineDispatcherProviderImp()
private lateinit var trendingSearchViewModel: TrendingSearchViewModel
@Before
fun setUp() {
trendingSearchViewModel = TrendingSearchViewModel(
loadTrendingSearchUseCase,
coroutineDispatcherProvider
)
}
@Test
fun `should get trending search suggestions`() {
runBlocking {
// Arrange
val trending1 = UUID.randomUUID().toString()
val trending2 = UUID.randomUUID().toString()
val trending3 = UUID.randomUUID().toString()
whenever(loadTrendingSearchUseCase.execute()).thenReturn(listOf(trending1, trending2, trending3))
val job = launch {
trendingSearchViewModel.trendingSearchStateFlow.value
}
// Act
trendingSearchViewModel.getTrendingSearch()
// Assert
val result = trendingSearchViewModel.trendingSearchStateFlow.value
assertThat(result).isNotEmpty()
job.cancel()
}
}
}
这是我在测试中模拟的用例:
class LoadTrendingSearchUseCaseImp @Inject constructor(
private val searchCriteriaProvider: SearchCriteriaProvider,
private val coroutineDispatcherProvider: CoroutineDispatcherProvider
) : LoadTrendingSearchUseCase {
override suspend fun execute(): List<String> {
return withContext(coroutineDispatcherProvider.io()) {
searchCriteriaProvider.provideTrendingSearch().trendingSearches
}
}
}
以防万一,这是我的界面:
interface CoroutineDispatcherProvider {
fun io(): CoroutineDispatcher = Dispatchers.IO
fun default(): CoroutineDispatcher = Dispatchers.Default
fun main(): CoroutineDispatcher = Dispatchers.Main
fun immediate(): CoroutineDispatcher = Dispatchers.Main.immediate
fun unconfined(): CoroutineDispatcher = Dispatchers.Unconfined
}
class CoroutineDispatcherProviderImp @Inject constructor() : CoroutineDispatcherProvider
我认为 Jack Wharton 的这个库 https://github.com/cashapp/turbine 将来在您需要更复杂的场景时会有很大帮助。
我认为正在发生的事情是您在片段中调用 .collect { }
并且确保流程已启动。检查终端运算符定义:流上的终端运算符正在暂停函数启动流的集合。 https://kotlinlang.org/docs/flow.html#terminal-flow-operators
sharedFlow 并非如此,它可能被配置为急切启动。
所以要解决您的问题,您可以拨打
val job = launch {
trendingSearchViewModel.trendingSearchStateFlow.collect()
}
这对我有用:
@Test
fun `should get trending search suggestions`() {
runBlockingTest {
// Arrange
val trending1 = UUID.randomUUID().toString()
val trending2 = UUID.randomUUID().toString()
val trending3 = UUID.randomUUID().toString()
val listOfTrending = listOf(trending1, trending2, trending3)
whenever(loadTrendingSearchUseCase.execute()).thenReturn(listOfTrending)
/* List to collect the results */
val listOfEmittedResult = mutableListOf<List<String>>()
val job = launch {
trendingSearchViewModel.trendingSearchStateFlow.toList(listOfEmittedResult)
}
// Act
trendingSearchViewModel.getTrendingSearch()
// Assert
assertThat(listOfEmittedResult).isNotEmpty()
verify(loadTrendingSearchUseCase).execute()
job.cancel()
}
}