如何测试SnapshotStateList正在更新

问题描述 投票:0回答:1

我有

class MyViewModel(private val activitiesRepo: ActivitiesRepo) : ViewModel() {

    val activities = mutableStateListOf<Activity>()

    private var activitiesFlow =
        activitiesRepo.getAllActivitiesFlow().shareInViewModel(viewModelScope)

    fun initialize() {
        fetchActivities()
        collectActivities()
    }

    private fun fetchActivities() =
        viewModelScope.launch {
            activitiesRepo.fetchAllActivities()
        }

    private fun collectActivities() = viewModelScope.launch {
        activitiesFlow.collectLatest { newActivities ->
            [email protected]()
            [email protected](newActivities)
        }
    }
}

并且我想测试

activities
状态是否已使用
collectActivities()

中收集的数据进行更新

我尝试了很多方法,但

activities
始终是一个空的快照状态列表。 这是我尝试过的一个例子:

class MyViewModelTest {

    private val activitiesRepo: ActivitiesRepo = mockk(relaxed = true)
    private lateinit var viewModel: MyViewModel

    @Before
    fun setUp() {
        Dispatchers.setMain(testDispatcher)
        viewModel = ParkingsViewModel(activitiesRepo = activitiesRepo)
    }


    @Test
    fun `initialize updates activities list`() = runTest {
        val mockActivities = listOf(Activity(id = 1))
        every { activitiesRepo.getAllActivitiesFlow() } returns flowOf(mockActivities)
        
        // Launch the collection of activities in the ViewModel
        viewModel.initialize()

        advanceUntilIdle()

        assertThat(viewModel.activities).containsExactlyElementsIn(mockActivities)
    }

    @AfterEach
    fun tearDown() {
        Dispatchers.resetMain()
    }
}
android testing coroutine kotlin-flow mockk
1个回答
0
投票

这就是为什么你不应该在视图模型中使用

MutableState
的原因之一:https://stackoverflow.com/a/74601657

如果您不能或不想用

MutableState
切换
MutableStateFlow
,您需要用
Snapshot.withMutableSnapshot
包装对 MutableState 的所有写访问。

© www.soinside.com 2019 - 2024. All rights reserved.