REST Assured Basics - Lab 1
1. Base Test class
The base test class is one test pattern that must be used in any layer. Let's add the basic RESTAssured configuration:
- Create a class named
BaseApiConfiguration
in thecom.workshop
package atsrc/test/java/
folder - Add the keyword abstract on its declaration
- Add the configuration necessary to execute any later test:
import io.restassured.RestAssured; import io.restassured.config.JsonConfig; import io.restassured.config.RestAssuredConfig; import io.restassured.path.json.config.JsonPathConfig; import org.junit.jupiter.api.BeforeAll; public abstract class BaseApiConfiguration { @BeforeAll static void mainConfiguration() { RestAssured.baseURI = "http://localhost"; RestAssured.basePath = "/api/v1"; RestAssured.port= 8088; RestAssured.config = RestAssuredConfig.newConfig(). jsonConfig(JsonConfig.jsonConfig().numberReturnType(JsonPathConfig.NumberReturnType.BIG_DECIMAL)); RestAssured.enableLoggingOfRequestAndResponseIfValidationFails();; } }
2. Add the restrictions tests
2.1 Create the package to add the restrictions tests
- Create an additional package called
restriction
incom.workshop
in thesrc/test/java
folder
2.2 Search for a CPF without restriction
Steps
- Create a Java class named
RestrictionsTest
incom.workshop.restriction
in thesrc/test/java
folder - Make
RestrictionsTest
extendsBaseApiConfiguration
- Create a test method named
shouldQueryCpfWithoutRestriction()
- Add the following to the test:
- pre-condition (
given()
) using a path parameterpathParam
using- key:
cpf
- value:
1234567890
- key:
- action (
when()
) to get (get()
) the/restrictions/{cpf}
endpoint - assert (
then()
) in the status code expecting HTTP 404- tip: use
HttpStatus.SC_NOT_FOUND
- tip: use
- Run the test
Expected results
- Green test execution where the verification of the status code is successful
Solution
Click to see...
import org.apache.http.HttpStatus;
import org.junit.jupiter.api.Test;
import com.workshop.BaseApiConfiguration;
import static io.restassured.RestAssured.given;
class RestrictionsTest extends BaseApiConfiguration {
@Test
void shouldQueryCpfWithoutRestriction() {
given()
.pathParam("cpf", "1234567890")
.when()
.get("/restrictions/{cpf}")
.then()
.statusCode(HttpStatus.SC_NOT_FOUND);
}
}