java spring test mockmvc

java spring test 

 

@SpringBootTest
@RunWith(SpringRunner.class)
@AutoConfigureMockMvc
@Slf4j
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class TestApp {
    @Resource
    private WebApplicationContext webApplicationContext;

    @Resource 
    private MockMvc mockMvc; 

    @Before
    public void beforeMethod() {
        test_user_id = 15854;
        mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();

    }

    private Object getResultDataObject(String url, Object param, Object o) throws Exception {
        String dataStr = getResultDataString(url, param);
        AuxTool.copyProperties(o, JSONObject.parseObject(dataStr, o.getClass()));
        return o;
    }

    private List getResultDataList(String url, Object param, Object o) throws Exception {
        String dataStr = getResultDataString(url, param);
        return JSONObject.parseArray(dataStr, o.getClass());
    }

    private String getResultDataString(String url, Object param) throws Exception {
        RequestBuilder request = MockMvcRequestBuilders
                .post(url)
                .header("test_user_id", test_user_id)
                .contentType(MediaType.APPLICATION_JSON)
                .characterEncoding("utf8")
                .content(JSONObject.toJSONString(param))
                .accept(MediaType.APPLICATION_JSON);
        String res = mockMvc.perform(request)
                .andDo(MockMvcResultHandlers.print())
                .andExpect(MockMvcResultMatchers.status().isOk())
                .andExpect(MockMvcResultMatchers.jsonPath("$.code", Matchers.is(0)))
                .andReturn()
                .getResponse()
                .getContentAsString();
        JSONObject result = JSONObject.parseObject(res);
        return JSONObject.toJSONString(result.get("data"));
    }

}

 

你可能感兴趣的:(java)