我是 kotlin 新手,我正在尝试为视图模型方法编写单元测试,该方法使用
获取用户信息val result = UserSvc().getUser()
我如何模拟 getUser() 方法
要模拟 getUser() 方法,您可以使用 Mockito 等模拟框架。方法如下:
dependencies { testImplementation("org.mockito:mockito-core:3.11.2") }
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 } }
这并不总是模拟事物的最佳解决方案,例如模拟优点 当您需要测试遗留代码时或者例如没有可用的抽象时 (真正的实现直接在类中使用)所以在这里我认为你可以创建一个假的 UserSvc() ,其中所有用户都将在一个列表中,而 getUser 将只过滤该列表并返回对应的用户。
尽管如果您需要的话,这里有一个很好的 kotlin 模拟库: https://github.com/mockk/mockk