Questions Management – Core Category Service – Build API to find category by id using Spring WebFlux and Spring Data MongoDB Reactive

Check out the full series of Questions Management tutorial here.

In the previous tutorial, we prepared all the necessary configurations for building the API to find a category by id like: a Category document object containing the information of a category, a CategoryRepository to manipulate with MongoDB, a CategoryController defines the APIs for Core Category Services that will start with “/category” and the connection information to the MongoDB server is configured in the application.properties file. Now, we are going to build this API!

To build the API to find category by id, I would add a method to expose a GET request “{id}” with id as the id of the category we are looking for:

The steps to find a category by id include:

First, we need to check that the category which we are searching is existing or not, depend on the id that the user is passing.

Spring Data MongoDB Reactive has provided us with a way to search by id so we just need to call it.

In case this category exists, we will return this category using the map() method with the HTTP status code of 200:

In case this category does not exist in the database, we will return the result of HTTP status code is 404 Not Found.

The entire contents of the findCategoryById() method will look like this:

Here we have completed the construction of the API to find category by id for the Core Category Service, let’s test it.

Suppose currently in the database I have the following categories:

Questions Management – Core Category Service – Build API to find category by id using Spring WebFlux and Spring Data MongoDB Reactive

then when I request to find a category with id is 5b297751366e2605cf3c0d3e:

Questions Management – Core Category Service – Build API to find category by id using Spring WebFlux and Spring Data MongoDB Reactive

The result will be:

Questions Management – Core Category Service – Build API to find category by id using Spring WebFlux and Spring Data MongoDB Reactive


Now we will add a new Unit Test for the code that we just added!

In the previous tutorial, I created a class test for CategoryController called CategoryControllerTest, a Mock object for CategoryRepository, and injected this Mock object into the CategoryController class:

Initializing the mock every time I run a test case:

Now I’m going to add two methods to test the method findCategoryById() in the CategoryController class.

A method to test if there is a category based on passing id:

A method to test for the absence of category based on passing id:

Run “Maven test” in STS or “mvn test” with Apache Maven, you will not see any errors.

Chia sẽ bài viết này ...Share on Facebook
Facebook
0Tweet about this on Twitter
Twitter
Share on LinkedIn
Linkedin

Add Comment