你好吗 我使用扩展 fun 将流程转换为 StateIn 我应用了官方文档中的这些步骤 https://developer.android.com/kotlin/flow/test#statein
这是我的代码
@HiltViewModel
class HomeViewModel @Inject constructor(
private val chatRepository: ChatRepository,
private val messageRepository: MessageRepository,
private val dispatchers :DispatcherProvider
) : ViewModel() {
val homeState = chatRepository.getChats().map {
HomeChatState(it)
}.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5000), HomeChatState())
fun addTestChat(chat: Chat) {
viewModelScope.launch(dispatchers.io) {
chatRepository.insertChat(
chat
)
}
}
和这个假回购
class FakeChatRepo:ChatRepository {
private val chats = MutableStateFlow<List<Chat>>(emptyList())
override fun getChats(): Flow<List<Chat>> {
return chats.asStateFlow()
}
override suspend fun insertChat(chat: Chat) {
chats.emit(chats.value + chat)
}
override suspend fun deleteChatById(chat: Chat) {
chats.value -= chat
}
override suspend fun readMessages(chatId: Int) {
TODO("Not yet implemented")
}
}
和这个测试代码
class ExampleUnitTest {
private lateinit var homeViewModel: HomeViewModel
@Before
fun setup() {
val messageRepo = MessageFakeRepository()
val chatRepo = FakeChatRepo()
val testDispatcher = TestDispatcherProvider()
homeViewModel = HomeViewModel(chatRepo, messageRepo, testDispatcher)
}
@OptIn(ExperimentalCoroutinesApi::class)
@Test
fun addChat_returnTrue() = runTest {
val chat =
Chat(
1,
"sender test",
"test",
"salman",
"Hi",
"",
LocalDateTime.now(),
1,
"hi"
)
val s = homeViewModel.homeState
backgroundScope.launch(UnconfinedTestDispatcher(testScheduler)) {
s.collect()
}
Truth.assertThat(s.value.chats).isEmpty()
homeViewModel.addTestChat(chat) // here is issue not update data and always retrun empty valye
Truth.assertThat(s.value.chats).containsExactly(chat)
}
}
问题是当从 addTestChat() 添加数据时,它不起作用,除了 谢谢