Quick config Mockito with Kotlin (and RxJava2)

Fernando Raviola
2 min readAug 14, 2017

I’m writing this article to have a handy reference on how to fix issues that arise when trying to use Mockito and Kotlin together. There are many articles that provide an in-depth explanation on what causes these problems and how to solve them linked below, so please check them out if you are feeling curious.

Final methods and classes

By default, Kotlin classes and methods are final. Mockito doesn’t support mocking final classes and methods out of the box.

Solution:

Create a file named org.mockito.plugins.MockMaker and place it under test/resources/mockito-extensions with the following line inside

mock-maker-inline

If you are feeling particularly lazy, you can download the file here. Hadi Hariri explains more about this on this blog post.

Null Safety

In Mockito, both anyObject() and any() will return Nullable types, so if the method you are trying to mock doesn’t accept nullable parameters Kotlin will complain, and rightfully so!

Solution:

Learn more about this solution on this great article by Elye.

RxJava Schedulers

Lastly, if you are using RxJava and testing your code on the JVM you will have to override the behaviour of AndroidSchedulers.mainThread() to avoid the following issue:

The easiest fix for this is as follows:

RxAndroidPlugins.setInitMainThreadSchedulerHandler {Schedulers.trampoline()}

Peter Tackage Explains this issue and alternative solutions on this excellent blog post. To be honest I didn’t get this error when using Kotlin, I scratched my head for a good while until I realised what was happening, I got this ugly stack trace instead:

Conclusion

These are the solutions that I found more convenient for my proposes, if you know a better way of solving any these problems, or if you encountered any additional problem and would like to contribute to this article, please let me know in the comments, it will be greatly appreciated!

--

--