對web專案的單元測試方法
1 HttpClient模擬請求,需要開啟伺服器
/*
Map<String,String> param = new HashMap<String,String>();
param.put("businesstype", "1006");
param.put("trade_no", "123123123");
param.put("orderid", "123456");
GetMethod method = getMethod(URL, param);
client.executeMethod(method);
if(method.getStatusCode() != 200) {
fail("未正確響應");
return;
}
String response = method.getResponseBodyAsString();
System.err.println(response);
PayStatusResponse payStatus = new PayStatusResponse();
payStatus.setBusinessType(1006);
payStatus.setOrderId("");
payStatus.setResultStatus(1);
String payStatusJson = JsonUtil.toJson(payStatus);
System.err.println(payStatusJson);
assertEquals(payStatusJson,response);
*/
json和物件之間轉換用jackson框架
2 springmvc可以使用mockMvc
static imports:
MockMvcBuilders.*, MockMvcRequestBuilders.*, MockMvcResultMatchers.*
WebApplicationContext wac = ...;
MockMvc mockMvc = webAppContextSetup(wac).configureWarRootDir("src/main/webapp", false).build()
mockMvc.perform(get("/form"))
.andExpect(status().isOk())
.andExpect(content().mimeType("text/html"))
.andExpect(forwardedUrl("/WEB-INF/layouts/main.jsp"));