servlets - Can't get the session for Junit testing -


my struts2 action classes use below code access session

    actioncontext.getcontext().getsession().clear(); 

however, when try use junit test action classes nullpointer exception.
have been reviewing of comments posted others on stackoverflow , have been using 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, still throws null pointer error. system able find context, when tries session dies on me. have tries few different ways accomplish same goal no avail. idea doing wrong?

use dependency injection approach , change action implement sessionaware. then, struts2 framework inject session action, such in example below. finally, can test injecting map action.

public class myaction extends actionsupport implements sessionaware {   private map<string, object> session;    public string execute() {     // actiony stuff     return success;   }    public void setsession(map<string, object> session) {     this.session = session;   } } 

fyi, servletconfiginterceptor handles performing injection , same kind of injection available accessing other servlet objects, such httpservletrequest or servletcontext.


Comments

Popular posts from this blog

html - How to style widget with post count different than without post count -

How to remove text and logo OR add Overflow on Android ActionBar using AppCompat on API 8? -

javascript - storing input from prompt in array and displaying the array -