Skip to content

Kotlin, JUnit , Mockito: @MockBean does not inject a mocked bean #1275

@yacinelakel

Description

@yacinelakel

Expected Behavior

Injected beans in a test class using @MicronautTest and @MockBean should inject a mock of the bean.

Actual Behaviour

The injected bean is not a mock, but instead the actual instance of the bean.

Steps To Reproduce

  1. Create a new Micronaut Application (v 4.9.3)
mn create-app --build=gradle_kotlin --jdk=21 --lang=kotlin --test=junit --features=http-client,mockito com.example.kotlin-junit
  1. Add a simple singleton class
@Singleton
open class EchoServiceImpl {
    open fun echo(message: String): String {
        return message
    }
}
  1. Update the KotlinJunitTest to create a mock using @MockBean, and inject it into the test class
@MicronautTest
open class KotlinJunitTest {

    @Inject
    lateinit var application: EmbeddedApplication<*>

    @Inject
    lateinit var echoService: EchoServiceImpl

    @Test
    fun testItWorks() {
        Assertions.assertTrue(application.isRunning)
    }

    @Test
    fun echoServiceIsMocked() {
        Assertions.assertTrue(Mockito.mockingDetails(echoService).isMock)
    }

    @MockBean(EchoServiceImpl::class)
    open fun echoService(): EchoServiceImpl {
        return Mockito.mock(EchoServiceImpl::class.java)
    }
}

Environment Information

No response

Example Application

https://github.com/yacinelakel/micronaut-kotlin-junit-mockbean-issue

Version

4.9.3

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions