1. 程式人生 > >Controller 層編寫測試類

Controller 層編寫測試類

前後端分離以後,Controller 部分的程式碼當然也要進行測試,但是往常我們的測試類無法傳送http請求,這時就需要用到 MockMvc,

一個簡單的例子:

測試類:

@RunWith(SpringRunner.class)
@SpringBootTest
public class ControllerTest {
    protected MockMvc mockMvc;
    //整合Web環境,將會從該上下文獲取相應的控制器並得到相應的MockMvc;
    @Autowired
    protected WebApplicationContext wac;

    @Before()
    public void setup() {
        mockMvc = MockMvcBuilders.webAppContextSetup(wac).build();  //構造MockMvc物件
    }
    //單位資料量統計服務
    @Test
    public void goUnitDataStatSvcTest() throws Exception {
        Map<String, Object> map = new HashMap<>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date startDate = sdf.parse("2018-11-20");
        Date endDate = sdf.parse("2018-11-23");
        map.put("startDate", "2018-11-20");
        map.put("endDate", sdf.format(endDate));
        map.put("instid", "2000");
        map.put("dateType", "other");
        log.info("總天數:"+UsedUtil.daysBetween(startDate, endDate));
        String content = JSONObject.toJSONString(map);
        String result = mockMvc.perform(post("/statistic/goUnitDataStatSvc")
                .contentType(MediaType.APPLICATION_JSON_UTF8)   // 請求中的媒體型別資訊—json資料格式
                .content(content))  // RequestBody資訊
                .andDo(print()) // 打印出請求和相應的內容
                .andExpect(status().isOk()) // 返回的狀態是200
                .andReturn().getResponse().getContentAsString();    // 返回MvcResult並且轉為字串
        Assert.assertNotNull(result);
    }
}

 

控制層 Controller.java
@Controller
@RequestMapping("/statistic")
public class StatisticInfoController {
    @RequestMapping(value = "/goUnitDataStatSvc")
    @ResponseBody
    public ResponseMsg<Object[]> goUnitDataStatSvc(HttpServletRequest request, @RequestBody Map<String,Object> param) throws ParseException {
        // 獲得引數
        String instid = userPlugins.getUser(request).getBackup1();
        Date startDate = startDateTransfer(param);
        Date endDate = endDateTransfer(param);
        // 是否選擇了快捷選項,目前只有選擇“全年-(month)”才有意義
        String dateType = String.valueOf(param.get("dateType")==null?"":param.get("dateType"));
        if(startDate == null || endDate == null || "".equals(instid)|| "".equals(dateType)){
            return new ResponseMsg<>();
        }
        // TODO 呼叫後臺服務
        Object[] obj = statisticInfoService.unitDataStatSvc(startDate, endDate, instid, dateType);
        return ResponsePlugins.ok(obj);
    }
}

方法解析:

  • perform執行一個 RequestBuilder 請求,會自動執行SpringMVC的流程並對映到相應的控制器執行處理;
  • get:聲明發送一個get請求的方法。MockHttpServletRequestBuilder get(String urlTemplate, Object... urlVariables):根據uri模板和uri變數值得到一個GET請求方式的。另外提供了其他的請求的方法,如:post、put、delete等。
  • param:新增request的引數,如上面傳送請求的時候帶上了了pcode = root的引數。假如使用需要傳送json資料格式
    的時將不能使用這種方式,可見後面被@ResponseBody註解引數的解決方法
  • andExpect:新增ResultMatcher驗證規則,驗證控制器執行完成結果是否正確(對返回的資料進行的判斷);
  • andDo:新增ResultHandler結果處理器,比如除錯時列印結果到控制檯(對返回的資料進行的判斷);
  • andReturn:最後返回相應的MvcResult;然後進行自定義驗證/進行下一步的非同步處理(對返回的資料進行的判斷);

 

 友情提示:如果自己的測試類怎麼也跑不通,請貼上如上程式碼,稍加改動,跑起來在修改自己的!