Questions Management – Core Question Service – Build the API for adding a new question using Spring WebFlux and Spring Data MongoDB Reactive

Check out the full series of Questions Management tutorial here.

Before we go into building the first API for the Core Question Service, we need to prepare the following:

First, we need to create a new QuestionRepository interface extends from the ReactiveMongoRepository interface to manipulate with the MongoDB database.

The contents of the QuestionRepository interface will look like this:

with Question document object:

You can see more the tutorial Reactive REST APIs with Spring Data MongoDB Reactive and Spring WebFlux for more information.

Next we will configure the connection to the MongoDB server.

Currently I am using MongoDB server without authentication mode so I just declare the following in application.properties file:

I will run this service using port 8081, so I will add the server.port property in the application.properties file as follows:

OK, everything is ready, now we will go to the main part of this tutorial!



I will create a controller named QuestionController with the following content:

With this declaration, I expose the APIs to the Core Question Service with the request URL starting with “/question”.

To work with MongoDB server, we need to inject QuestionRepository into QuestionController class as below:

To build the API for adding a new question, I will add a new method to expose a POST request “/add” with the data in the body as a Question document object:

Because Spring MongoDB Reactive has provided us with the save() method to save the data to MongoDB, we just need to call this method:

Now that we’ve finished building the API for adding a new question for the Core Question Service, let’s test it out.

Questions Management – Core Question Service – Build the API for adding a new question using Spring WebFlux and Spring Data MongoDB Reactive


The last thing we need to do is add a new Unit Test to the code we just added.

I will create a new class called QuestionControllerTest located in the src/test/java package to test the QuestionController class.

QuestionRepository mock class :

Inject the QuestionRepository’s mock object into the QuestionController class:

To use mock objects, we have to initialize them one by one so we will add a method with the JUnit @Before annotation as follows:

The code to test the createQuestion() method is as follows:

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

Add Comment