Mockito Kotlin lateinit error


What's inside this article ⌄
  • Mockito Kotlin lateinit error
  • Kotlin property not initialized Mockito
  • Fix Mockito Kotlin lateinit
  • Mockito Kotlin property initialization

Let’s look at this code:

 1class DemoTest {
 2
 3    @Mock
 4    private lateinit var myClass: MyClass
 5
 6    @BeforeEach
 7    fun init() {
 8        MockitoAnnotations.initMocks(this)
 9    }
10
11    @Test
12    fun test1() {
13        LogManager.getLogger().info("1: $myClass")
14        test2()
15    }
16
17    companion object {
18        private val myClass = MyClass(1, 2)
19
20        fun test2() {
21            LogManager.getLogger().info("2: $myClass")
22        }
23    }
24}

You see, that we have mock of myClass, that prepared by Mockito. In the same time we have object of MyClass inside companion object, that we prepared ourselves.

If you run this test with Kotlin 1.6.0 (and around) for instance, you’ll get this error:

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

But, with Kotlin 1.4.32 and around, this stuff works fine. We see smth like this as output:

1: myClass$1
2: MyClass(a=1, b=2)

So the solution just is to change link name in companion object to avoid name overlapping:

1// ...
2companion object {
3    private val myClassCustom = MyClass(1, 2)
4    // ...
5}