Alexa, tell VoxSnap to play posts from BlazeMeter
Unit Testing APIs is an important part of API testing, because Unit Testing ensures that API components will function properly. In this article we will learn how to cover Spring Boot Rest APIs with JUnit. Spring Boot is an open-source framework for application creation, and where we create our APIs.
There are many different variations and techniques to Unit Test APIs. I prefer the following combination: Spring Boot, JUnit, MockMvc and Mockito, because they are all open-source and support Java, which is my preferred language.
To start, we have to have IntelliJ IDEA, as an IDE for development, and JDK8, for using Java for development. These are my personal preferences but Eclipse, NetBeans or even a simple text editor could also be used.
Now, let’s setup a project. We will be testing controllers and repository classes. In short, we have 4 controllers (ArrivalController, DepartureController, UsersController, FlightsController) and 4 repositories (ArrivalRepository, DepartureRepository, UsersRepository, FlightsRepository). We will write tests per controller (testing the size of the JSON Object, the status of the call to the endpoint and an assertion on one item from the JSON object) and tests per repository (inserting two new items in a table and making sure the return object is equal).
Step 1 - Create an API Testing Project
1. Install IntelliJ IDEA
2. Make sure you have JDK installed (at least version 1.8.X).
Now we will create a new project.
3. Open IntelliJ and click “Create New Project”
4. Select Gradle, Java and the JDK version
5. Name your project
6. Choose the project destination
If you did everything correctly, you should now see a window with an empty Java project.
Step 2 - Add Dependencies
Now that we have a project, we need to setup the dependencies. To do that, double click on your build.gradle file and add the gradle configuration file.
Step 3 - Write Your Unit Test via JUnit
In IntelliJ IDEA, go to the class that you want to test. Hit Command + Shift + T and a popup will appear. In the popup, select “Create New Test...”. Then, IntelliJ IDEA will create a file for writing the test in. The file will be created in the default place. In our case, if we are going to cover the class ArrivalController, it will create a test class with the path test/java/com/demo/controller.
I personally prefer to group tests according to the test types: REST, UNIT, BDD, etc. For that reason, I create the test classes by myself.
In this test class we have two test methods - getArrivals and getArrivalsById. The reason we have two is because we have two methods in the controller itself, so we want to test them both.
The getArrivals method does the following:
• Creates …