How to pass the Java SE 8 Programmer I exam

This article was first published on Medium.

This post describes how I passed the Java SE 8 Programmer I exam.

Why take the exam

Opinions differ on how useful it is to pass this exam. It certainly isn’t easy. You’ll need to know quite a lot about Java syntax, and what the compiler will or will not allow you to do. However, it does not teach you to be a good Java programmer; you don’t have to write any actual code, and the code examples provided are definitely not clean code. They might even be anti-patterns.

Exam guide

When I took the exam, there was only one study guide available for Java 8:

OCA: Oracle Certified Associate Java SE 8 Programmer I Study Guide: Exam 1Z0-808 by Jeanne BoyarskyScott Selikoff

Overall, this guide was very helpful. It covers what you need to know, and provides practice questions at the end of each chapter, as well as several practice exams (which are also accessible online). It also provides great tips on how to pass the exam. The best tip for me was: for each question, if one of the options is “does not compile”, check if the code example will compile before looking at any of the other answers.

Personally, I found the book very helpful. Although some topics weren’t quite clear enough for me, and I did end up googling additional information.

In the mean time, other guides have become available. Since I didn’t use them, I can’t comment on their quality. I might try the guide by Mala Gupta, as I found her Java 7 version to be quite concise (which is helpful if you need to know exactly what will or won’t compile).

Practice

Another thing I did was write lots of code snippets to figure out some details; this way you see exactly what will compile or not, and what the result will be. It will help you find some common mistakes everyone makes when first starting out (missing semi-colons and brackets, etc.). And running code with a debugger will help you understand better what’s going on.

Mock exams

Apart from studying the exam topics, both by reading and trying out code, I found practice exams essential. Practice taking the exam as much as you can! Any exam guide will likely offer one or more practice exams. In addition, you can buy more mock exams.

In my case, I bought exams from Enthuware, which are good quality and not very expensive. They helped me learn the how to answer the types of questions you might expect on the exam, as well as to manage my time. (Pro tip: mark questions you’re not sure of and come back to them later. Do answer them; an answer that may or may not be correct, is better than no answer which is sure to be incorrect).

In addition, it showed me which areas were my weakest. Then, I would research those topics some more and clear up any confusion I had before doing another mock exam. Once I was consistently passed the mock exams, I also passed the actual exam.

Course

Because my employer at the time paid for it, I also did a course at Oracle. This one week course covers all of the topics, with some exercises. It is useful to have an instructor to help explain things to you. If you don’t take the course, you might have to ask friends or coworkers. In my opinion, doing more mock exams (even if you pay for them yourself) is better value for money. But if your employer is willing to pay for the course, it can’t hurt.

Conclusion

If you want to pass the exam, it will take some work. Don’t just read a book, but practice; both with code and with mock exams.

The exam is not easy and therefore does show that you have a firm grasp of the language. However, it doesn’t show that you are able to use it well. For that, you’ll need actual experience.

Managing state in Cucumber-JVM using Spring

This article was first published on Medium.

A frequently asked question about Cucumber-JVM is how to share state between steps. This post describes how to use Spring with Cucumber to help you share objects between steps, without accidentally sharing state between scenarios (a common cause of flaky scenarios).

First of all, why not use static variables?

A solution often seen to share variables or objects between steps, is to declare static variables at the top of the step definitions file. However, there are several downsides this approach:

  1. As your project grows, you’ll probably want to divide your step definitions into different classes, divided into meaningful groups. At that point, you can no longer use the static variables declared in one step definition file.
  2. Using static variables might cause your tests to accidentally leak state into other scenarios, making them unreliable. Test automation is only any good if it is reliable.

Using Dependency Injection

The recommended solution to share state is to use Dependency Injection (DI). Cucumber supports several DI frameworks, including PicoContainer, Spring and Guice.

Using Dependency Injection with Cucumber will bring you several benefits:

  • You can safely share state between your steps
  • It will help improve the design of your test code; making it easier to share state between different step definition classes (so you can split them into meaningful groups).
  • It will create and manage instances of classes for you.

Choosing a Dependency Injection framework

