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.

Enjoy!

Did you enjoy this content? We have got more on the way! Sign up here for regular updates!

Geef een reactie

Het e-mailadres wordt niet gepubliceerd. Vereiste velden zijn gemarkeerd met *