2

I am trying to write unit test cases for a Kotlin class A and trying to mock return client() call present in test() method to unit test test() method:

A.kt kotlin class:
class A (par 1, par 2) : B(par 1, par 2) {
   override fun test(item: String): Boolean {
      return client()
   }
}


B.kt kotlin class:
abstract class B(par 1, par 2) {
    private val client: WebClient by lazy {
        //does something
    }
    protected fun client(): WebClient = client
}

Is it possible to mock the client() call in test() method? And if possible how to do it and what library should I use for mocking?

DR93
  • 463
  • 6
  • 21

1 Answers1

0

This should be doable using Mockito testing framework. However, mocking an object returned from a object's method would require mocking the object itself.

val mockOfA = Mockito.mock(A::class)
val mockOfClient = Mockito.mock(WebClient:class)
Mockito.when(mockOfA.test(anyString())).thenReturn(mockOfClient)  // Mind your original snippet return type Boolean from A.test()

If your class A implements internal logic you want to test in your test scenario, there are two possible paths:

  • Create a Spy instead of a Mock. Mocks do only whatever you explicitly set them up to do. Spy 'falls back' to original implementation when it is not given any mock behaviour.
  • Rewrite you class A so that it depends on external dependency of a ClientProvider to get an instance of WebClient to return in method test() and inject a mock of said provider to your object of type A during the test.
ryfterek
  • 669
  • 6
  • 17
  • client().post().uri("some uri").syncBody(body).execute(uri, exception) - this is the complete so it returns a boolean – DR93 Feb 16 '20 at 17:10