模拟无状态会话bean会产生javax.naming.NoInitialContextException



有一些类:

 @Stateless   
 public class SomeSimpleBean implements SomeSimpleLocal{
    private static SomeSimpleBean cachedInstance;
    public static SomeSimpleLocal lookup() throws NamingException {
      if (cachedInstance == null) {
        cachedInstance = (SomeSimpleLocal) new InitialContext()
            .lookup(“something”);
    }
    return cachedInstance;
 }
 ...
}

还有另一类:

public class SomeOtherClass(){
private SomeSimpleLocal getSomeSimpleBean() throws SomeException {
    try {
        return SomeSimpleLocal.lookup();
      } catch (Throwable e) {
        throw new SomeException(“…”, e);
      }
    }
private String generateResponse(String transactionId, String someParameter) throws Exception {
    SomeSimpleBean beanController = getSomeSimpleBean();
    String receivedString = controller.someMethod(transactionId,
        someParameter);
    return receivedString;
    }
    ...
public String giveMeSomeData(){
    ...
  String xxx = generateResponse(a,b);
    ...
    return someString;
   }
 }

在这种情况下可以模拟SomeSimpleBean吗?模拟SomeSimpleBean得到javax.naming.NoInitialContextException

Hashtable<Object, Object> env = new Hashtable<Object, Object>();
InitialContextFactory fact = mock(InitialContextFactory.class);
InitialContextFactoryBuilder builder = mock(InitialContextFactoryBuilder.class);
InitialContext ctx = mock(InitialContext.class);
SomeSimpleBean someSimepleBeanMock = mock(SomeSimpleBean.class);
NamingManager.setInitialContextFactoryBuilder(builder);
when(builder.createInitialContextFactory(env)).thenReturn(fact);
when(NamingManager.getInitialContext(env)).thenReturn(ctx);
when(ctx.lookup("SomeSimpleBean/local")).thenReturn(
        someSimpleBeanMock);

相关内容

  • 没有找到相关文章

最新更新