如何模拟在Java-EE中通过@Resource注入的SessionContext?

时间:2015-09-21 13:01:09

标签: java java-ee junit mockito

我收到了以下NullPointerException

Caused by: java.lang.NullPointerException at FacadeBean.createRegistration(FacadeBean.java:389)

FacadeBean.java下:

private SessionContext context

public CreateRegistrationResponse createRegistration() {
  try {
    // snip
  } catch (DataAccessException de){
    context.setRollbackOnly(); //---------line 389
    throw new ServiceException("Error");        
  }
}

测试课

@Test(expected = ServiceException.class)
public void testCreateRegistrationError() throws ServiceException {
    doThrow(DataAccessException.class).when(mockRegistrationPeristenceImpl).create(any(Registration.class));
    facadeBeanTest.createRegistration(RegistrationFacadeMock.getCreateRegistrationRequest());
}

有人可以告诉我如何模拟以下行,以便我可以忽略此context.setRollbackOnly();

public class FacadeBean {
  public FacadeBean() {}
  @Resource
  private SessionContext context
}

1 个答案:

答案 0 :(得分:1)

最简单的方法是将类更改为使用method injection而不是字段注入

换句话说,在你真正的课堂上,改变一下:

@Resource
private SessionContext context;

进入这个:

private SessionContext context;

@Resource
public void setSessionContext(SessionContext sessionContext) {
 this.sessionContext = sessionContext;
}

然后,一旦你完成了这个,你可以使用你的单元测试注入模拟:

@Before
public void setUp() {
  // You probably have other code here already
  facadeBean.setSessionContext(mock(SessionContext.class));
}

如果你这样做,你可能会遇到JAXB的问题;如果发生这种情况,请阅读以下问题:SessionContext Injection using @Resource annotation

如果您无法更改代码,您可以通过反射访问该字段,执行以下操作:

@Before
public void setUp() {
  Field sessionContextField = FacadeBean.class.getDeclaredField("context");
  sessionContextField.setAccessible(true);
  sessionContextField.set(beanObject, mock(SessionContext.class));
}