Questions Management – Core Category Service – Build API retrieving all categories 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 the API retrieving all the categories in the MongoDB database: a document Category object containing information about a category, a CategoryRepository to manipulate with MongoDB, a CategoryController that defines the APIs of the Core Category Service 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 API retrieving all the categories, I’m going to add a method to expose a GET request “/all” in CategoryController:

Since Spring Data MongoDB Reactive has provided us with a method to search all categories then our job just calls to use:

Very simple, right?

Suppose currently in the database I have the following categories:

Questions Management – Core Category Service – Build API retrieving all categories using Spring WebFlux and Spring Data MongoDB Reactive

then when I run the request to get all the available categories, the result will be:

Questions Management – Core Category Service – Build API retrieving all categories 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 test class 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 a method to test the findAllCategories() method of the CategoryController class, like this:

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

Add Comment