SpringBoot2.x 单元测试

1.引入 dependency

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
    <exclusions>
        <exclusion>
            <groupId>org.junit.vintage</groupId>
            <artifactId>junit-vintage-engine</artifactId>
        </exclusion>
    </exclusions>
</dependency>

2.接口

@Slf4j
@RestController
@RequestMapping("demo")
public class DemoController extends BaseController {

    @GetMapping("find/{id}")
    public String findById(@PathVariable Long id) {
        log.info("按主键查询, id: {}", id);
        return "Hello World";
    }

    @PostMapping("save")
    public String save(@RequestBody DemoBo bo) {
        log.info("保存, bo: {}", bo);
        return "保存成功";
    }

    @GetMapping("findByName")
    public String findByName(@RequestParam String name) {
        log.info("findByName, bo: {}", name);
        return name;
    }

}

3.测试类,使用MockMvc测试接口

@Slf4j
@SpringBootTest
@AutoConfigureMockMvc  //自动配置 MockMvc
class DemoControllerTest1 {

    @Autowired
    private MockMvc mock;

    @Test
    void findById() throws Exception {
        MvcResult mvcResult = mock.perform(MockMvcRequestBuilders.get("/demo/find/123").characterEncoding("UTF-8"))
                .andExpect(MockMvcResultMatchers.status().isOk())
                .andExpect(MockMvcResultMatchers.jsonPath("$.code").value("S0000")) //比较json结果值
                .andReturn();
        MockHttpServletResponse response = mvcResult.getResponse();
        response.setCharacterEncoding("UTF-8");
        String content = response.getContentAsString();
        log.info("findById Result: {}", content);
    }

    @Test
    void save() throws Exception {
        MvcResult mvcResult = mock.perform(
                MockMvcRequestBuilders.post("/demo/save")
                        .contentType(MediaType.APPLICATION_JSON_VALUE)
                        .characterEncoding("UTF-8")
                        .content(JSONObject.toJSONString(new DemoVo("Hello World")))
        )
                .andExpect(MockMvcResultMatchers.status().isOk())
                .andExpect(MockMvcResultMatchers.jsonPath("$.code").value("S0000")) //比较json结果值
                .andReturn();
        MockHttpServletResponse response = mvcResult.getResponse();
        response.setCharacterEncoding("UTF-8");
        String content = response.getContentAsString();
        log.info("save Result: {}", content);
    }

    @Test
    void findByName() throws Exception {
        MvcResult mvcResult = mock.perform(
                MockMvcRequestBuilders.get("/demo/findByName")
                        .characterEncoding("UTF-8")
                        .param("name", "Test")
        )
                .andExpect(MockMvcResultMatchers.status().isOk())
                .andExpect(MockMvcResultMatchers.jsonPath("$.code").value("S0000")) //比较json结果值
                .andReturn();
        MockHttpServletResponse response = mvcResult.getResponse();
        response.setCharacterEncoding("UTF-8");
        String content = response.getContentAsString();
        log.info("findByName Result: {}", content);
    }
}

4. 输出结果

2020-04-10 13:53:23.530  INFO 4916 --- [main] c.j.system.controller.DemoController     : 按主键查询, id: 123
2020-04-10 13:53:23.552  INFO 4916 --- [main] c.j.s.controller.DemoControllerTest1     : findById Result: Hello World


2020-04-10 13:53:23.570  INFO 4916 --- [main] c.j.system.controller.DemoController     : findByName, bo: Test
2020-04-10 13:53:23.575  INFO 4916 --- [main] c.j.s.controller.DemoControllerTest1     : findByName Result: Test


2020-04-10 13:53:23.609  INFO 4916 --- [main] c.j.system.controller.DemoController     : 保存, bo: DemoBo(name=Hello World)
2020-04-10 13:53:23.611  INFO 4916 --- [main] c.j.s.controller.DemoControllerTest1     : save Result: 保存成功
原文地址:https://www.cnblogs.com/xubao/p/14780794.html