Rest Assured BDD
- Home
- Rest Assured BDD
Using Rest Assured with BDD-style syntax lets you write more expressive and readable API tests in Java, resembling natural-language test scenarios. While Rest Assured doesn’t require Cucumber to use BDD-style syntax, you can combine it with Cucumber for full Gherkin-based BDD if needed.
1. BDD-Style Rest Assured Example (Without Cucumber)
You can use given-when-then syntax directly in Rest Assured:
import io.restassured.RestAssured;
import static io.restassured.RestAssured.*;
import static org.hamcrest.Matchers.*;
import org.junit.jupiter.api.Test;
public class BddApiTest {
@Test
public void getUserDetails() {
given()
.baseUri("https://reqres.in/api")
.log().all()
.when()
.get("/users/2")
.then()
.log().all()
.statusCode(200)
.body("data.id", equalTo(2))
.body("data.email", containsString("@reqres.in"));
}
}
2. Maven Dependencies (pom.xml
)
<dependencies>
<dependency>
<groupId>io.rest-assured</groupId>
<artifactId>rest-assured</artifactId>
<version>5.4.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest</artifactId>
<version>2.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>5.9.3</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<version>5.9.3</version>
<scope>test</scope>
</dependency>
</dependencies>
3. BDD with Rest Assured + Cucumber (Optional)
To use Gherkin feature files with Rest Assured, you can integrate Cucumber:
Feature File (src/test/resources/features/login.feature
)
Feature: Login API
Scenario: Successful login
Given I set the login payload
When I send the POST request to "/login"
Then the response code should be 200
And the response should contain a token
Step Definitions (LoginSteps.java
)
import io.restassured.response.Response;
import static io.restassured.RestAssured.*;
import static org.hamcrest.Matchers.*;
import io.cucumber.java.en.*;
import org.junit.jupiter.api.Assertions;
public class LoginSteps {
private Response response;
@Given("I set the login payload")
public void setLoginPayload() {
given().contentType("application/json")
.body("{\"email\":\"eve.holt@reqres.in\", \"password\":\"cityslicka\"}");
}
@When("I send the POST request to {string}")
public void sendPost(String endpoint) {
response = when().post("https://reqres.in/api" + endpoint);
}
@Then("the response code should be {int}")
public void checkStatusCode(int code) {
response.then().statusCode(code);
}
@Then("the response should contain a token")
public void checkToken() {
Assertions.assertNotNull(response.jsonPath().getString("token"));
}
}
Benefits of Rest Assured BDD Style
Clean, readable code with
given()
,when()
,then()
Integrated with Hamcrest matchers for expressive assertions
Easy integration with Cucumber for full BDD workflows