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.

3 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 ๐Ÿ˜‰

  2. Lachlan Deck says:

    Iโ€™ve tried copying JMockitExtensions.kt into my project and using the expectations block doesnโ€™t appear to setup JMockit with the expectation.

    A very simple test fails.

    class ErrorMessage(val msg)

    def testFoo(@Mocked errorMessage: ErrorMessage) {
    expectations {
    result = โ€œfooโ€


    to be equal to:

    but was not.

    Reverting to object : `Expectations() { init { … } }` works.

    openjdk 11, JMockit 1.48.

Leave a Reply to Stephan Oudmaijer Cancel reply

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