If your project already uses Dependency Injection, you could use the framework you already have. If not, consider using PicoContainer; it’s very light-weight and easy to use (at least, this is my personal experience in side projects).

Since my team already uses Spring in our projects, we’ve opted to use Spring with Cucumber.

Adding the cucumber-spring dependency

In order to use Spring with Cucumber, we need to add a cucumber-spring dependency to our pom.xml:

<dependency>
<groupId>io.cucumber</groupId>
<artifactId>cucumber-spring</artifactId>
<version>2.4.0</version>
<scope>test</scope>
</dependency>

Other dependencies

If you are using Spring and Cucumber in your project, you will already have those dependencies. Otherwise, you should add those as well.

Annotation based configuration

If you are using annotation based configuration, you can register your classes as Beans to be managed by Spring:

  • Add the @Component annotation to each of the classes you’d like Spring to manage for you.
  • Add an annotation to specify the scope: the @Scope("cucumber-glue"), in order to have cucumber-spring remove them after each scenario!
  • Add the location of your classes to the @ComponentScan of your (test) configuration.
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@Configuration
@ComponentScan("your.package")
public class Config {
}

This approach works for any classes that you have defined yourself. This may include:

  • domain objects (like a “Customer” or an “Account”)
  • any other step definition files (if you have split your files)
  • any “services” or “helper” classes you extract to represent parts of the system your tests interact with (like PageObjects, REST API’s, etc.). The steps can then call these services/helpers, instead of each other.

If you are using classes that you have not defined yourself, you cannot annotate them as Components for Spring to find with the component scan. You will have to explicitly register them as Beans in your (test) configuration.

Here is an example, using Selenium WebDriver:

import org.openqa.selenium.WebDriver;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;

@Configuration
@ComponentScan("your.package")
public class Config {
    @Bean
    @Scope("cucumber-glue")
    public WebDriver webDriver() {
        // return a driver with desired capabilities
    }
}

In our latest projects, we are using SpringBoot. We can annotate our StepDefinitions class with @SpringBootTest(classes = [Config.class]);.

XML configuration

Alternatively, you can specify your beans in a .cucumber.xml file, like this. Here is an example (again using Selenium WebDriver; this could also be one of your own classes):

<bean class="org.openqa.selenium.WebDriver" scope="cucumber-glue" />

You can annotate your StepDefinitions with @ContextConfiguration("classpath:cucumber.xml").

Using the Beans

You can now use the Beans, by autowiring them where you need them.

For example, you can Autowire your WebDriver to your PageObject:

import org.openqa.selenium.WebDriver;
import org.springframework.beans.factory.annotation.Autowired;

public class PageObject {
    @Autowired
    WebDriver driver;    // the rest of your page object
}

Conclusion

As you can see, it is relatively easy to add Cucumber-Spring to manage state. You are now able to safely share state between your steps, as well as split your step definition files into meaningful groups.

This will make your project easier to understand and maintain, and your tests more reliable.

Getting started with Cucumber in Java — A 10 minute tutorial

This article was first published on Medium.

This tutorial will tell you how to get started with Cucumber-jvm in Java. It is intended as a brief, easy guide. For more examples on how to use Cucumber with Java or Kotlin, check the links at the bottom of this tutorial.

Prerequisites

To get started with Cucumber in Java, you will need the following:

  • Java SE — Java 8 (Java 9 is not yet supported by Cucumber)
  • Maven — Version 3.3.1 or higher
  • An IDE editor, for example IntelliJ IDEA (which will be used in this introduction; the community edition is free!)
  • A Cucumber plugin for your IDE, for example IntelliJ IDEA Cucumber for Java plugin to go with IntelliJ IDEA

Setting up the project

First, we need to set up the project so we can use Cucumber.

Create a Maven project

In this tutorial, we’re using Maven to import external dependencies. We start by creating a new Maven project, which will automatically create some of the directories and files we will need.

To create a new Maven project in IntelliJ IDEA:

  1. Click the menu option File > New > Project
  2. In the New project dialog box, select Maven on the left (if it isn’t already selected)
  3. Make sure that the Project SDK is selected (for instance, Java 1.8) and click Next
  4. Specify a GroupId and ArtifactId for your project and click Next
  5. Specify a Project name and Project location for your project (if needed) and click Finish

