视图模型中的模拟对象

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

我是 kotlin 新手,我正在尝试为视图模型方法编写单元测试,该方法使用

获取用户信息
val result = UserSvc().getUser()

我如何模拟 getUser() 方法

kotlin unit-testing mockito android-jetpack
2个回答
0
投票

要模拟 getUser() 方法,您可以使用 Mockito 等模拟框架。方法如下:

  1. 将 Mockito 依赖项添加到您的 build.gradle.kts 或 build.gradle 文件中:
dependencies {
    testImplementation("org.mockito:mockito-core:3.11.2")
}
  1. 编写单元测试,模拟 UserSvc 类及其 getUser() 方法:
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.Mock
import org.mockito.Mockito.`when`
import org.mockito.junit.MockitoJUnitRunner

@RunWith(MockitoJUnitRunner::class)
class YourViewModelTest {

    @Mock
    lateinit var userSvc: UserSvc

    @Test
    fun testYourViewModelMethod() {
        // Mock the behavior of getUser() method
        `when`(userSvc.getUser()).thenReturn(/* your mocked user object or data */)

        // Create an instance of your view model, passing the mocked userSvc
        val viewModel = YourViewModel(userSvc)

        // Call the method you want to test in your view model
        viewModel.yourMethodToTest()

        // Assert the behavior or state of your view model after calling the method
    }
}

0
投票

这并不总是模拟事物的最佳解决方案,例如模拟优点 当您需要测试遗留代码时或者例如没有可用的抽象时 (真正的实现直接在类中使用)所以在这里我认为你可以创建一个假的 UserSvc() ,其中所有用户都将在一个列表中,而 getUser 将只过滤该列表并返回对应的用户。

尽管如果您需要的话,这里有一个很好的 kotlin 模拟库: https://github.com/mockk/mockk

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