如何在单元测试中模拟初始上下文构造函数
当我尝试模拟以下方法(方法使用远程EJB调用业务逻辑)进行Junit测试时,它给出了javax.nameing.NoInitialContextException
private void someMethod(int id1, int id2, HashMap map){
......some code........
Context ctx = new InitialContext();
Object ref = ctx.lookup("com.java.ejbs.MyEJB");
EJBHome ejbHome = (EJBHome)PortableRemoteObject.narrow(ref, EJBHome.class);
EJBBean ejbBean = (EJBBean)PortableRemoteObject.narrow(ejbHome.create(), EJBBean.class);
ejbBean.someMethod(id1,name);
.......some code.......}
我对上述方法的单元测试
@Test
public void testsomeMethod() throws Exception {
.......setting initial code...
//Mock context and JNDI
InitialContext cntxMock = PowerMock.createMock(InitialContext.class);
PowerMock.expectNew(InitialContext.class).andReturn(cntxMock);
expect(cntxMock.lookup("com.java.ejbs.MyEJB")).andReturn(refMock);
..........some code..........
PowerMock.replayAll();
Whitebox.invokeMethod(ObjectOfsomeMethodClass, "someMethod", id1, id2, map);
}
当 Whitebox.invokeMethod(ObjectOfsomeMethodClass, “someMethod”, id1, id2, map) 方法调用时,它会给出以下异常。
javax.naming.NoInitialContextException: Need to specify class name in environment or system property, or as an applet parameter, or in an application resource file: java.naming.factory.initial
at javax.naming.spi.NamingManager.getInitialContext(NamingManager.java:645)
at javax.naming.InitialContext.getDefaultInitCtx(InitialContext.java:288)
at javax.naming.InitialContext.getURLOrDefaultInitCtx(InitialContext.java:325)
at javax.naming.InitialContext.lookup(InitialContext.java:392)
我相信,尽管我们在测试方法中模拟了 Context,但在调用 Whitebox.invokeMethod(ObjectOfsomeMethodClass,“someMethod”, id1, id2, map) 方法时,它不会使用 mock 对象,而不是尝试在原始方法(someMethod)中调用 Context ctx = new InitialContext(); 方法。