How to test REST Services with RestAssured

In this tutorial, we will be discussing REST Assured framework to Test JAX-RS Web services. This tutorial is designed for RESTAssured beginners, but even experienced users may find some useful tips and tricks.

RestAssured is a Java library that provides a domain-specific language (DSL) for writing powerful, maintainable tests for RESTful APIs. It allows you to write tests in a simple and intuitive way, and provides support for several popular libraries for testing such as JUnit and TestNG.

Before we dive into the specifics of using RESTAssured, it’s important to understand some of the basic concepts and terminology. Therefore, we recommend checking this article: RESTAssured tutorial

Defining the REST Service

Now that we have everything set up and have a basic understanding of the concepts, it’s time to start defining a REST Service which includes multiple endpoints, each one with different Parameter types:

@Path("/")
public class SimpleRESTService {


	@POST
	@Produces("application/json")
	@Consumes("application/json")
	@Path("json")
	public Data calculate(Data data) {
		data.setResult(data.getX()+data.getY());
		return data;
	}
	
	@Path("form")
	@POST
	@Consumes("application/x-www-form-urlencoded")
	public String login(@FormParam("email") String email, @FormParam("password") String password) {
		return "Logged with "+email+"/"+password;
	}

	@GET
	@Path("path/{id}")
	public String loginPath(@PathParam("id") String id) {
		return "Id is " +id;
	}

	@GET
	@Path("query")
	public String loginQuery(@DefaultValue("11111")  @QueryParam("id") String id) {
		return "Id is " +id;
	}


	@GET
	@Path("header")
	public String checkBrowser(@HeaderParam("User-Agent") String whichBrowser) {
		System.out.println("Browser is "+whichBrowser);
         return "Browser is "+whichBrowser;
	}

	@GET
	@Path("session")
	public String checkSession(@CookieParam("JSESSIONID") String sessionid) {
		return "Session is "+sessionid;
	}


}

This REST Service is discussed more in detail in this article: How to use Parameters in REST Services

To be able to build the Service, you need to include the Jakarta EE dependency in your Project:

<dependency>
    <groupId>jakarta.platform</groupId>
    <artifactId>jakarta.jakartaee-api</artifactId>
    <version>10.0.0</version>
    <scope>provided</scope>
</dependency>

Next, we will code our REST Assured Test class.

Coding the RESTAssured Test

Firstly, to get started using RESTAssured you should include in your Maven project the following dependencies:

<dependency>
    <groupId>io.rest-assured</groupId>
    <artifactId>rest-assured</artifactId>
    <version>${restassured.version}</version>
    <scope>test</scope>
</dependency>

<dependency>
    <groupId>org.junit.jupiter</groupId>
    <artifactId>junit-jupiter</artifactId>
    <version>${junit.version}</version>
    <scope>test</scope>
</dependency>

Also, make sure you are defining the artifact version in your properties. For example:

<junit.version>5.9.1</junit.version>
<restassured.version>4.4.0</restassured.version>

Also, to simplify your Test assertions you should include also Hamcrest. This is a library of matcher objects that can you can use to specify rules for matching objects in Java. It provides a more readable syntax for evaluating the state of an object, and is particularly useful when writing unit tests.

<dependency>
    <groupId>org.hamcrest</groupId>
    <artifactId>hamcrest-all</artifactId>
    <version>1.3</version>
</dependency>

Next, add a JUnit 5 Test class to your Project:

public class RestAssuredTest  {

	@BeforeAll
	public static void start() throws Exception {

		RestAssured.baseURI = "http://localhost:8080/rest-parameters/rest/";
	}
}	

Our class includes the @BeforeAll annotation to mark a method that should be run before all test methods in a test class. In our example, we are setting up a shared resources: the base URI for all RestAssured Tests.

Next, we will add the @Test methods to test all the Service Endpoints.

Testing JSON Payloads

Our first @Test method will Test the calculate REST Endpoint, which takes as input the Data object as JSON Object:

@Test
public void testWithJSONPayload() {
RestAssured.defaultParser = Parser.JSON;

String data = "{\"x\": \"5\",\"y\": \"10\"}";

	RestAssured.given().urlEncodingEnabled(true)
			.contentType("application/json")
			.body(data)
			.when()
			.post("/json")
			.then()
			.statusCode(200)
			.body("result", Matchers.equalTo(15));

}

Please note the RestAssured.defaultParser method which allows you to set the default parser to be used for parsing the response body of a request. As part of this Test, we use the Hamcrest Matchers.equalTo to assert that the result attribute equals to 15.

Testing Query Parameters

To test query parameters with RestAssured, you can use the queryParam method in combination with the when and get methods to make a GET request to the desired endpoint. The queryParam method allows you to specify the query parameters to be included in the request. For example:

@Test
public void testWithQueryParam() {

	RestAssured.given()
			.queryParam("id", "2")
			.when().get("/query")
			.then()
			.statusCode(200)
			.body(equalTo("Id is 2"));


}

Testing Path Parameters

To Test a Service which uses Path Parameters, you can use instead the pathParam method in combination with the when and get methods to make a GET request to the desired endpoint. For example:

@Test
public void testWithPathParam() {

	RestAssured.given()
			.pathParam("id", "2")
			.when().get("/path/{id}")
			.then()
			.statusCode(200)
			.body(equalTo("Id is 2"));


}

Testing with Form Parameters

To test Form parameters with RestAssured, you can use the formParams method to specify the form parameters in the request. For example:

@Test
public void testWithFormParam() {
String email =  "[email protected]";
	String password ="Pas54321";
	RestAssured.given().urlEncodingEnabled(true)
			.param("email", email)
			.param("password", password)
			.when().post("/form")
			.then()
			.statusCode(200)
			.body(equalTo("Logged with "+email+"/"+password));


}

Besides, you can also use the form method to specify the form parameters as a Map, like this:

Map<String, String> formParams = new HashMap<>();
formParams.put("param1", "value1");
formParams.put("param2", "value2");

given()
    .form(formParams)

Testing with Header Parameters

To test header parameters with RESTAssured, you can use the headers method to specify the header name and value that you want to test. For example:

@Test
public void testWithHeaderParam() {

	RestAssured.given().urlEncodingEnabled(true)
			.headers(
					"User-Agent", "MyJavaApplication/1.0"
			)
			.when().get("/header")
			.then()
			.statusCode(200)
			.body(equalTo("Browser is MyJavaApplication/1.0"));


}

Testing with Cookie Parameters

Finally, to test cookie parameters with REST Assured, you can use the cookie method of the RequestSpecification class. This method allows you to specify a cookie by name and value, and returns a RequestSpecification object that you can use to further configure the request. For example:

@Test
public void testWithCookie() {
String id =  UUID.randomUUID().toString();
	RestAssured.given().urlEncodingEnabled(true)

        .cookie("JSESSIONID",  id)
			.when().get("/session")
			.then()
			.statusCode(200)
			.body(equalTo("Session is "+id));


Conclusion

In this tutorial, we have covered the basics of using RESTAssured, as well as some advanced features and best practices. We hope that this tutorial will help you to get started with RESTAssured and that you feel confident using it in your own projects.

Source code for this article is available here: https://github.com/fmarchioni/mastertheboss/tree/master/test/restassured-test

Found the article helpful? if so please follow us on Socials