如何在JavaEE中模拟通过@Resource注入的SessionContext?

如何在JavaEE中模拟通过@Resource注入的SessionContext?,java,jakarta-ee,junit,mockito,Java,Jakarta Ee,Junit,Mockito,我得到以下NullPointerException: Caused by: java.lang.NullPointerException at FacadeBean.createRegistration(FacadeBean.java:389) 在FacadeBean.java下: private SessionContext context public CreateRegistrationResponse createRegistration() { try { // sni

我得到以下
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()


最简单的方法是更改要使用的类,而不是字段注入

换言之,在真实的课堂上,改变这一点:

@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产生问题;如果出现这种情况,请阅读以下问题:


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

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

我尝试了抑制和模拟,不起作用,抑制(field(FacadeBean.class,“context”);现在我没有范围更改现有代码,只编写JUnit/mockito而不修改现有代码。请建议我是否可以抑制该字段?@Durron597,根据示例,beanObject代表什么?
@Before
public void setUp() {
  Field sessionContextField = FacadeBean.class.getDeclaredField("context");
  sessionContextField.setAccessible(true);
  sessionContextField.set(beanObject, mock(SessionContext.class));
}