Search code examples
kotlinmockk

Kotlin coEvery mock actually calls function and then fails


I am using coEvery to mock a function in a test. The function itself takes in a token a makes an http call. In the test, I want it to return a hard coded data object, but for some reason the coEvery actually calls into my function and then fails the http GET call?

My function looks like this in Kotlin,

suspend fun fetchData(userToken: String?): DataResponse {
  return webClient.get()
    .uri("some_uri")
    .header("Authorization", userToken)
    .retrieve()
    .awaitBody<DataResponse>()
}

And the test has this,

coEvery {
  myService.fetchData("valid_token")
} returns DataResponse(user_id=1, user_name="test") 

The test goes on to call a function which goes into fetchData. However, when running the test, I see that the test never goes into the top level caller function in the test, but it does go into the mocked fetchData test like it's actually running that function?

At the top of my test file, the initialization for MyService is done like this,

MyService(
  @Autowired private val myService: MyService
)

I'm wondering if this could be an issue, that it's not done via lateinit too.


Solution

  • I was able to resolve this by moving the fetchData function to it's own class, like FetchDataService.

    Then when I needed to mock it out it worked because it was not mocking the main file I was testing.