如何测试使用 RequestDispatcher 重定向我的 void 方法?
到目前为止我做了什么。
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。
最佳答案
您需要创建一个模拟的 RequestDispatcher
期望被转发,并从您的模拟中返回它:
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);
关于java - 测试一个向前重定向的无效方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50106350/