Questions Management – Core Question Service – Build API find question 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 to build an API to find question by id in the MongoDB database: a Question document object containing the information of a question, a QuestionRepository to manipulate with MongoDB, a QuestionController that defines APIs for the Core Question Service will start with “/question” 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 an API to find question by id, I would add a method to expose a GET request “/{id}” with id as the id of the question we are looking for:

The steps to look up question by id include:

First, we also need to check whether the question we are looking for does exist or not based 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 question exists, we will return it using the map() method with the HTTP status code of 200:

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

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

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

Suppose the current in the database I have the following questions:

Questions Management – Core Question Service – Build API find question by id using Spring WebFlux and Spring Data MongoDB Reactive

so when I request to find the question with id is 5ad5d9d651bd7a0aefa87fb3, the result will be:

Questions Management – Core Question Service – Build API find question 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 my last post, I created a new test class for QuestionController class called QuestionControllerTest, mock object for QuestionRepository, and injected this mock object into the QuestionController class, initializing mock objects each time I run a test case as follows:

Now we will add two methods to test for the method of findQuestionById() of the QuestionController class as follows:

A method to test for the case there is an existing question base on passing id:

A method to test for the case there is non-existing question with passing id:

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

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

Add Comment