Spring Boot REST API Unit Testing With JUnit
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. You can also participate - the source code is located here. 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.XXX).
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 this window with an empty Java project:
Step 2 - Add Dependencies
Now that we have a project, we need to setup the dependencies. You can use these dependencies, since they are public.
To do that, double click on your build.gradle file and add the following gradle configuration file:
Step 3 - Write Your Unit Test via JUnit
In Intellij IDEA, go to the class that you want to test. Hit Cmd + 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. You can see this in the following screenshot:
I personally prefer to group tests (as you can see in the same picture - there are 3 folders: bdd, rest, unit) according to the test types: REST, UNIT, BDD, etc. For that reason, I create the test classes by myself. For this example ArrivalControllerTest is located at the test/java/com/demo/unit/controller path.
Here is the test class itself:
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 (code snippet above):
- Creates an Arrival entity and sets the test value for the city
- Creates a list of Arrivals (because we will have just one member, it can be a singeltonList)
- Using given from mockito, makes sure the mocked ArrivalController will return a list of Arrivals
- Performs a GET request to the mocked controller with the credentials and performs simple assertions:
- Status - 200 (which isOk)
- The JSON object has one member
- The JSON body has a city key with the value we set
The second test method does the same for the getArrivalsById(). The difference is that it assumes one JSON object result instead of a list of Arrivals of JSON objects.
That’s all. Now we can execute this single test by clicking the play button at the beginning of the line of the method name (see the following picture). The purpose of this execution is to make sure the test is working properly:
After execution you will see this results of test execution, including the status, count and stacktrace. We can see that our test passed (on the left side), the number of tests (the progress bar is in the middle up top) and the stacktrace for execution.
That’s it for that one controller. The next step will be to add tests for all controllers.
Step 4 - Setting up the Unit Tests for the APIs
Now, let’s test one API repository class with this unit test. This is a unit test that covers the database testing part. For example, writing test data to the DB and afterwards verifying it is properly stored.
Like in the previous part, go to the ArrivalRepository class, hit Cmd + Shift + T and create a new test class via IntelliJ IDEA or by yourself.
This is the code for that test class:
In this test, we are using the H2 database for testing. This is common practice. Otherwise, you need to have the same type of database set up in all test/dev environments, maintain them and make sure you clean them up after test execution. This is not necessary when you use the H2 DB, because it is in the memory. After the test(s) is finished, the database will be fully dropped.
The test covers the following:
- Use entityManager to create two new rows of data in the Arrival table of test H2 database
- Search for all records from the database via findAll query
- Perform assertions on the size of the data and the equality of the gathered objects
The second method does the same, but because it is for findAllById, it checks just one object equality.
That’s al! Now you can do the same for all other repository classes with their methods.
Step 5 - Running the Unit Tests on Your APIs
After all the controller and repository class tests are set up, we need to execute them. Do that by highlighting the folder unit -> right click -> select “Run ‘Tests’ in ‘com.demo.unit’ with Coverage” (see next picture), so we will have also the code coverage report.
These are the coverage results, showing how many classes and methods are covered by unit tests:
That’s it! You now know how to run Unit Tests with JUnit for REST APIs. Looking to automate your API tests? Get your API Testing started with BlazeMeter.