# How to use Mockito with Kotlin?

**URL:** <https://discuss.kotlinlang.org/t/how-to-use-mockito-with-kotlin/324>\
**Category:** Uncategorized\
**Created:** [April 9, 2013, 12:19pm UTC](https://discuss.kotlinlang.org/t/how-to-use-mockito-with-kotlin/324 "2013-04-09T12:19:46Z")\
**Posts on this page:** 19\
**Page:** 1

<div class="post-metadata">

**Author:** ![nanosk](https://avatars.discourse-cdn.com/v4/letter/n/a4c791/32.png) [@nanosk](https://discuss.kotlinlang.org/u/nanosk)\
**Post date:** [April 9, 2013, 12:19pm UTC](https://discuss.kotlinlang.org/t/how-to-use-mockito-with-kotlin/324/1 "2013-04-09T12:19:46Z")

</div>

I stumbled upon a number of papercuts when trying to use Mockito together with Kotlin which I wanted to discuss with the community.

**a) Mockito.any(…) and other matchers often return null**  
To me, this seems to effectively block using Mockito with Kotlin.

See the following example:

```kotlin
import org.junit.Test as test
import java.math.BigDecimal
import org.mockito.Mockito.doNothing
import org.mockito.Mockito
import org.mockito.Matchers
open class DependencyOfCUT {
  fun d(aParam: BigDecimal) {
  //do something
  }
}
class CUT {
  fun testedMethod(d: DependencyOfCUT) {
  d.d(BigDecimal.ZERO)
  }
}
class TheTest {
  test fun aTest() {
  val d = Mockito.mock(javaClass<DependencyOfCUT>())!!
  //added !! for illustration purpose only:
   // >>>> Matchers.any will almost always return <null> which causes NPEs at runtime <<<<
  // Other mockito matchers will also effectively return ‘null’
  Mockito.doNothing().when(d).d(Matchers.any(javaClass<BigDecimal>())!!)
  &nbsp;&nbsp;CUT().testedMethod(d)

  }
}
```

**\>\>\>\> Matchers.any will almost always return \<null\> which causes NPEs at runtime \<\<\<\<**

**b) escaping syntax for when/is required all the time**

```kotlin
when(object.method(anyString()).thenReturn(“something”)
```

The same applies to heavy users of hamcrest (independent of mockito)

```kotlin
assertThat(a.getB(), is(expected))
```

This is inconvinient and hinders readability. Maybe we can come up with a more readable alternative? Typing the ` sign interrupts the flow since it is intended to be put on top of the next letter. If I type "`" + “i” I’ll end up with ì (accent-I).

**c) The need for open classes/methods**  
Mocking frameworks such as Mockito very often rely on non-final classes/methods. If a class is used by some other class and the other class is unit-tested, it seems we have to declare it open. The same applies to its methods. At the end, almost all classed need to be open. Does it make sense to default to final (non-open) for tests?

Kotlin strives for a good Java Interoperability which is necessary to be accepted. I would appreciate if we could use existing libraries (i.e. Mockito) painlessly. Otherwise we end up reimplementing proven Java libraries - Mockito is just an example - in Kotlin.  
I would agree that some reimplementation is desireable to take advantage of advanced APIs which are not possible in Java. I would appreciate it if we could just re-use existing libs.

What do you think?

---

<div class="post-metadata">

**Author:** ![abreslav](https://sea1.discourse-cdn.com/flex019/user_avatar/discuss.kotlinlang.org/abreslav/32/8279_2.png) [@abreslav](https://discuss.kotlinlang.org/u/abreslav)\
**Post date:** [April 9, 2013, 12:39pm UTC](https://discuss.kotlinlang.org/t/how-to-use-mockito-with-kotlin/324/2 "2013-04-09T12:39:09Z")

</div>

a) If you are OK with the risk of having an exception at runtime, annotate Mockito methods as @NotNull b) Use rename on import to work around the naimng problem

---

<div class="post-metadata">

