How to get ActionContext from Struts 2 during acceptance testing?

I am writing acceptance tests (behavior testing) using cucumber-jvm, in an application with Struts 2 and Tomcat as my servlet container. At some point in my code, I need to extract the user from the Struts 2 HttpSession created using the HttpServletRequest .

Since I am running tests and not starting Tomcat, I do not have an active session and I get a NullPointerException .

Here is the code I need to call:

 public final static getActiveUser() { return (User) getSession().getAttribute("ACTIVE_USER"); } 

And the getSession method:

 public final static HttpSession getSession() { final HttpServletRequest request (HttpServletRequest)ActionContext. getContext().get(StrutsStatics.HTTP_REQUEST); return request.getSession(); } 

Honestly, I'm not very good at Struts 2, so I need a little help. I looked at this cucumber-jvm with built-in tomcat , but I'm trying to figure it out.

I also reviewed this Struts 2 Junit Tutorial . Unfortunately, it doesn’t cover all the functions of StrutsTestCase very well, and this is the easiest use case (all reviewed, quite useless tutorial).

So, how can I run my acceptance test, as if the user was using the application?


UPDATE:

Thanks Steven Benitez for the answer!

I had to do two things:

  • Drop the HttpServletRequest as suggested,
  • Check HttpSession to get the required attribute.

here is the code i added to my cucumber-jvm tests:

 public class StepDefs { User user; HttpServletRequest request; HttpSession session; @Before public void prepareTests() { // create a user // mock the session using mockito session = Mockito.mock(HttpSession.class); Mockito.when(session.getAttribute("ACTIVE_USER").thenReturn(user); // mock the HttpServletRequest request = Mockito.mock(HttpServletRequest); Mockito.when(request.getSession()).thenReturn(session); // set the context Map<String, Object> contextMap = new HashMap<String, Object>(); contextMap.put(StrutsStatics.HTTP_REQUEST, request); ActionContext.setContext(new ActionContext(contextMap)); } @After public void destroyTests() { user = null; request = null; session = null; ActionContext.setContext(null); } 

}

+4
source share
1 answer

An ActionContext is an object for a request that represents the context in which the action is performed. The static methods getContext() and setContext(ActionContext context) supported by ThreadLocal . In this case, you can call this before the test:

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

And then clean it after:

 ActionContext.setContext(null); 

In this example, only the method you need will be provided. If you need additional entries on the map based on a code that you did not specify here, simply add them accordingly.

Hope this helps.

+2
source

Source: https://habr.com/ru/post/1492087/


All Articles