How to Use Mockito2 mock final class (KAD 23) and kotlinmockito2 on Kotlin
By Antonio Leiva
Time: Mar 2 and 2017
Link: https://antonioleiva.com/mockito-2-kotlin/
As mentioned in the previous article, one of the most common problems with Kotlin is that by default, all classes and functions are disabled.
That is to say, if you want a mock class (which may be very common in Java testing), you may need to use reserved words.open
Open it or extract an interface.
Both methods may be annoying. In fact, they restrict Java developers from using Kotlin.
Fortunately, Mockito 2 removes this restriction. Today I plan to teach you how to do it.
What is the problem?
Imagine that you have a class in Kotlin, which is like this:
1 class ClosedClass {2 3 fun doSomething() {4 }5 }
You need to test the doSomething method of the class.
The method is as follows:
1 @Test fun testClosedClass() {2 val c = Mockito.mock(ClosedClass::class.java)3 c.doSomething()4 verify(c).doSomething()5 }
If you use Mockito 1.x, you will get the following error:
Mockito cannot mock/spy following:
-Final classes
-Anonymous classes
-Primitive types
The update dependency is related to Mockito 2
As we said, Mockito 2 is fully capable of mock, so we need to update the dependency. In this article, the latest version of Mockito 2 is 2.8.9. However, because they are updated frequently recently, check the latest version.
1 testCompile 'org.mockito:mockito-core:2.8.9'
Now we run the code again, but it still fails!
Mockito cannot mock/spy because:
-Final class
Although mock anonymous classes or primitive types are not restricted at all, it is different from final classes. Why?
This option is still experimental and requires manual activation.
Enable mock final classes Selection
To enable it, you needtest/resources/mockito-extensions
Createorg.mockito.plugins.MockMaker
File:
It is a simple text file:
1 mock-maker-inline
There is no other content.
Now you can test it again and see that it is running normally. Great!
Mock attributes
You can also use the mock attribute, and there is no problem. For example, if we modify the code of this class:
1 class ClosedClass(val prop: Int) {2 3 fun doSomething() {4 }5 }
Let's take a look at the mock attribute values:
1 @Test fun testClosedClass() {2 val c = Mockito.mock(ClosedClass::class.java)3 `when`(c.prop).thenReturn(3)4 5 val prop = c.prop6 assertEquals(3, prop)7 }
I want it to return 3. Then, I check that the value is correct.
You can also check whether the property has been called:
1 verify(c).prop
Conclusion
As you can see, all restrictions are removed in the latest version of the most popular mock library.
So there is no excuse! Now you can use Kotlin to write all your tests.
Remember, you can find all this content and more details in this free guide, which will help you build your first project; or in this book, you can learn how to create a complete application from scratch.