测试重定向向前的void方法 [英] Test a void method that redirect foward
本文介绍了测试重定向向前的void方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何测试使用RequestDispatcher重定向我的void方法?
How can I test a void method that redirects me with RequestDispatcher?
我到目前为止所做的.
public void testAuthAction_userNull() {
HttpServletRequest requestMock = createMock(HttpServletRequest.class);
HttpServletResponse responseMock = createMock(HttpServletResponse.class);
expect(requestMock.getSession().getAttribute("user")).andReturn(null);
replay(requestMock);
AuthAction action = new AuthAction();
RequestDispatcher rd = requestMock.getRequestDispatcher("/User/login.jsp");
}
我要测试的方法是
public void execute(HttpServletRequest request, HttpServletResponse response) {
User user = (User) request.getSession().getAttribute("User");
try {
if(user == null) {
RequestDispatcher rd = request.getRequestDispatcher("/User/login.jsp");
if(rd != null)
rd.foward(request, response);
} else {/* */}
}
catch(Exception e){/* */}
}
我正在使用JUnit和EasyMock.
I'm using JUnit and EasyMock.
推荐答案
您需要创建一个预期将被转发的RequestDispatcher
的模拟,并从该模拟中将其返回:
You need to create a mock of RequestDispatcher
expecting to be forwarded, and return it from your mock:
RequestDispatcher dispatcherMock = createMock(RequestDispatcher.class);
expect(requestMock.getRequestDispatcher("/User/login.jsp"))
.andReturn(dispatcherMock);
// Expect to be forwarded.
dispatcherMock.forward(requestMock, responseMock);
EasyMock.expectLastCall().once();
replay(dispatcherMock);
replay(requestMock);
// Run your test on whatever instance has `execute`:
someInstance.execute(requestMock, responseMock);
这篇关于测试重定向向前的void方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文