Cucumber Testing: Spring Cucumber Integration

I’ve been recently coding some Cucumber and Spring based tests. Integrating Spring with Cucumber can be a little tricky so I decided to share my findings in this blog post.

Please see GitHub: https://github.com/crossminds/cucumber-examples for a complete working sample project.

For technologies used I assume Java 8, Spring 4+, Maven and Cucumber 3+. Let’s start by coding a service interface – the object under test:

And an implementation:

It’s a really simple service :-). The service instance is a Spring managed bean. The Spring Java application context class is also pretty straightforward:

Now let’s do some more interesting stuff. Cucumber based Java tests typically contain these components:

  • Feature files – text files (human readable) that Cucumber interprets to execute the tests. In true TDD these files would come first. They can also be coded by a tester while a developer is working on the glue part.
  • Steps classes – they contain Cucumber glue and the actual testing logic.
  • If using Spring there’s typically also a Spring test context configuration class. This is strictly speaking not necessary but it can be really useful if you need some test specific Spring managed beans (e.g. a testing context).
  • A Runner class – the class that combines all previous components together and executes the tests.

Our feature file looks like this:

There are two scenarios testing the two business methods of the Calculator service. The tests are really rather simple ;-).

The corresponding Steps class looks like this:

Now this is getting more interesting as there are a couple of important details:

  • The Steps class implements En – an interface provided by Cucumber that makes Cucumber introspect it. This interface also defines many useful annotations and methods for defining the glue.
  • This assures that Spring annotations (for instance @Autowired) are interpreted correctly by Cucumber.
  • The instance of the Calculator business service is injected into the Steps class for testing.

The Spring application context for tests is really simple:

The most interesting component is the Cucumber runner:

The important details here:

  • The Runner class implements GlueBase (a super interface of En). This causes Cucumber to process the Spring @ContextConfiguration annotation which references the Spring testing application context.
  • The glue path contains the Steps classes and the Runner class. It’s important that the Runner class be also contained on the glue path as otherwise the Spring annotations wouldn’t be processed by Cucumber.

That’s all! With this setup Spring context will be processed as expected and dependency injection will work properly.

Leave a Reply

Your email address will not be published. Required fields are marked *