我在视图模型测试中遇到模拟问题。我每次编译都有错误:
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
我无法制作模拟来测试 viewmodel 的行为。
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)
}
}
我试图在我的视图模型测试中模拟类,但每次我收到如上所示的错误。
如果您创建了假冒产品,则无需模拟您的产品。您必须将
every
与函数调用一起使用。例如:
every { productProducer.getNewProduct() } returns product1
只需为您的 mockProducts 和 mockGroupProducts 删除四个 every 并且您的代码应该可以工作。