Spring Restdocs and Spring Cloud Contract with Cucumber

In this post, I will describe Spring Restdocs and Spring Cloud Contract integration into Cucumber tests. The main problem is that we can’t use the most of common JUnit and Spring Test annotations like @Before, @After and @Rule in Cucumber tests, so we have to set up testing environment manually.

Project dependencies

Our test project will be a secured rest service:

Cucumber feature and runner

We will develop a service providing contacts list. We can describe it in this feature:

In our next step we need to create a class running our Cucumber tests:

  • With annotation @RunWith we specify runner class that will be used in our tests
  • With annotation @CucumberOptions we specify Cucumber options:
    • Property strict defines implementation mandatory for all steps definitions
    • Property glue defines a package containing classes with steps definitions implementation
    • Property features defines a location containing Cucumber tests features

If we try to run our tests right now we’ll get output like this:

So we need to implement listed methods. But first of all we should integrate Spring Test into our Cucumber tests.

Spring Test integration and steps definitions implementation

We need a class initializing Spring application context and configuring Spring Restdocs and Spring Cloud Contract.

Note than we cannot use Cucumber’s @Before and @After annotations in this class. But we can do it in classes with steps definitions implementation.

So now we can implement step definitions in a class extending SpringCucumberIntegrationTest:

And implementation of controller satisfying our tests will be:

Additional resources