How to mock InitialContext constructor in unit testing

后端 未结 4 482
臣服心动
臣服心动 2020-12-06 03:16

when I try to mock following method(Method is using remote EJB call for business logic) for the Junit test, it gives javax.naming.NoInitialContextException

p         


        
4条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-06 03:30

    You can refactor your code and extract the initialization of the context in new method.

    private void someMethod(int id1, int id2, HashMap map){
        ......some code........
    
        Context ctx = getInitialContext();
        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.......}
    

    Your test code will be something like this:

    Context mockContext = mock(Context.class);
    doReturn(mockContext).when(yourclass).getInitalContext(); 
    ...... some code....
    

提交回复
热议问题