我在用莫克克·科特林图书馆。我有一个服务服务,它有一个调用3d派对客户端的私有方法
class Service {
fun foo() {
bar()
}
private fun bar() {
client = Client()
client.doStuff()
}
}现在在我的测试中,我需要模拟客户端。
@Test
fun `my func does what I expect` {
}我还需要模拟doStuff返回的内容。我怎样才能在Kotlin mockk上实现这一点?
发布于 2022-04-09 17:56:54
首先,您不应该在服务类中实例化像Client 这样的依赖项,因为您不能访问它来提供模拟。我们先处理一下..。
class Client { // this is the real client
fun doStuff(): Int {
// access external system/file/etc
return 777
}
}
class Service(private val client: Client) {
fun foo() {
bar()
}
private fun bar() {
println(client.doStuff())
}
}然后这个如何使用Mockk
class ServiceTest {
private val client: Client = mockk()
@Test
fun `my func does what I expect`() {
every { client.doStuff() } returns 666
val service = Service(client)
service.foo()
}
}https://stackoverflow.com/questions/71809686
复制相似问题