How to Use Rest Assured and Spring Boot Test For API Testing
Using Rest Assured and Spring Boot Tests in combination
REST API development is a common task. Developers are to code a lot of endpoints and follow a succession of standard operations: develop an endpoint, run their application on a local machine and test it, create unit tests and run them, publish the endpoint to a dev environment and test it, publish the endpoint to a pre-live environment and test it. There is really a lot of work with the endpoint.
We can use Swagger or Postman to simplify the work. But many developers prefer to automate the checking process in a Java way.
To do this, we have to choose suitable technologies and to create the necessary tests. A good example of such technologies would be a combination of Rest Assured and Spring Boot Test. In this article we will demonstrate how to quickly create useful tests for an API. We will use Rest Assured to test our API and Spring Boot Test to set up Rest Assured for any environment.
First of all, we have to understand what environments we want to test and what type of authentication our application has. Let’s take a local machine and a dev env as our environments, and the Basic Authentication as a type of authentication.
Let’s start, we have to create an environment configuration using a properties file.
We can separate different environments using spring profiles:
And add configuration classes for these properties:
The second step is to set up the main abstract test class with RestAssured.
We can use the power of the Spring Boot Test to make the configuration flexible:
We can also separate the main logic and the logic of authentication and specifications:
Finally, we can create the first unit test class and check our endpoint:
The unit test can help us to check the endpoint /api/endpoint and to verify the HttpStatus.OK response. We have the endpoint tested, but we can see a problem. We want to check specific JSON data and different environments can provide different data.
To resolve the situation we can add a parser to convert JSON data into the same view:
To be flexible we have added a couple of variables.
The first one, activeProfile, is for choosing the correct file for a Spring profile.
The second one is caseName, which is used for choosing the necessary file for the corresponding test. The last step is to create files using the file structure: