gpt4 book ai didi

java - 模拟无状态 session bean 会给出 javax.naming.NoInitialContextException

转载 作者:行者123 更新时间:2023-12-01 11:55:18 25 4
gpt4 key购买 nike

有一些类:

 @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);

关于java - 模拟无状态 session bean 会给出 javax.naming.NoInitialContextException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28500460/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com