You should now have a project with the following structure:

├── pom.xml
└── src
├── main
│ └── java (marked as sources root)
│ └── resources (marked as resources root)
└── test
└── java (marked as test sources root)

Add Cucumber to your project

Add Cucumber to your project by adding a dependency to your pom.xml:

<dependencies>
<dependency>
<groupId>io.cucumber</groupId>
<artifactId>cucumber-java</artifactId>
<version>2.3.1</version>
<scope>test</scope>
</dependency>
</dependencies>

In addition, we need the following dependencies to run Cucumber with JUnit:

<dependencies>
...
<dependency>
<groupId>io.cucumber</groupId>
<artifactId>cucumber-junit</artifactId>
<version>2.3.1</version>
<scope>test</scope>
</dependency> <dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
</dependencies>

If you have IntelliJ IDEA configured to auto-import dependencies, it will automatically import them for you. Otherwise, you can manually import them by opening the Maven Projects menu on the right and clicking the Reimport all Maven Projects icon on the top left of that menu. To check if your dependencies have been downloaded, you can open the External Libraries in the left Project menu in IntelliJ IDEA.

To make sure everything works together correctly, open a terminal and navigate to your project directory (the one containing the pom.xml file) and enter mvn clean test.

You should see something like the following:

[INFO] Scanning for projects...
[INFO]
[INFO] -------------------------------------------------------------
[INFO] Building cucumber-tutorial 1.0-SNAPSHOT
[INFO] ------------------------------------------------------------- <progress messages....>[INFO] -------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] -------------------------------------------------------------
[INFO] Total time: <time> s
[INFO] Finished at: <date> <time>
[INFO] Final Memory: <X>M/<Y>M
[INFO] -------------------------------------------------------------

Your project builds correctly, but nothing is tested yet as you have not specified any behaviour to test against.

Specifying Expected Behaviour

We specify the expected behaviour by defining features and scenarios.

The feature describes (part of) a feature of your application, and the scenarios describe different ways users can use this feature.

Creating the Feature Directory

Features are defined in .feature files, which are stored in the src/test/resources/ directory (or a sub-directory).

We need to create this directory, as it was not created for us. In IntelliJ IDEA:

  1. In the Test folder, create a new directory called resources.
  2. Right click the folder and select Mark directory as > Test Resources Root.
  3. You can add sub-directories as needed. Create a sub-directory with the name of your project in src/test/resources/

Our project structure is now as follows:

├── pom.xml             (containing Cucumber and JUnit dependencies)
└── src
    ├── main
    │   └── java        (marked as sources root)
    │   └── resources   (marked as resources root)
    └── test
        ├── java        (marked as test sources root)
        └── resources   (marked as test resources root)
                └── <project>

Creating a Feature

To create a feature file:

  1. Open the project in your IDE (if needed) and right-click on the src/test/resources/<project> folder.
  2. Select New > File
  3. Enter a name for your feature file, and use the .feature extension. For instance, belly.feature.

Our project structure is now as follows:

├── pom.xml             (containing Cucumber and JUnit dependencies)
└── src
├── main
│ └── java (marked as sources root)
│ └── resources (marked as resources root)
└── test
├── java (marked as test sources root)
└── resources (marked as test resources root)
└── <project>
└── belly.feature

Files in this folder with an extension of .feature are automatically recognized as feature files. Each feature file describes a single feature, or part of a feature.

Open the file and add the feature description, starting with the Feature keyword and an optional description:

Feature: Belly
Optional description of the feature

Creating a Scenario

Scenarios are added to the feature file, to define examples of the expected behaviour. These scenarios can be used to test the feature. Start a scenario with the Scenario keyword and add a brief description of the scenario. To define the scenario, you have to define all of its steps.

Defining Steps

These all have a keyword (GivenWhen, and Then) followed by a step. The step is then matched to a step definition, which map the plain text step to programming code.

The plain text steps are defined in the Gherkin language. Gherkin allows developers and business stakeholders to describe and share the expected behaviour of the application. It should not describe the implementation.

