Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it not possible to set expectations on a lazy property?

Tags:

mockito

kotlin

The following test yields a NullPointerException. Is it not possible to set expectations on a lazy property?

class GarbTest {
    @Test
    fun xx(){
        val aa = Mockito.mock(AA::class.java)
        Mockito.`when`(aa.bb).thenReturn("zz")
    }

    open class AA(){
        val bb by lazy { "cc" }
    }
}
like image 573
Johnny Avatar asked Sep 01 '16 16:09

Johnny


1 Answers

In your example, AA.bb is final. final/private/equals()/hashCode() methods cannot be stubbed/verified by Mockito. You need to mark bb as open:

open class AA(){
    open val bb by lazy { "cc" }
}

You might also consider using nhaarman/mockito-kotlin: Using Mockito with Kotlin. e.g.:

class GarbTest {
    @Test
    fun xx() {
        val aa = mock<AA>() {
            on { bb } doReturn "zz"
        }
    }

    open class AA() {
        val bb: String = "cc"
    }
}
like image 116
mfulton26 Avatar answered Oct 12 '22 08:10

mfulton26