Kotlin + Gradle + Spek 2 + JUnit 5 — a simple guide
Disclaimer: the original blog post has been published at 98elements blog.
I wanted to try out Kotlin + Spek 2 testing framework combination. It turns out both Gradle and Spek 2 documentation leave much to be desired… So here it is a step-by-step guide to build a simple application.
A calculator that allows to add and divide numbers is enough demonstrate all required Gradle configuration options and introduce Spek 2 specs syntax. Let’s start with the desired test structure. Framework is inspired heavily by RSpec so Ruby developers will feel at home and find familiar keywords, like describe
, context
, and it
blocks:
It is easy to implement the code to make the specs pass:
How to run the specs? gradle init
command will create a basic project structure for us. We will need to provide the configuration options in the settings.gradle
and build.gradle
files:
JUnit 5 dependency is required as Spek 2 doesn’t provide any assertions library. See JUnit 5 User Guide for a detailed documentation. Alternatives include kotlin-test
, HamKrest, Expekt, and Kluent.
Now we are finally able to run the tests with the help of generated Gradle wrapper:
And what if we break one test? Let’s find out:
I hope this blog post will guide you through the setup of Spek 2 framework with Kotlin and Gradle in no time!
You can find the code for this blog post at 98elements/calculator GitHub repository.