The feature file contains the Gherkin source.

  • The Given keyword precedes text defining the context; the known state of the system (or precondition).
  • The When keyword precedes text defining an action.
  • The Then keyword precedes text defining the result of the action on the context (or expected result).

The scenario will look this:

Scenario: a few cukes
Given I have 42 cukes in my belly
When I wait 1 hour
Then my belly should growl

Running the test

To run the tests from JUnit we need to add a runner to our project.

Create a new Java class in your src/test/java/<project> directory, called RunCucumberTest.java:

package <project>;

import cucumber.api.CucumberOptions;
import cucumber.api.junit.Cucumber;
import org.junit.runner.RunWith;

@RunWith(Cucumber.class)
@CucumberOptions(plugin = {"pretty"})
public class RunCucumberTest{
}

Our project structure is now as follows:

├── pom.xml             (containing Cucumber and JUnit dependencies)
└── src
├── main
│ └── java (marked as sources root)
│ └── resources (marked as resources root)
└── test
├── java (marked as test sources root)
│ └── <project>
│ └── RunCucumberTest.java
└── resources (marked as test resources root)
└── <project>
└── belly.feature

The JUnit runner will by default use classpath:package.of.my.runner to look for features. You can also specify the location of the feature file(s) and glue file(s) you want Cucumber to use in the @CucumberOptions.

You can now run your test by running this class. You can do so by right-clicking the class file and selecting RunCucumberTest from the context menu.

You should get something like the following result:

1 Scenarios (1 undefined)
3 Steps (3 undefined)
0m0.015s
You can implement missing steps with the snippets below:@Given("^I have (\\d+) cukes in my belly$")
public void i_have_cukes_in_my_belly(int arg1) throws Exception {
// Write code here that turns the phrase above into concrete actions
throw new PendingException();
}@When("^I wait (\\d+) hour$")
public void i_wait_hour(int arg1) throws Exception {
// Write code here that turns the phrase above into concrete actions
throw new PendingException();
}@Then("^my belly should growl$")
public void my_belly_should_growl() throws Exception {
// Write code here that turns the phrase above into concrete actions
throw new PendingException();
}
Process finished with exit code 0

As we can see, our tests have run, but have not actually done anything — because they are not yet defined.

Define Snippets for Missing Steps

We now have one undefined scenario and three undefined steps. Luckily, Cucumber has given us examples, or snippets, that we can use to define the steps.

To add them to a Java class in IntelliJ IDEA:

  1. Create a new Java class in your src/test/java/<project> folder (for instance, StepDefinitions.java)
  2. Paste the generated snippets into this class

IntelliJ IDEA will not automatically recognize those symbols (like @Given@When@Then), so we’ll need to add import statements. In IntelliJ IDEA:

  • Add import statements for @Given@When@Then (underlined in red)

In IntelliJ IDEA you can do so by putting your cursor on the @Given symbol and press ALT + ENTER, then select Import class.

Our project structure is now as follows:

├── pom.xml             (containing Cucumber and JUnit dependencies)
└── src
├── main
│ └── java (marked as sources root)
│ └── resources (marked as resources root)
└── test
├── java (marked as test sources root)
│ └── <project>
│ └── RunCucumberTest.java
│ └── StepDefinitions.java
└── resources (marked as test resources root)
└── <project>
└── belly.feature

Now, when you run the test, these step definitions should be found and used.

Note: Run configurations

If this does not work, select Run > Edit Configurations, select Cucumber java from the Defaults drop-down, and add the project name to the Glue field on the Configuration tab.

Your result will include something like the following:

cucumber.api.PendingException: TODO: implement me
at skeleton.Stepdefs.i_have_cukes_in_my_belly(Stepdefs.java:10)
at ✽.I have 42 cukes in my belly(/Users/maritvandijk/IdeaProjects/cucumber-java-skeleton/src/test/resources/skeleton/belly.feature:4)

The reason for this is that we haven’t actually implemented this step; it throws a PendingException telling you to implement the step.

Implement the steps

We will need to implement all steps to actually do something.

  • Update your StepDefinitions.java class to implement the step definition.

