android 无法在ViewModel的测试中模拟,(Kotlin,Compose)

tpxzln5u  于 2023-03-27  发布在  Android
关注(0)|答案(1)|浏览(208)

我在视图模型的测试中遇到了一个模拟问题。我在每次编译中都有错误:

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)
    }
}

我尝试在我的视图模型测试中模拟类,但每次我都收到如上所述的错误。

zphenhs4

zphenhs41#

如果你有假冒的产品,你不需要模仿你的产品。你必须使用every和一个函数调用。例如:

every { productProducer.getNewProduct() } returns product1

只需删除mockProducts和mockGroupProducts的四个every,您的代码就可以工作了。

相关问题