JMockit extensions for Kotlin

Sometimes you have to deal with existing libraries… also libraries that do not provide out-of-the-box support for Kotlin (bastards!). What do you do in such a scenario? Write your own 😉

In one of my recent projects we were using a mocking framework called: JMockit. We already had a lot of tests which were written using JMockit and we preferred not to switch to a different mocking framework.

Consider the following existing (example) Java application:

When testing the AddressBook functionality, we could use a Mocking framework to Mock the repository interaction and behaviour. Meet JMockit! In JMockit you have define Mock behaviour using anonymous inner classes. This can be done using the JMockit class called Expectations. An example test using JMockit Expectations in Java:

We can rewrite the test in Kotlin using anonymous inner classes for the Expectations and Verification objects. The Kotlin equivalent of the above test would look like:

We now get confronted with some Kotlin boilerplate…. say what?!!!!

Hey wait!!! But Kotlin is concise right? Yes, but we need to add this ourselves 🙂 We can do this using extension functions in Kotlin, which allows us to write the boilerplate above like:

What does this look like when we apply the extensions defined above?

The complete version of the test using the extensions would look like:

By adding some custom extensions, you can very easily add your own (Kotlin) flavor to existing frameworks that, out of the box, do not provide support for your favourite programming language.


This article was originally posted @
This entry was posted in Blog, Kotlin and tagged . Bookmark the permalink.

2 Responses to JMockit extensions for Kotlin

  1. Jasper Sprengers says:

    I’ve used JMockit myself with Kotlin, but frankly I switched back to mockito, now that it supports mocking final classes and there’s the mockito-kotlin glue library to iron out the rough patches. Haven’t looked at MockK yet in detail, but it looks pretty cool.

    • I havent used MockK, looks nice indeed!

      Well I started with Mockito, switched to JMockit and back again 😉 Recently I was working on a few applications that consist of a hybrid code-base, Java and Kotlin. JMockit was already in use…. Combining both JMockit and Mockito in the same codebase does not always turn out to be a superb combination 😉

Leave a Reply

Your email address will not be published. Required fields are marked *