The step can be implemented like this:

@Given("^I have (\\d+) cukes in my belly$")
public void I_have_cukes_in_my_belly(int cukes) throws Throwable {
Belly belly = new Belly();
belly.eat(cukes);
}

To make this step compile we also need to implement a class Belly with a method eat().

  • Implement the class Belly.java inside your src/main/java/<project> folder; create your <project> directory here (if needed)

Our project structure is now as follows:

├── pom.xml             (containing Cucumber and JUnit dependencies)
└── src
├── main
│ └── java (marked as sources root)
│ │ └── <project>
│ └── Belly.java
│ └── resources (marked as resources root)
└── test
├── java (marked as test sources root)
│ └── <project>
│ └── RunCucumberTest.java
│ └── StepDefinitions.java
└── resources (marked as test resources root)
└── <project>
└── belly.feature

Now you run the test and implement the code to make the step pass. Once it does, move on to the next step and repeat!

PendingException

Once you have implemented this step, you can remove the statement throw new PendingException(); from the method body. The step should no longer thrown a PendingException, as it is no longer pending.

Result

Once you have implemented all your step definitions (and the expected behaviour in your application!) and the test passes, the summary of your results should look something like this:

Tests run: 5, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.656 secResults :Tests run: 5, Failures: 0, Errors: 0, Skipped: 0[INFO] -------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] -------------------------------------------------------------
[INFO] Total time: 5.688 s
[INFO] Finished at: 2017-05-22T15:43:29+01:00
[INFO] Final Memory: 15M/142M
[INFO] -------------------------------------------------------------

Examples

To get started with a working project, try the cucumber-java skeleton project which is available from GitHub.

For more examples of how to use Cucumber, have a look at the examples provided in the cucumber-jvm project on GitHub.

If you’d like to try Cucumber with Kotlin, have a look at my blog post.

Note: This tutorial was originally written as part of the new Cucumber documentation. You can find the cucumber documentation project on GitHub. It was adapted a little here to make a stand-alone tutorial.

Take-aways from European Testing Conference 2018 — Do try this at home!

This article was first published on Medium.

This week I was lucky enough to attend European Testing Conference in Amsterdam. To get an impression of the conference, you can visit their website, read up on the #EuroTestConf hashtag on Twitter, or check any of the links at the end of this post.

In this blogpost, I’d like to share some of the take-aways from this conference. Do try this at home!

  1. “Painless Visual Testing” — Gojko Adzic

During the first keynote, Gojko Adzic likened visual testing to traveling with children: “always more painful and expensive than expected”.

Tools can help you collect data, but cannot determine whether the result looks “good”. We will often have to visually inspect the UI. Existing tests break when we makes changes to the UI.

To deal with this, Gojko introduced the idea of visual approval testing and gave a demo of a tool built for that purpose: https://github.com/AppraiseQA/appraise

It would be fun to play with this tool, or at least this idea, to see how this could help make visual testing easier.

An earlier version of this talk can be found here.

2. How Would You Test a Text Field? — Maaret Pyhäjärvi

Maaret used the interview question “ How Would You Test a Text Field?” to generate ideas on how to test a text field, and illustrate how the types of answers people give indicate their level of test experience and mindset.

Some resources mentioned in the talk:

3. Writing Better BDD Scenarios — Seb Rose and Gáspár Nagy

During the workshop, Seb mentioned Example Mapping as described by Matt Wyne

4. Generating Test Scenarios” — Llewellyn Falco

Llewellyn showed us how to quickly increase test coverage by generating test cases. This is also something I’d love to play with!

Of course, he had to first show us his infamous sparrow deck:

Also, the BugMagnet tool was mentioned:

Having just recently heard of BugMagnet, I definitely plan to use this at work!

For more on approval testing: http://approvaltests.com/

5. Automating repetitive communication tasks with a Bot” — Pooja Shah

Pooja Shaj showed us chatbot Alice. You can find the repository on GitHub: https://github.com/moengage/alice

6. Interactive sessions

The conference made a point of being interactive; a lot of the insights came from great keynotes and workshops, as well as fellow attendees.

