1. 程式人生 > >MockMVC測試Controller中常見的請求方式

MockMVC測試Controller中常見的請求方式

TestController.java
@RestController
public class TestController {

    private final String PATH = "D:\\Develop\\JavaEE\\laboratory";

    @GetMapping(value = "/mockTestA")
    public String mockTestA(@RequestParam("a") String a,
                            @RequestParam("b") String b) {
        return a + b;
    }

    @PostMapping(value = "/mockTestB")
    public String mockTestB(@RequestParam(value = "a", defaultValue = "1") String a,
                            @RequestParam(value = "b", defaultValue = "2") String b) {
        return a + b;
    }

    @PostMapping(value = "/mockTestC")
    public User mockTestC(@RequestBody User user) {
        return user;
    }

    @PostMapping(value = "/file")
    public String file(MultipartFile file) throws IOException {
        File localFile = new File(PATH, "test.txt");

        file.transferTo(localFile);

        return file.getName();
    }
    
}
User.java
@Setter
@Getter
@AllArgsConstructor
@NoArgsConstructor
public class User {

    private String id;

    private String username;
}
TestControllerTest
@RunWith(SpringRunner.class)
@SpringBootTest
public class TestControllerTest {

    @Autowired
    private WebApplicationContext wac;

    private MockMvc mockMvc;

    @Before
    public void setUp() {
        mockMvc = MockMvcBuilders.webAppContextSetup(wac).build();
    }

    @Test
    public void mockTestA() throws Exception {
        String result = mockMvc.perform(get("/mockTestA")
                .param("a", "1")        // 新增引數
                .param("b", "2")
                .contentType(MediaType.APPLICATION_JSON_UTF8))      // 設定資料格式
                .andDo(print())     // 列印輸出發出請求的詳細資訊
                .andExpect(status().isOk())     // 對返回值進行斷言
                .andReturn().getResponse().getContentAsString();        // 獲取方法的返回值

        Assert.assertEquals("12", result);
    }

    @Test
    public void mockTestB() throws Exception {
        String result = mockMvc.perform(post("/mockTestB")
                .param("a", "10")
                .param("b", "11")
                .contentType(MediaType.APPLICATION_JSON_UTF8))
                .andDo(print())
                .andExpect(status().isOk())
                .andReturn().getResponse().getContentAsString();

        Assert.assertEquals("1011", result);
    }

    @Test
    public void mockTestC() throws Exception {
        Map<String, String> map = new HashMap<>();
        map.put("id", "123");
        map.put("username", "tom");
        String content = JSONObject.toJSONString(map);

        String result = mockMvc.perform(post("/mockTestC")
                .contentType(MediaType.APPLICATION_JSON_UTF8)
                .content(content))
                .andDo(print())
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.id").value("123"))
                .andReturn().getResponse().getContentAsString();

        Assert.assertNotNull(result);
    }

    @Test
    public void file() throws Exception {
        String result = mockMvc.perform(fileUpload("/file")
                .file(new MockMultipartFile("file", "test.txt",
                        "multipart/form-data",
                        "hello upload".getBytes("UTF-8"))))
                .andDo(print())
                .andExpect(status().isOk())
                .andReturn().getResponse().getContentAsString();
        Assert.assertEquals("file", result);
    }
}