How to mock InitialContext constructor in unit testing

后端 未结 4 486
臣服心动
臣服心动 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:33

    Handmade

    As InitialContext doc says, you can provide your own factory for InitialContext objects, using java.naming.factory.initial system property. When the code runs inside application server, the system property is set by the server. In our tests, we provide our own implementation of JNDI.

    Here's my Mockito only solution: I defined a custom InitialContextFactory class, that returns a mock of InitialContext. You customize the mock as you wish, probably to return more mocks on lookup calls.

    public class PlainTest {
      @Mock InitialContextFactory ctx;
      @InjectMocks Klasa1 klasa1;
    
      public static class MyContextFactory implements InitialContextFactory
      {
        @Override
        public Context getInitialContext(Hashtable environment) throws NamingException {
          ConnectionFactory mockConnFact = mock(ConnectionFactory.class);
          InitialContext mockCtx = mock(InitialContext.class);
          when(mockCtx.lookup("jms1")).thenReturn(mockConnFact);
          return mockCtx;
        }
      }
    
      @Before
      public void setupClass() throws IOException
      {
        MockitoAnnotations.initMocks(this);
        System.setProperty("java.naming.factory.initial",
          this.getClass().getCanonicalName() + "$MyContextFactory");
      }
    

    Spring (added by edit)

    If you don't mind leveraging Spring Framework for testing purposes, here's their simple solution: SimpleNamingContextBuilder:

    SimpleNamingContextBuilder builder = new SimpleNamingContextBuilder();
    DataSource ds = new DriverManagerDataSource(...);
    builder.bind("java:comp/env/jdbc/myds", ds);
    builder.activate();
    

    It's ok to put it in @Before or @BeforeClass. After activate(), jndi data will be pulled from spring dummy.

提交回复
热议问题