**Author:** ![nanosk](https://avatars.discourse-cdn.com/v4/letter/n/a4c791/32.png) [@nanosk](https://discuss.kotlinlang.org/u/nanosk)\
**Post date:** [April 9, 2013, 1:08pm UTC](https://discuss.kotlinlang.org/t/how-to-use-mockito-with-kotlin/324/3 "2013-04-09T13:08:14Z")

</div>

a) @NotNull does not help since it really returns in most cases. It does not return null for primitives and their wrappers.

The code above compiles but it throws

``

```kotlin
jet.runtime.Intrinsics$JetNullPointerException
     at reproducer.ktxxxx_mockito_npe.TheTest.aTest(NpeProducer.kt:27)
     …
```

To use Mockito and Kotlin almost all stubbed methods need to allow null. Are there other mocking frameworks which are more Kotlin-compatible?

b) I’m fine with that

any comment on c)? I read somewhere that you are thinking about a test-mode in which all classes are open but I could not find it anymore.

---

<div class="post-metadata">

**Author:** ![abreslav](https://sea1.discourse-cdn.com/flex019/user_avatar/discuss.kotlinlang.org/abreslav/32/8279_2.png) [@abreslav](https://discuss.kotlinlang.org/u/abreslav)\
**Post date:** [April 9, 2013, 2:14pm UTC](https://discuss.kotlinlang.org/t/how-to-use-mockito-with-kotlin/324/4 "2013-04-09T14:14:23Z")

</div>

с) use traits, mocking classes sounds odd anyway

---

<div class="post-metadata">

**Author:** ![nanosk](https://avatars.discourse-cdn.com/v4/letter/n/a4c791/32.png) [@nanosk](https://discuss.kotlinlang.org/u/nanosk)\
**Post date:** [April 9, 2013, 2:37pm UTC](https://discuss.kotlinlang.org/t/how-to-use-mockito-with-kotlin/324/5 "2013-04-09T14:37:22Z")

</div>

> с) use traits, mocking classes sounds odd anyway

I'd say that introducing an interface or using a trait just for testing/mocking sounds odd. Why introduce an artificial artifact which needs to be subclassed when I can do without? What would you to with (Kotlin-) libraries which you cannot alter?

From a design point-of-view traits are something different than classes since (correct me if I’m wrong) you cannot just instantiiate traits.

---

<div class="post-metadata">

**Author:** ![abreslav](https://sea1.discourse-cdn.com/flex019/user_avatar/discuss.kotlinlang.org/abreslav/32/8279_2.png) [@abreslav](https://discuss.kotlinlang.org/u/abreslav)\
**Post date:** [April 9, 2013, 3:12pm UTC](https://discuss.kotlinlang.org/t/how-to-use-mockito-with-kotlin/324/6 "2013-04-09T15:12:37Z")

</div>

At least there are different opinions on this matter. Some people think that you should have an interface for every public abstraction.

---

<div class="post-metadata">

**Author:** ![nanosk](https://avatars.discourse-cdn.com/v4/letter/n/a4c791/32.png) [@nanosk](https://discuss.kotlinlang.org/u/nanosk)\
**Post date:** [September 2, 2014, 8:14am UTC](https://discuss.kotlinlang.org/t/how-to-use-mockito-with-kotlin/324/7 "2014-09-02T08:14:54Z")

</div>

Correct, these different opinions are part of thousands of existing libraries **which we cannot change**. Or is there a way to make a class dynamically extend/implement a trait similar to extension functions?

---

<div class="post-metadata">

**Author:** ![maaartinus](https://avatars.discourse-cdn.com/v4/letter/m/7ea924/32.png) [@maaartinus](https://discuss.kotlinlang.org/u/maaartinus)\
**Post date:** [September 4, 2014, 1:10am UTC](https://discuss.kotlinlang.org/t/how-to-use-mockito-with-kotlin/324/8 "2014-09-04T01:10:07Z")

</div>

> Correct, these different opinions are part of thousands of existing libraries **which we cannot change**. Or is there a way to make a class dynamically extend/implement a trait similar to extension functions?

Wouldn't JMockit help? They claim to be able to mock about everything, including final classes and final methods.

---

<div class="post-metadata">

**Author:** ![nanosk](https://avatars.discourse-cdn.com/v4/letter/n/a4c791/32.png) [@nanosk](https://discuss.kotlinlang.org/u/nanosk)\
**Post date:** [September 4, 2014, 8:28am UTC](https://discuss.kotlinlang.org/t/how-to-use-mockito-with-kotlin/324/9 "2014-09-04T08:28:09Z")

</div>

There's also Powermock/Powermockito which also claims that they can do that.

But Andrey’s suggestion to introduce a trait is different (if I got it right). Just assume that DependencyOfCUT is part of an external library. Since DependencyOfCUT does not implement an Interface/Trait with method d as expected by CUT we would need to introduce the interface/trait and a way to make DependencyOfCUT implement it. I guess it is possible to do that using byte-code modification. However CUT.testedMethod would have to take this Interface as an parameter instead of DependencyOfCUT, so we need that in production code.

Since I would prefer not to use byte-code enhancements in my production code, this is not an acceptable way.

Solution 2 would be to wrap the external DependencyOfCUT behind an Interface/Trait which is implemented by a project-specific class which is in turn delegating to the real DependencyOfCUT.

Essentially this means wrapping every external dependency which does not follow the “Interface for everything” paradigm. In my opinion this is impractical for a non-trivial project.

---

<div class="post-metadata">

**Author:** ![ikant](https://sea1.discourse-cdn.com/flex019/user_avatar/discuss.kotlinlang.org/ikant/32/1524_2.png) [@ikant](https://discuss.kotlinlang.org/u/ikant)\
**Post date:** [September 12, 2014, 4:41pm UTC](https://discuss.kotlinlang.org/t/how-to-use-mockito-with-kotlin/324/10 "2014-09-12T16:41:39Z")

</div>

Unlce bob talks quite a lot about this sort of thing:

[http://blog.8thlight.com/eric-smith/2011/10/27/thats-not-yours.html](http://blog.8thlight.com/eric-smith/2011/10/27/thats-not-yours.html)

The strategy I have used is to create an interface (or trait), then create an implementing class that wraps your dependency.&nbsp;&nbsp;No need for byte-code mods.

---

<div class="post-metadata">

**Author:** ![nanosk](https://avatars.discourse-cdn.com/v4/letter/n/a4c791/32.png) [@nanosk](https://discuss.kotlinlang.org/u/nanosk)\
**Post date:** [September 12, 2014, 5:28pm UTC](https://discuss.kotlinlang.org/t/how-to-use-mockito-with-kotlin/324/11 "2014-09-12T17:28:51Z")

</div>

Sorry, I do not get the difference between your strategy and my "Solution 2". I would say this is a lot of effort compared to mocking a class.

---

<div class="post-metadata">

**Author:** ![nanosk](https://avatars.discourse-cdn.com/v4/letter/n/a4c791/32.png) [@nanosk](https://discuss.kotlinlang.org/u/nanosk)\
**Post date:** [September 12, 2014, 5:34pm UTC](https://discuss.kotlinlang.org/t/how-to-use-mockito-with-kotlin/324/12 "2014-09-12T17:34:32Z")

</div>

could someone please help with my point (a)?

Using Mockito with matchers is impossible since they return null regardeless of the kotlin signature allowing or disallowing null. This either results in a NPE or a compiler error (as explained in earlier posts).

Is there someone who has sucessfully used other mock libraries with Kotlin?

Thanks

---

<div class="post-metadata">

**Author:** ![ikant](https://sea1.discourse-cdn.com/flex019/user_avatar/discuss.kotlinlang.org/ikant/32/1524_2.png) [@ikant](https://discuss.kotlinlang.org/u/ikant)\
**Post date:** [September 12, 2014, 5:35pm UTC](https://discuss.kotlinlang.org/t/how-to-use-mockito-with-kotlin/324/13 "2014-09-12T17:35:00Z")

</div>

Sorry I wasn't suggesting it was different, but the benefit you gain is decoupling from the implementation and potentially a better design.&nbsp;&nbsp;If this decoupling doesn't serve you well then possibly an integration test or some sort of double not created by Mockito.

---

<div class="post-metadata">

**Author:** ![nanosk](https://avatars.discourse-cdn.com/v4/letter/n/a4c791/32.png) [@nanosk](https://discuss.kotlinlang.org/u/nanosk)\
**Post date:** [September 12, 2014, 6:56pm UTC](https://discuss.kotlinlang.org/t/how-to-use-mockito-with-kotlin/324/14 "2014-09-12T18:56:24Z")

</div>

ok, thanks

---

<div class="post-metadata">

**Author:** ![Unitcraft](https://avatars.discourse-cdn.com/v4/letter/u/2acd7d/32.png) [@Unitcraft](https://discuss.kotlinlang.org/u/Unitcraft)\
**Post date:** [September 13, 2014, 12:44am UTC](https://discuss.kotlinlang.org/t/how-to-use-mockito-with-kotlin/324/15 "2014-09-13T00:44:31Z")

</div>

There is same problem with JMockit. Kotlin needs own mock lib with all power of JMockit.

---

<div class="post-metadata">

**Author:** ![cy6erGn0m](https://sea1.discourse-cdn.com/flex019/user_avatar/discuss.kotlinlang.org/cy6ergn0m/32/1439_2.png) [@cy6erGn0m](https://discuss.kotlinlang.org/u/cy6erGn0m)\
**Post date:** [February 26, 2015, 5:51pm UTC](https://discuss.kotlinlang.org/t/how-to-use-mockito-with-kotlin/324/16 "2015-02-26T17:51:17Z")

</div>

There is workaround for this issue with (a).

So if you need to call method “d” you can make helper function that looks like:

```kotlin
fun uninitialized<T>() : T = null as T
```

after that you can use it in when

```kotlin
Mockito.doNothing().when(d).d(uninitialized()))
```

---

<div class="post-metadata">

**Author:** ![rliesenfeld](https://avatars.discourse-cdn.com/v4/letter/r/9fc29f/32.png) [@rliesenfeld](https://discuss.kotlinlang.org/u/rliesenfeld)\
**Post date:** [April 11, 2016, 3:44pm UTC](https://discuss.kotlinlang.org/t/how-to-use-mockito-with-kotlin/324/17 "2016-04-11T15:44:55Z")

</div>

My personal take on this topic, as someone who has a lot experience with mocking libraries (I created JMockit):

1. Kotlin should have its own testing libraries, including a JUnit/TestNG equivalent, a mocking library, and a coverage tool. Trying to use tools that were created and only meant for the Java language (even if possible) is not going to cut it. JMockit, for instance, makes several assumptions (use of instance initialization blocks, use of JUnit or TestNG, etc.) that won’t translate well to Kotlin, if at all. The same for libraries like Mockito having method names like `when` which are reserved keywords in Kotlin.

2. In general, mocking is not a practice that is conducive to good automated tests. It should be used sparingly. Integration tests with no mocking tend to be much better. I say that as someone who has written thousands of JUnit/TestNG tests since 2004, with and without mocking. So, your best choice (whatever the programming language) is to _not_ mock.

---

<div class="post-metadata">

**Author:** ![nobunaga](https://avatars.discourse-cdn.com/v4/letter/n/b5a626/32.png) [@nobunaga](https://discuss.kotlinlang.org/u/nobunaga)\
**Post date:** [March 25, 2018, 10:46am UTC](https://discuss.kotlinlang.org/t/how-to-use-mockito-with-kotlin/324/18 "2018-03-25T10:46:01Z")

</div>

While i appreciate your efforts with JMockit, I too have been writing tests for years and saying that you should not mock or use integration tests is an anti pattern or rather will make your tests less maintainable in the long run. ‘Unit’ tests should be testing a unit. Not a number of units. Mocking helps achieve this as you control the behaviour of dependent classes. The testing pyramid also talks about where you should focus your tests.

Integration tests are useful and should be in your test suite, but primarily to keep your tests maintainable and quick, unit tests are a much better option than having a large set of integration tests.

---

<div class="post-metadata">

**Author:** ![Wasabi375](https://sea1.discourse-cdn.com/flex019/user_avatar/discuss.kotlinlang.org/wasabi375/32/4741_2.png) [@Wasabi375](https://discuss.kotlinlang.org/u/Wasabi375)\
**Post date:** [March 25, 2018, 11:02am UTC](https://discuss.kotlinlang.org/t/how-to-use-mockito-with-kotlin/324/19 "2018-03-25T11:02:22Z")

</div>

Well this tends to be a question of philosophy and there are good reasons for both sides. Yes integration tests are harder to maintain, but are also the sort of test catching the more severe bugs (well depending on your type of project). I’ve been working both on games and “normal” business applications and I agree with you that for the business application I was working on unit tests were the better choice most of the time.  
In games on the other hand, there are a lot of things where unit tests simply make no sense. Behavior is not defined on a unit level but in the interaction between different units, so integration tests become much more important while unit tests become mostly (IMO) a waste of time.
