Kukumber — Getting started with Cucumber in Kotlin

This article was first published on Medium.

My team is creating an application in Kotlin. To make development of Cucumber tests easier, we decided to also use Cucumber-jvm with Kotlin instead of Java. Fortunately, it is possible to use cucumber-java8 in Kotlin (kotlin-java8)

Prerequisites

If you’d like to follow along, make sure you have the following installed:

Add dependencies

We use Maven, so we added the following dependencies to our pom.xml:

Maven dependencies for Cucumber-jvm

Note: The cucumber-junit dependency is added so we can add a JUnit Runner to run our tests, which we will do later.

If you don’t have Kotlin already configured in your project, you’ll need to add those dependencies also (or have IntelliJ IDEA do it for you).

Add a feature file

In our src/test/resources folder we create a new directory and add a .feature file. For this example, we’ll reuse the belly.feature from the cucumber-java-skeleton

Feature file `belly.feature`

Unfortunately the IntelliJ IDEA Cucumber plugin does not (yet) support a link between the steps in our feature file and our step definitions, like it does for Java. Also, we cannot generate snippets in Kotlin directly. Fortunately there is a work around: we can run the tests to generate snippets in Java 8 lambda style.

You can run the test from IntelliJ IDEA by right-clicking the feature file and selecting “Run ‘Feature:belly’” from the context menu.

When you run the tests, you should get something like the following result:

Generated snippets

Add Step Definitions

In the src/test/kotlin folder, we add a new Kotlin File/Class, called `StepDefs`.

We only have to write a little Kotlin code in the file:

Create StepDefs.kt

Note that our StepDefs implement the `cucumber.api.java8.En` interface, so we need to import it.

Now, when we copy-paste the generated snippets inside the `init{}` block, IntelliJ IDEA offers to convert it to Kotlin for us. Once we do, we will also need to import the `cucumber.api.PendingException` mentioned in the snippets.

Now we have the following StepDefs.kt file and we can start implementing the steps, as well as the code to make them pass!

Add snippets to StepDefs.kt

To run our features from a JUnit runner, we’ll need to add one. In the src/test/kotlin folder, we add a new Kotlin File/Class, called RunKukesTest.

RunKukesTest.kt

This code is available on GitHub: https://github.com/mlvandijk/kukumber-skeleton