JMockit extensions for Kotlin

JMockit extensions for Kotlin
Post-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:

https://gist.github.com/soudmaijer/b15e29a0f2b2262cac62a8998abb6625

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:

https://gist.github.com/soudmaijer/d4f422e021e9b66660033fbf2b27810f

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:

https://gist.github.com/soudmaijer/4c2f1af25b2d29c240a6d4ed81c0f744

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

https://gist.github.com/soudmaijer/22ab661e5786eb2958d74b0894f7a4a2

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:

https://gist.github.com/soudmaijer/7b2e06340350cbed06ce13e4c9543e76

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

https://gist.github.com/soudmaijer/3aee328b64001dc94452b109c461d4f0

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

https://gist.github.com/soudmaijer/d4cb0780e072fe61cd523752c7707e3f

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!

Read more