Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to use Mockito with Kotlin without open the class?

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?

like image 644
Elye Avatar asked Apr 10 '16 23:04

Elye


People also ask

Can we use Mockito 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.

Is Mockito open source?

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).

Can Mockito mock a class?

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.

Is Mockk better than Mockito?

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.


2 Answers

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
like image 73
Cristan Avatar answered Oct 19 '22 10:10

Cristan


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

like image 38
Lovis Avatar answered Oct 19 '22 09:10

Lovis