Spring boot 2.x Test

107 阅读1分钟

spring boot 2.x junit5 使用MockMvc测试Controller

@Slf4j
@SpringBootTest
class XhImportRecordControllerTest {
	// 用于生成 MockMvc 实例
    @Autowired
    private WebApplicationContext webApplicationContext;
    //mvc 环境对象
    private MockMvc mockMvc;
	// 在所有方法执行钱初始化 MockMvc
    @BeforeEach
    public void init() {
        mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
    }


    @Test
    void getXhCreateTaskRecord() throws Exception {
        final XhCreateTaskRecordVo vo = new XhCreateTaskRecordVo();
        vo.setAuthLevel(3);
        vo.setUserId(1);
        vo.setOrgCode("1.346.");
        vo.setPageSize(10);
        vo.setPageNum(1);
//        mvc = MockMvcBuilders.webAppContextSetup(wac).build();
        final String json = JSON.toJSONString(vo);
		// 生气请求 request
        final MockHttpServletRequestBuilder request = MockMvcRequestBuilders.post("/getXhCreateTaskRecord")
                .accept(MediaType.APPLICATION_JSON)
                .contentType(MediaType.APPLICATION_JSON_VALUE)
                //传json参数
                .content(json);
        final String contentAsString = mockMvc.perform(request)
		  .andExpect(MockMvcResultMatchers.status().isOk())
		.andReturn().getResponse().getContentAsString();
        log.info(contentAsString);
    }
}