0

I am trying to write a test class in Kotlin with org.jetbrains.kotlin:kotlin-test-junit:1.4.31 in my build.gradle.

In my test class, mocks are not getting initialized via the '@RunWith' annotation i.e. :

@RunWith(MockitoJUnitRunner::class)

e.g. I am using

@InjectMocks lateinit var bookService: BookServiceImpl

For above mocks to get initialized I have to use 'MockitoAnnotations.initMocks(this)' (otherwise I get exception) e.g.

@InjectMocks lateinit var bookService: BookServiceImpl

@Test
fun testStudentGenerationEvent(){
    MockitoAnnotations.initMocks(this)
    val student = MyTestUtil.getStudentDTO()
    bookService.prepareStudentGenerationEvent(customerData, "test-student-topic")
}

can anyone suggest why above behavior is happening? Why @RunWith(MockitoJUnitRunner::class) is not initializing the mock ( I get exception

    lateinit property bookService has not been initialized kotlin.UninitializedPropertyAccessException: lateinit property bookService has not been initialized

) and only MockitoAnnotations.initMocks(this) is able to initialize.

Akash Verma
  • 638
  • 1
  • 11
  • 15
  • Are you using JUnit 4 or JUnit 5? If you're using JUnit 5, you should use `@ExtendWith(MockitoExtension::class)`. – Mark Rotteveel Jan 30 '22 at 09:56
  • amazing! this works and the mock got initialised. But still I didn’t quite get the reasoning behind the above behaviour. To answer your question though I am using Junit4 ( as I already mentioned the dependency org.jetbrains.kotlin:kotlin-test-junit:1.4.31). So I dunno why this worked ?! – Akash Verma Jan 30 '22 at 10:03
  • If using `@ExtendWith(MockitoExtension::class)` works, then you're using JUnit 5, not JUnit 4. – Mark Rotteveel Jan 30 '22 at 10:05
  • Okay, how can we check the version. As per the dependency it says 1.4.31 (so I suppose it is junit4) please correct or add if wrong/missing anything. Thank you. – Akash Verma Jan 30 '22 at 10:08
  • 2
    That dependency of kotlin-test-junit does not necessarily mean you're using JUnit 4 or 5. It depends on what `@Test` annotation you imported. – Mark Rotteveel Jan 30 '22 at 10:10
  • Okay. But anyways what is the reason it gets intialized with @ExtendWith(MockitoExtension::class) and not with @RunWith(MockitoJUnitRunner::class). Any idea? – Akash Verma Jan 30 '22 at 14:50
  • 2
    Mark Rotteveel just told you. Your @Test annotation is either from org.junit.jupiter annotation or an org.junit. The former being junit 5 and the latter junit 4. – Daniel Jacob Jan 30 '22 at 16:28
  • 1
    Because `@RunWith` is JUnit 4, and `@ExtendWith` is its more powerful replacement in JUnit 5. – Mark Rotteveel Jan 30 '22 at 17:48

0 Answers0