As we probably know, by default Kotlin class once defined, it is final, unless it is explicitly declared open
.
This would post a challenge when we want to Mock it using Mockito. We need to explicitly declare it as open
. Is there a way we could avoid declaring it as open
while able to Mock it for our testing?
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.
Mockito is an open source testing framework for Java released under the MIT License. The framework allows the creation of test double objects (mock objects) in automated unit tests for the purpose of test-driven development (TDD) or behavior-driven development (BDD).
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.
In Android, there are a lot of frameworks used for mocking in unit testing, such as PowerMock, Mockito, EasyMock, etc. MockK is definitely a better alternative to other mocking frameworks for Kotlin, the official development language for Android. Its main philosophy is first-class support for Kotlin features.
The MockMaker plugin doesn't seem to work when running espresso tests. Therefore, you can use Kotlin's all-open pugin instead.
Add the plugin in build.gradle:
buildscript {
dependencies {
classpath "org.jetbrains.kotlin:kotlin-allopen:$kotlin_version"
}
}
apply plugin: "kotlin-allopen"
Specify the annotation that will make the class open:
allOpen {
annotation("com.my.MyMockable")
}
Create your annotation which can be used to annotate classes:
@Target(AnnotationTarget.CLASS)
annotation class MyMockable
Then, in order to make your class and its public methods Mockable (open), annotate it with your annotation:
@MyMockable
Mockito2 can now mock final classes as well.
However, this feature is opt-in, so you need to enable it manually.
To do so, you need to define a file /mockito-extensions/org.mockito.plugins.MockMaker
containing the line mock-maker-inline
See e.g.
http://hadihariri.com/2016/10/04/Mocking-Kotlin-With-Mockito/ or
https://github.com/mockito/mockito/wiki/What%27s-new-in-Mockito-2#unmockable
for a quick introduction
on a side note, this currently doesn't work for android
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With