Home > OS >  Mock class used in a method Kotlin
Mock class used in a method Kotlin

Time:04-10

I am using mockk Kotlin library. I have a service Service that has a private method calling a 3d party client

class Service {
  fun foo() {
    bar()
  }
  
  private fun bar() {
    client = Client()
    client.doStuff()
  }
}

Now in my test I need to mock Client, e.g.

@Test
fun `my func does what I expect` {

}

I need to also mock what doStuff returns. How do I achieve this in Kotlin mockk?

CodePudding user response:

Firstly, you should never instantiate a dependency like Client inside your service class since you cannot access it to provide a Mock. Let's deal with that first...

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

and then this how to use 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()
    }
}
  • Related