我在视图模型的测试中遇到了一个模拟问题。我在每次编译中都有错误:
Missing mocked calls inside every { ... } block: make sure the object inside the block is a mock
io.mockk.MockKException: Missing mocked calls inside every { ... } block: make sure the object inside the block is a mock
我无法制作模拟来测试视图模型的行为。
class MyPantryViewModelTest {
@Test
fun `given viewmodel initialized when ui state observed then ui state is Empty`() {
val mockProduct1 by lazy { mockk<Product>() }
val mockProduct2 = mockk<Product>()
val mockGroupProduct1 = mockk<GroupProduct>()
val mockGroupProduct2 = mockk<GroupProduct>()
val product1 = Product(id = 1, name = "Test 1")
val product2 = Product(id = 2, name = "Test 2")
val expectedProductList = listOf(product1, product2)
val groupProduct1 = GroupProduct(product = mockProduct1, quantity = 5)
val groupProduct2 = GroupProduct(product = mockProduct2, quantity = 3)
val groupsProduct = listOf(groupProduct1, groupProduct2)
every { mockProduct1 } returns product1
every { mockProduct2 } returns product2
every { mockGroupProduct1 } returns groupProduct1
every { mockGroupProduct2 } returns groupProduct1
val mockGetGroupProductListUseCase = mockk<GetGroupProductListUseCase>()
every { mockGetGroupProductListUseCase.invoke(any()) } returns groupsProduct
val mockGetGroupProductUseCase = mockk<GetGroupProductUseCase>()
every { mockGetGroupProductUseCase.invoke(any(), any()) } returns groupProduct1
val mockObserveAllProductsUseCase = mockk<ObserveAllProductsUseCase>()
every { mockObserveAllProductsUseCase.invoke() } returns flowOf(expectedProductList)
// given
val viewModel =
MyPantryViewModel(mockGetGroupProductListUseCase, mockObserveAllProductsUseCase)
// when
val uiState = viewModel.uiState.value
// then
assertTrue(uiState is MyPantryUiState.Empty)
}
}
我尝试在我的视图模型测试中模拟类,但每次我都收到如上所述的错误。
1条答案
按热度按时间zphenhs41#
如果你有假冒的产品,你不需要模仿你的产品。你必须使用
every
和一个函数调用。例如:只需删除mockProducts和mockGroupProducts的四个every,您的代码就可以工作了。