How do I mock a SessionContext injected via @Resource in Java-EE? -
i'm getting following nullpointerexception
:
caused by: java.lang.nullpointerexception @ facadebean.createregistration(facadebean.java:389)
under facadebean.java
:
private sessioncontext context public createregistrationresponse createregistration() { try { // snip } catch (dataaccessexception de){ context.setrollbackonly(); //---------line 389 throw new serviceexception("error"); } }
test class
@test(expected = serviceexception.class) public void testcreateregistrationerror() throws serviceexception { dothrow(dataaccessexception.class).when(mockregistrationperistenceimpl).create(any(registration.class)); facadebeantest.createregistration(registrationfacademock.getcreateregistrationrequest()); }
could tell me how mock below line, can ignore context.setrollbackonly();
public class facadebean { public facadebean() {} @resource private sessioncontext context }
easiest way change class use method injection instead of field injection.
in other words, in real class, change this:
@resource private sessioncontext context;
into this:
private sessioncontext context; @resource public void setsessioncontext(sessioncontext sessioncontext) { this.sessioncontext = sessioncontext; }
then, once you've done that, can inject mock using unit test:
@before public void setup() { // have other code here facadebean.setsessioncontext(mock(sessioncontext.class)); }
you may have issue jaxb if this, though; if happens, read question: sessioncontext injection using @resource annotation
if can't change code, can access field via reflection, doing this:
@before public void setup() { field sessioncontextfield = facadebean.class.getdeclaredfield("context"); sessioncontextfield.setaccessible(true); sessioncontextfield.set(beanobject, mock(sessioncontext.class)); }
Comments
Post a Comment