The interactive parts of the conference included a speed meet (talk to different people for 5 minutes each), lean coffee (facilitated discussion) and open space (free format to present, discuss or ask for help).

More on Lean Coffee: http://leancoffee.org/

One of the questions raised in our group was “How to motivate developers to test?”. Apart from the obvious “managing programmers is like herding cats”, one of the ideas mentioned was to have a bug bash.

Wrap up

The conference ended with a retrospective.

As you can see, we had a lot of fun, learned a lot and went home with new ideas to try out!

Read more:

If you want to read more about the conference, check out the following (especially the sketch notes by @marianneduijst and @KatjaBudnikov):

Conferences as a change toolMaaret Pyhäjärvi

European Testing Conference 2018 – Coming HomeLisi Hocke

ETC 2018, it was simply awesomeAmit Wertheimer

ETC 2018, did I say it was awesome?Amit Wertheimer

European Testing Conference 2018Markus Tacker

What I learned on first day of European Testing Conference 2018 – Karlo Smid

Arena lifeSeb Rose

Jackpot!Seb Rose

European Testing Conference 2018 #EuroTestConfKatja Budnikov

Collection of Sketchnotes of #EuroTestConfMarianne Duijst

Getting started with Java Programming

This article was first published on Medium.

This is a blog post I’ve been meaning to write for years about how I got started learning Java. It describes the resources that worked for me; and what I recommend to people who ask me how to get started. From now on, I can just point them to this blog. 🙂

Resources

Fortunately, there are many great resources available nowadays to learn Java. (Or any programming language or Computer Science skills, really.)

Here are some that helped me get started over four years ago:

1. The New Boston (video tutorials)

Bucky Roberts created a series of video tutorials that will help you get started with Java programming, from installing the JDK to basic syntax and moving on to different language features. He explains everything using example code. What I did (and recommend) was to follow along with the tutorial, making sure that my code ran. In the beginning, it would take me double the length of the video (or more!) to get it to work, due to many small typing or syntax errors. By the end of the tutorial, I would often anticipate where he would go and type the code before he did.

The courses are available on YouTube (https://www.youtube.com/playlist?list=PLFE2CE09D83EE3E28). Once you finish the Beginner course, you can continue with the Intermediate course.

2. Head First Java (book)

This book was recommended by a coworker who was helping our team learn and improve our technical skills. It covers the basics of Java syntax and Object Oriented Programming. There are questions and exercises throughout the book.

More information on the publisher’s website: http://shop.oreilly.com/product/9780596009205.do

3. Kattis and HackerRank (practice)

My manager at the time recommended Kattis (https://open.kattis.com/) for practice. This is one of many sites that offers programming challenges. You can write your solution to any one of the challenges on the site; and when you submit your solution, it will run against a set of (secret) tests.

Solving challenges taught me several different things; I learned to write working Java code, but I also learned to search for how to do certain things. For example, when a challenge called for manipulation of Strings, I would either google how to do what I wanted and/or if I knew there was a Java class that might offer the behavior I needed, I would google the Java documentation for that class. In addition, it taught me to look for edge cases, when my solution failed with a wrong answer. Finally, it taught me to improve my code, to make it faster when it didn’t meet the time limit. The only downside of Kattis (for me, anyway), is that it requires knowledge of algorithms.

In addition to Kattis, I used HackerRank (https://www.hackerrank.com) for even more practice. They offer challenges, contests, and several tutorial tracks as well. The upside of the tutorials is that they focus more on real life problems you might actually need to solve in your job or side project.

4. Code reviews / Mentoring

Finally, I was lucky enough to have a friend who is a very experienced developer and kind enough to review my code. This was by far the best way to learn how to write good code! So don’t be afraid to ask someone you know and trust to look at your code and tell you how it could be improved.

Conclusion

This is how I got started with Java programming. These are the resources I recommend to people when they ask to get started.

I hope they work for you too!

If you have found other resources that really helped you, please let me know which ones are your favorites and why.

For more resources, check out this repo on Github: https://github.com/mlvandijk/programming-links/blob/master/README.md

My thanks to Thomas Sundberg for the review!

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