This is my third article on getting Started

In the first two articles, we showed you how to configure, write, and run a Spring Boot test program that uses Mockito to mock objects that are not easy to construct or obtain. Here’s how to write unit tests for the Controller layer and Service layer in Spring Boot.

Spring Boot Controller layer tests

Spring Boot provides a very handy tool for testing the Collector layer, using the MockMvc class to test the Controller’s interface and simulate the controller layer receiving an HTTP request without having to start a real server.

To test the Controller layer, mock the service layer on which the Controller layer depends. Since both the Service layer and the Controller layer are managed by the Spring container, Use @MockBean to mock and inject a Service.

@RestController
public class AddController{
  
  @Autowired
  private AddService addService;
  
  @RequestMapping(value = "/add", method = {RequestMethod.GET}, consumes = "application/json", produces = "application/json")
  public Response<Integer> add(
    @RequestParam("a") int a,
    @RequestParam("b") int b
  ) {
    int sum = addService.add(a,b);
    return newResponse<Integer>(sum); }}@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureWebMvc
@AutoConfigureMockMvc
public class AddControllerTest {
	@MockBean
  private AddService addService;

  @Autowired
  private MockMvc mockMvc;
  
  @Test
  public void addTest(a){
    when(addService.add(1.1)).thenReturn(2);
    
    mockMvc.perform(get("/conv")
        .contentType(MediaType.APPLICATION_JSON)
        .param("a"."1")
        .param("b"."1"))
        .andExpect(status().isOk())
        .andExpect(jsonPath("$.code", is(0)))
        .andExpect(jsonPath("$.data", is(new Integer(2)))); }}Copy the code
  • JsonPath Expressions

    JsonPath Expressions are used to represent the root of JSON data, the root of JSON data, and the root of JSON data. XXXX can obtain the member data of XXX. Use brackets to get an element in a JSON array. See JsonPath Expressions

Spring Boot Service layer test

The Spring Boot Service layer is tested primarily by the Mock DAO layer, which is also managed by the Spring container, so the mock method is similar to the above and the testing process is similar, so I won’t repeat it here.

conclusion

This is the end of the introduction of Spring Boot unit testing, basically using the previous tools can write a more complete test, remember, your code must have unit test coverage requirements, so that the future refactoring, adding new business will not be painful, refuting the core-boot years!

Refer to the article

Spring Boot test method

Injecting Mockito Mocks into Spring Beans

SpringBoot Test and its annotations

JsonPath Expressions

www.journaldev.com/21876/mocki…

www.baeldung.com/java-spring…