Spring Boot Unit Testing (JUnit with Mockito)

Spring Boot Unit Testing (JUnit with Mockito) | The spring-boot-starter-test dependency includes junit-jupiter, vintage, mockito dependencies.

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-test</artifactId>
</dependency>

Mocking means creating dummy implementations or objects. If we want to test the Spring Boot application, then the following dummies are required:-

  • Component Scanning
  • Auto Configuration for Web Application
  • Spring Container [AnnotationConfigServletWebApplicationContext]
  • Request objects
  • Environment details(props)

We need to provide all the above details using Mock support. If run starter class that takes care of all above thing. But this time we are running a Test class.

Also see:-

Setup Full Environment (equal work to starter class)

  1. Loading properties file for Test environment. If we do not provide this, by default application.properties file is loaded. Else we can use: @TestPropertySource("classpath:application-test.properties")
  2. Create Spring Container that uses internally WebApplication Support(DispatcherServlet):-
    @SpringBootTest(webEnvironment = WebEnvironment.MOCK). It creates by default: AnnotationConfigServletWebApplicationContext
  3. Create required objects inside the container:- DataSource, HandlerMapping, ORM Config (EntityManagerFactory, EntityManager), etc. It can be implemented using: @AutoConfigureMockMvc

For the final runtime environment reference is given by MockMvc. That supports Test Dispatcher Servlet, Access Spring Container, execution of RestControllers, Database Connection support etc.

Todo Unit Test coding follow the below steps:-

  • Create one Dummy/proxy(not made by the client) HTTP Request.
  • Execute the dummy request using MockMvc and get the result(MvcResult).
  • Read the response from the result object.
  • Assert Response Data(checking Status, Body/content, header type e.t.c).
{"empName":"A","empSal":2500.0,"empMail":"[email protected]"}

Database dumps are used for Mock Testing, not the production or UAT env used.

@SpringBootTest(webEnvironment = WebEnvironment.MOCK)
@AutoConfigureMockMvc
@TestPropertySource("classpath:application-test.properties")
public class MiniProjectApplicationTests {

    @Autowired
    private MockMvc mockMvc;

    @Test
    public void testSaveOp() throws Exception {
        // 1. prepare http request
        MockHttpServletRequestBuilder request = 
          MockMvcRequestBuilders.post("/employee/update")
            .contentType("application/json")
            .content("{\"empName\":\"A\",\"empSal\":2500.0,\"empMail\":\"[email protected]\"}");

        // 2. execute request and get result
        MvcResult result = mockMvc.perform(request).andReturn();

        // 3. Read Response from result
        MockHttpServletResponse response = result.getResponse();

        // 4. assert/validate result
        assertEquals(HttpStatus.CREATED.value(), response.getStatus());
        assertNotNull(response.getContentAsString());
    }

}

Examples for different request construction:-

/employee/save (POST)

MockHttpServletRequestBuilder request = 
    MockMvcRequestBuilders
      .post("/employee/update")
      .contentType("application/json")
      .content("{\"empName\":\"A\",\"empSal\":2500.0,\"empMail\":\"[email protected]\"}");
/employee/all (GET)

MockHttpServletRequestBuilder request = 
    MockMvcRequestBuilders
      .get("/employee/all")
      .accept("application/json");
/employee/remove/10 (DELETE)

MockHttpServletRequestBuilder request = 
   MockMvcRequestBuilders.delete("/employee/remove/10");
/employee/find/10 (GET)

MockHttpServletRequestBuilder request = 
    MockMvcRequestBuilders
      .get("/employee/find/10")
      .accept(MediaType.APPLICATION_XML);
/employee/update (PUT)

MockHttpServletRequestBuilder request = 
    MockMvcRequestBuilders
      .put("/employee/update")
      .contentType("application/json")
      .content("{\"empName\":\"A\",\"empSal\":2500.0,\"empMail\":\"[email protected]\"}");

If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or do you find anything incorrect? Let us know in the comments. Thank you!

Leave a Comment

Your email address will not be published. Required fields are marked *