Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to mock accessors by Mockito in Kotlin?

Tags:

Is it possible to mock getter and setter of the property by Mockito? Something like this:

@Test
fun three() {
    val m = mock<Ddd>() {
//        on { getQq() }.doReturn("mocked!")
    }
    assertEquals("mocked!", m.qq)
}
open class Ddd {
     var qq : String = "start"
        set(value) {
            field = value + " by setter"
        }
        get() {
            return field + " by getter"
        }
}
like image 499
tse Avatar asked Nov 14 '16 12:11

tse


People also ask

Does Mockito work with Kotlin?

Mockito has been around since the early days of Android development and eventually became the de-facto mocking library for writing unit tests. Mockito and Mockk are written in Java and Kotlin, respectively, and since Kotlin and Java are interoperable, they can exist within the same project.

What can be mocked in Mockito?

The Mockito. mock() method allows us to create a mock object of a class or an interface. We can then use the mock to stub return values for its methods and verify if they were called. We don't need to do anything else to this method before we can use it.

Can Mockito mock interfaces?

Mockito mocks not only interfaces but also abstract classes and concrete non-final classes. Out of the box, Mockito cannot mock final classes and final or static methods, but if you really need it, Mockito 2 provides the experimental MockMaker plugin.


2 Answers

To mock getter just write:

val m = mock<Ddd>()
`when`(m.qq).thenReturn("42")

also i suggest to use mockito-kotlin, to use useful extensions and functions like whenever:

val m = mock<Ddd>()
whenever(m.qq).thenReturn("42")
like image 160
Ruslan Avatar answered Sep 20 '22 14:09

Ruslan


Complementing IRus' answer, you could also use the following syntax:

val mockedObj = mock<SomeClass> {
  on { funA() } doReturn "valA"
  on { funB() } doReturn "valB"
}

or

val mockedObj = mock<SomeClass> {
  on(it.funA()).thenReturn("valA")
  on(it.funB()).thenReturn("valB")
}
like image 42
EyesClear Avatar answered Sep 17 '22 14:09

EyesClear