Common Step Definitions

We are primarily dealing with REST APIs. In all our test, we need to assert the HTTP Response Code. Step Definition code to assert the HTTP Response Code can be used in multiple feature files. Hence, in this chapter, we will move that to a separate class called In future if there is a need to share a step definitions across multiple feature files, we can add those methods to

Move HTTP Response Code Assertion Step Definition to Common Step Definitions class

Navigate to following location and create the common step definitions class,

cd src/test/java/com/madrascoder/cucumberbooksample/stepdefinitions

Add the following code,

import com.madrascoder.cucumberbooksample.TestContext;
import io.restassured.response.Response;
import org.springframework.beans.factory.annotation.Autowired;

public class CommonStepDefinitions {

  private TestContext testContext;

  @Then("the save {string}")
  public void theSave(String expectedResult) {
    Response response = testContext.getResponse();
    final int actualStatusCode = response.statusCode();

    if ("IS SUCCESSFUL".equals(expectedResult)) {
      assertThat(actualStatusCode).isIn(200, 201);

    } else if ("FAILS".equals(expectedResult)) {
      assertThat(actualStatusCode).isIn(400, 412);

    } else if ("NOT FOUND".equals(expectedResult)) {

    } else {
      throw new IllegalArgumentException(
          "Expected result is invalid. Valid values are 'IS SUCCESSFUL', 'FAILS', 'NOT FOUND'");


In this chapter, we learnt how to deal with step definitions that are commonly used across multiple feature files. Test Context class that we created in the previous chapter made it possible to split the common step definitions to its own class.

In the next chapter, we will move all boiler plate REST API calls to an abstract base class and let all step definitions class extend it. This way we write less code per step definitions there by its easier to maintain.


Photo by Kit Suman on Unsplash

Previous Chapter | Scroll Up to Top | Table of Contents | Next Chapter