Search code examples
unit-testingjunitmicronautmockk

How to use @MockBean without having to @Inject the Bean again?


Is there a more concise / elegant way to reach this functionality in Micronaut?

@MicronautTest
class ControllerTest {
    @Inject
    @field:Client("/")
    lateinit var client: RxHttpClient

    @Inject
    lateinit var redeemService: RedeemService

    @MockBean(RedeemService::class)
    fun redeemService(): RedeemService = mockk {
        every { validate(any()) } returns true
    }

    @Test
    fun test() {
        // some logic triggering a call to redeemService
        verify(exactly = 1) {
            redeemService.validate("123")
        }
    }
}

To me it looks like redundant work to have to declare the @MockBean and then also having to @Inject the previously declared @MockBean. From what I remember, in Spring Boot this is just an annotation on a lateinit var.

Did I misunderstand or overlook something?


Solution

  • You need the mock bean, for replacing the service and inject it everywhere in your application .. if you want to do some verification you either have to inject it back or create instance within your class and return that with the mock bean

    private val redeemService: RedeemService = mockk {
        every { validate(any()) } returns true
    }
    
    @MockBean(RedeemService::class)
    fun redeemService() = redeemService