0

I am new to the Micronaut framework and trying to test a demo example I created.

I am encountering the error io.mockk.MockKException: no answer found for: MathFacade(#3).computeAgain(3).

My code works as such - MathService invokes MathFacade. I want to test MathService so I mock MathFacade in my MathServiceTest with intentions to only test MathService.

My code is as below:

MathServiceTest

package io.micronaut.test.kotlintest

import io.kotlintest.specs.BehaviorSpec
import io.micronaut.test.annotation.MicronautTest
import io.micronaut.test.annotation.MockBean
import io.micronaut.test.extensions.kotlintest.MicronautKotlinTestExtension.getMock
import io.mockk.mockk
import io.mockk.every
import io.reactivex.Single
import kotlin.math.pow
import kotlin.math.roundToInt

@MicronautTest
class MathServiceTest(
        private val mathService: MathService,
        private val mathFacade: MathFacade
): BehaviorSpec({

    given("the math service") {

        `when`("the service is called with 3") {
            val mock = getMock(mathFacade)
            every { mock.computeAgain(any()) } answers {
                Single.just(firstArg<Int>().toDouble().pow(3).roundToInt())
            }
            val result = mathService.compute(2)
            then("the result is 9") {
                mathService.compute(3).test().assertResult(27)
            }
        }
    }
}) {

    @MockBean(MathFacade::class)
    fun mathFacade(): MathFacade {
        return mockk()
    }
}

MathService

package io.micronaut.test.kotlintest

import io.reactivex.Single
import javax.inject.Singleton

@Singleton
class MathService(private val mathFacade: MathFacade) {

    fun compute(num: Int): Single<Int> {
        return mathFacade.computeAgain(num)
    }
}

MathFacade

package io.micronaut.test.kotlintest

import io.reactivex.Single
import javax.inject.Singleton

@Singleton
class MathFacade() {
    fun computeAgain(num: Int): Single<Int>{
        return Single.just(num*4)
    }
}

Any help will be appreciated!

  • I don't know Micronaut, but typically with such mocking framework errors, you are likely not mocking the right object. If you put a breakpoint on `mathService.compute(2)`, does the facade point to the mock? – akarnokd Feb 06 '20 at 13:10
  • Based off what you have shown it looks like it should work. Try comparing your code to the tests in the `micronaut-test` repo – James Kleeh Feb 07 '20 at 17:45

0 Answers0