采用Struts2+Spring+Hibernate,控制层一段被测试的代码如下:
/**
* 删除费用
* @return
*/
public String doDeleteFeeRecord() {
String message = "";
PrintWriter pw = null;
String feeRecordId = request.getParameter("feeRecordId");
UserInfoVO userInfoVO = (UserInfoVO) session.get("userInfo");
try {
message = "{success:true}";
feeRecordService.deleteFeeRecord(feeRecordId );
logService.insertLog(userInfoVO.getLoginName(), "删除费用成功", request.getRemoteAddr(), 1);
} catch (FinanceException e) {
message = "{success:false}";
try {
logService.insertLog(userInfoVO.getLoginName(), "删除费用失败",request.getRemoteAddr(), 0);
} catch (FinanceException ex) {
request.setAttribute("errorText", ex.getMessage());
return "showWebError";
}
}
response.setContentType("text/json;charset=GBK");
try {
pw = response.getWriter();
pw.write(message);
pw.close();
} catch (IOException e) {
request.setAttribute("errorText", e.getMessage());
return "showWebError";
}
return null;
}
采用EasyMock对上面的代码进行测试,这个过程大致可以分为以下几个步骤:
测试类如下:
public class TestFeeRecordAction {
private FeeRecordAction feeRecordAction = null;
@BeforeClass
public static void setUpBeforeClass() throws Exception {
}
@AfterClass
public static void tearDownAfterClass() throws Exception {
}
@Before
public void setUp() throws Exception {
ApplicationContext context = new FileSystemXmlApplicationContext("E:/software/Java/workstation/financeWeb/WebRoot/WEB- INF/FinanceContext.xml");
feeRecordAction = (FeeRecordAction) context.getBean("feeRecordAction");
}
@After
public void tearDown() throws Exception {
feeRecordAction = null;
}
@Test
public void testDoDeleteFeeRecord() throws IOException {
/**
* 生成Mock对象
*/
HttpServletRequest request = EasyMock.createMock(HttpServletRequest.class);
feeRecordAction.setServletRequest(request);
HttpServletResponse response = EasyMock.createMock(HttpServletResponse.class);
feeRecordAction.setServletResponse(response);
Map<String, UserInfoVO> map = new HashMap<String, UserInfoVO>();
UserInfoVO userInfoVO = new UserInfoVO();
userInfoVO.setLoginName("admin");
map.put("userInfo", userInfoVO);
feeRecordAction.setSession(map);
/**
* 设定 Mock 对象的预期行为和输出
*/
EasyMock.expect(request.getParameter("feeRecordId")).andReturn("1").once();
EasyMock.expect(request.getRemoteAddr()).andReturn("192.168.1.103").once();
PrintWriter pw = new PrintWriter(System.out, true);
EasyMock.expect(response.getWriter()).andReturn(pw).once();
/**
* 将 Mock 对象切换到 Replay 状态
*/
EasyMock.replay(request);
EasyMock.replay(response);
/**
* 调用 Mock 对象方法进行单元测试
*/
feeRecordAction.doDeleteFeeRecord();
pw.flush();
/**
* 对 Mock 对象的行为进行验证
*/
EasyMock.verify(request);
EasyMock.verify(response);
}
}
运行测试用例时,需要将方法doDeleteFeeRecord中的response.setContentType("text/json;charset=GBK");注释掉