So verspotten Sie den InitialContext-Konstruktor beim Unit-Testen
wenn ich versuche, die folgende Methode (Methode verwendet Remote-EJB-Aufruf für Geschäftslogik) für den Junit-Test zu verspotten, wird javax.naming.NoInitialContextException @ ausgegebe
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.......}
Mein Komponententest für obige Methode
@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);
}
wenn die Whitebox.invokeMethod (ObjectOfsomeMethodClass, "someMethod", id1, id2, map)ie @ -Methode ruft die folgende Ausnahme auf.
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)
Ich glaube, obwohl wir das @ verspottKontex In der Testmethode wird das Mock-Objekt beim Aufrufen von @ nicht verwende Whitebox.invokeMethod (ObjectOfsomeMethodClass, "someMethod", id1, id2, map) -Methode, stattdessen wird versucht, das @ aufzurufContext ctx = new InitialContext (); Methode in der ursprünglichen Methode (someMethod).