Check out the full series of Questions Management tutorial here.
In the previous tutorial, we prepared all the necessary configurations to be able to build the API to retrieve all the questions contained in the MongoDB database: a Question document object containing the information of a question, a QuestionRepository for manipulation with MongoDB, a QuestionController that defines the Core Question Service APIs 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 that takes all the questions, I will add a method to expose a GET request “/all”:
1 2 3 4 |
@GetMapping("/all") public Flux<Question> findAllQuestions() { } |
Since Spring Data Mongo Reactive has provided us with a method to search all the questions, our job is just to use it:
1 2 3 4 |
@GetMapping("/all") public Flux<Question> findAllQuestions() { return questionRepository.findAll(); } |
That’s it! 🙂 Let’s test us.
Suppose, my database has the following questions:
then when I run the request to get all the questions, the result will be:
Now we will add a new Unit Test for the code that we just added.
In my last post, I created a new QuestionController class called QuestionControllerTest, mock object for QuestionRepository, and inject this Mock object into the QuestionController class, initializing Mock objects each time running a test case:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
package com.huongdanjava.questionservice; import org.junit.Before; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import com.huongdanjava.questionservice.repository.QuestionRepository; public class QuestionControllerTest { @Mock private QuestionRepository questionRepository; @InjectMocks private QuestionController questionController; @Before public void init() { MockitoAnnotations.initMocks(this); } } |
Now, I will add a method to test for the method of the findAllQuestions() of QuestionController:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
@Test public void testFindAllQuestions() { // Create Question document to return when using findAll Question question = new Question(); question.setId("123"); question.setDescription("Test"); question.setCategoryId("123XYZ"); // Mock findAll() method of QuestionRepository to return a Flux when(questionRepository.findAll()).thenReturn(Flux.just(question)); // Call method Flux<Question> questions = questionController.findAllQuestions(); Question result = questions.blockFirst(); // Assertions assertEquals("123", result.getId()); assertEquals("Test", result.getDescription()); assertEquals("123XYZ", result.getCategoryId()); } |
Run “Maven test” in STS or “mvn test” with Apache Maven, you will not see any errors.