springboot mockMvc单元测试

mockMvc配置


public class TestApplication {
    @Autowired
    private WebApplicationContext context;

    @Bean
    public MockMvc setup() {
        return MockMvcBuilders.webAppContextSetup(this.context).build();
    }
}

@RunWith(SpringRunner.class)
@SpringBootTest(
        webEnvironment = SpringBootTest.WebEnvironment.MOCK,
        classes = TestApplication.class)
@AutoConfigureMockMvc
public class YjbgApplyMsgReceiveControllerIntegrationTest {

    @Autowired
    private MockMvc mvc;    

        MvcResult mvcResult = mvc.perform(post("/yjbg-apply-msg-receives")
                .contentType(MediaType.APPLICATION_JSON)
                .content(asJsonString(yjbgApplyMsgReceiveDTO))
        )
                .andExpect(status().isOk())
                //contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)
                .andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON))
                .andReturn();

        String contentAsString = mvcResult.getResponse().getContentAsString();
        ResultResponse resultResponse = JSONObject.parseObject(contentAsString, ResultResponse.class);
        JSONObject jsonData = (JSONObject) resultResponse.getData();
        YjbgApplyMsgReceiveDTO createResultData = JSONObject.toJavaObject(jsonData, YjbgApplyMsgReceiveDTO.class);
        assertNotNull(createResultData);
        assertNotNull(createResultData.getId());
}        

版权声明:本文为weixin_41725792原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。