Questions Management – Core Option Service – Build API to create a new option 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 Option Service, we need to prepare the following:

First, we need to create an OptionRepository interface extends from the ReactiveMongoRepository interface to manipulate the MongoDB database.

The contents of the OptionRepository interface will look like this:

with the Option document object:

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

Next I 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 8083 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 OptionController with the following content:

With this declaration, I expose APIs for the Core Option Service with the request URL starting with “/option”.

To work with MongoDB server, we need to inject OptionRepository into OptionController class as follows:

To build API to add a new option, I will add a method to expose a POST request “/add” with data in the body as the Option 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:

At this point, we have completed the API to create a new option for the Core Option Service, let’s test it.

Questions Management – Core Option Service – Build API to create a new option 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 OptionControllerTest located in the src/test/java package to test the OptionController class.

Mock OptionRepository class:

Inject the mock object of the OptionRepository to the OptionController class:

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

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

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

Add Comment