kotlinmockkkotest

Kotlin: Type mismatch: inferred type is Runs but Awaits was expected


I am currently writing tests using kotest and MockK in Kotlin. I encountered an error during the mocking process while writing tests in Kotlin using kotest and MockK.

every { accountService.findAccount(nonExistAccountId.toString()) } just Runs
//Kotlin: Type mismatch: inferred type is Runs but Awaits was expected

But previously, I didn't encounter any problems with the same process.

every { noticeRepository.delete(any()) } just  Runs
//no error

So, I checked the declaration of 'just'.

/**
 * Part of DSL. Answer placeholder for Unit returning functions.
 */
@Suppress("UNUSED_PARAMETER")
infix fun MockKStubScope<Unit, Unit>.just(runs: Runs) = answers(ConstantAnswer(Unit))

/**
 * Part of DSL. Answer placeholder for never returning suspend functions.
 */
@Suppress("UNUSED_PARAMETER")
infix fun <T, B> MockKStubScope<T, B>.just(awaits: Awaits) = coAnswers { awaitCancellation() }

Why isn't the function above being called?


Solution

  • So, you don't have an error in this case because the delete() method in noticeRepository returns Unit.

    every { noticeRepository.delete(any()) } just  Runs
    

    just Runs is only used to mock responses of functions or methods that return Unit

    When you want to mock response for method that actually DOES returns a values, you use different approach

    every { accountService.findAccount(nonExistAccountId.toString()) } returns // add your Account mock value here
    

    More details can be found here: https://mockk.io/#answers