EasyMock - request.getSession为null

时间:2015-07-01 07:56:59

标签: java junit easymock

我正在测试以下方法:

public static String createSn(HttpServletRequest request, String usrnm) {
    HttpSession session = request.getSession(true);
    session.setAttribute("UserID", usrnm);

    return session.getId();
}

使用我的JUnit测试代码:

HttpServletRequest request = createNiceMock(HttpServletRequest.class);
HttpSession session = createNiceMock(HttpSession.class);
expect(request.getSession()).andReturn(session);

replay(request);
replay(session);

String username="testuser";
String snID = LogInUtils.createSn(request, username);

但是,这些行似乎产生Null Pointer Exception

HttpSession session = request.getSession(true);
session.setAttribute("UserID", usrnm);

总之request.getSession(true)似乎不适用于我的模拟请求。我哪里出错了?

感谢您的意见:)

1 个答案:

答案 0 :(得分:4)

您应该使用:

expect(request.getSession(true)).andReturn(session);

在您的示例中,您模拟了代码中未调用的方法request.getSession()