1

My Struts2 Action classes use the below code to successfully access the session

    ActionContext.getContext().getSession().clear();

However, when I try to use Junit to test my Action classes I get a NullPointer exception.
I have been reviewing some of the comments posted by others on StackOverflow and have been using the below code:

HttpServletRequest request;

HttpSession session;

@Before
public void setUp() throws Exception {        

    request = Mockito.mock(HttpServletRequest.class);
    request.setAttribute("beanList", beanList);
    request = Mockito.mock(HttpServletRequest.class);
    Mockito.when(request.getSession()).thenReturn(session);

    Map<String, Object> contextMap = new HashMap<String, Object>();
    contextMap.put(StrutsStatics.HTTP_REQUEST, request);
    ActionContext.setContext(new ActionContext(contextMap));
}

However, it still throws a null pointer error. The system is able to successfully find get the context, but when it tries to get the session it dies on me. I have also tries a few different ways to accomplish the same goal to no avail. Any idea what I am doing wrong?

4

2 回答 2

4

实例化或模拟你的会话怎么样?

session = mock(HttpSession.class);

打电话之前

Mockito.when(request.getSession()).thenReturn(session);

于 2013-09-03T22:36:08.280 回答
2

使用依赖注入方法并更改您的操作以实现SessionAware. 然后,Struts2 框架会将会话注入到您的操作中,如下例所示。最后,您可以通过简单地将 Map 注入到您的操作中来进行测试。

public class MyAction extends ActionSupport implements SessionAware {
  private Map<String, Object> session;

  public String execute() {
    // do actiony stuff
    return SUCCESS;
  }

  public void setSession(Map<String, Object> session) {
    this.session = session;
  }
}

仅供参考,ServletConfigInterceptor处理执行此注入,并且相同类型的注入可用于访问其他 servlet 对象,例如HttpServletRequestServletContext.

于 2013-09-04T03:01:10.907 回答