What is the problem?
And you want to test that its
The way to do it would be the following:
If you use Mockito 1.x, you’ll get the following error:
So now we run our code again, but… it fails again!
This option is still a bit experimental, and requires a manual activation.

It’s a simple text file, in which you have to write:
Nothing else.
Now you can run the test again, and you’ll see that it runs smoothly. Great!
Now let’s mock the value of the property:
I’m asking it to return 3 when it’s called, and later, I check that the value is correct.
You can also check that a property has been called with:
So excuses are over! You can now write all your tests using Kotlin.
class ClosedClass {
fun doSomething() {
}
}
doSomething method is called.The way to do it would be the following:
@Test fun testClosedClass() {
val c = Mockito.mock(ClosedClass::class.java)
c.doSomething()
verify(c).doSomething()
}
Mockito cannot mock/spy following:
– final classes
– anonymous classes
– primitive types
Update dependencies to Mockito 2
As we have said, Mockito 2 is able to mock it all, so we’re going to update the dependency. At the time of writing this article the latest version is 2.8.9. But check it out because they are updating very often lately.
testCompile 'org.mockito:mockito-core:2.8.9'
Mockito cannot mock/spy because :We’re no longer limited to mock anonymous classes or primitive types, but it’s not the same for final classes. Why is this?
– final class
This option is still a bit experimental, and requires a manual activation.
Enable the option to mock final classes
To do this, you’ll need to create a file in thetest/resources/mockito-extensions folder called org.mockito.plugins.MockMaker:
It’s a simple text file, in which you have to write:
mock-maker-inline
Now you can run the test again, and you’ll see that it runs smoothly. Great!
Mocking Properties
You can also mock properties with no issues. If we change the code of the class to this, for example:
class ClosedClass(val prop: Int) {
fun doSomething() {
}
}
@Test fun testClosedClass() {
val c = Mockito.mock(ClosedClass::class.java)
`when`(c.prop).thenReturn(3)
val prop = c.prop
assertEquals(3, prop)
}
You can also check that a property has been called with:
verify(c).prop
Conclusion
As you can see, all the limitations have disappeared thanks to the latest version of the most popular mocking library.So excuses are over! You can now write all your tests using Kotlin.
Comments
Post a Comment