Spring mvc controller测试用例

#封装请求工具类


import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;

import java.util.Map;

import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

/**
 * Created by liuzz on 2017/7/13.
 */
public class RequestUtils {

    public static void post(MockMvc mockMvc, String url, String content) throws Exception {
        String result = mockMvc.perform(
                MockMvcRequestBuilders.post(url)
                        .contentType(MediaType.APPLICATION_JSON)
                        .accept(MediaType.APPLICATION_JSON)
                        .content(content)
        )
                .andDo(print())
                .andExpect(status().isOk())
                .andReturn().getResponse().getContentAsString();

        Gson gson = new GsonBuilder().setPrettyPrinting().create();
        Map map = gson.fromJson(result, Map.class);
        System.out.println(gson.toJson(map));
    }
}

 

#测试用例



/**
 * Created by liuzz on 2017/7/10.
 */
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = ServiceFacadeApplication.class)
public class TestControllerTest {

    @Autowired
    private TestController controller;

    private MockMvc mockMvc;

    @Before
    public void setUp() throws Exception {
        mockMvc = MockMvcBuilders.standaloneSetup(controller).build();
    }

    @Test
    public void tree() throws Exception {
        RequestUtils.post(mockMvc, "/test/test", "{\n" +
                "    \"category\": 0\n" +
                "}");
    }

}

 

没什么技术含量,但是方便使用