java - How to get an ActionContext from Struts 2 during acceptance tests? -
i writing acceptance tests (testing behavior) using cucumber-jvm, on application struts 2 , tomcat servlet container. @ point in code, need fetch user struts 2 httpsession
, created httpservletrequest
.
since i'm doing tests , not running tomcat, don't have active session , nullpointerexception
.
here's code need call:
public final static getactiveuser() { return (user) getsession().getattribute("active_user"); }
and getsession method:
public final static httpsession getsession() { final httpservletrequest request (httpservletrequest)actioncontext. getcontext().get(strutsstatics.http_request); return request.getsession(); }
in honesty, don't know struts 2, need little help. i've been looking @ cucumber-jvm embedded tomcat example, i'm struggling understand.
i've been looking @ struts 2 junit tutorial. sadly, doesn't cover strutstestcase
features , it's simplest of use cases (all considered, pretty useless tutorial).
so, how can run acceptance test if user using application?
update:
thanks steven benitez answer!
i had 2 things:
- mock httpservletrequest, suggested,
- mock httpsession attribute wanted.
here's code i've added cucumber-jvm tests:
public class stepdefs { user user; httpservletrequest request; httpsession session; @before public void preparetests() { // create user // mock session using mockito session = mockito.mock(httpsession.class); mockito.when(session.getattribute("active_user").thenreturn(user); // mock httpservletrequest request = mockito.mock(httpservletrequest); mockito.when(request.getsession()).thenreturn(session); // set 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); }
}
an actioncontext
per-request object represents context in action executes. static methods getcontext()
, setcontext(actioncontext context)
backed threadlocal
. in case, can call before test:
map<string, object> contextmap = new hashmap<string, object>(); contextmap.put(strutsstatics.http_request, yourmockhttpservletrequest); actioncontext.setcontext(new actioncontext(contextmap));
and clean after with:
actioncontext.setcontext(null);
this example provide method testing needs. if need additional entries in map based on code didn't provide here, add them accordingly.
hope helps.
Comments
Post a Comment