0

I am trying to Mock the InitialContext Value to my test class, but was getting the below exception.

Caused by: 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.

  1. I tried using @Mock and @Injectmocks
  2. I used the below code in my test class

    when((DataSource) ctx.lookup("Database name")).thenReturn(dataSource);
    

    but still getting the same excpetion.

The complete test method:

public void getdetails() { 

  MainclassObj mainclassObj=new MainclassObj(); 
  InitialContext ctx = Mockito.mock(InitialContext.class); 

  when((DataSource) ctx.lookup("Database name")).thenReturn(dataSource); 
  //This is the manin class where DB call is made.
  mainclassObj.getRequiredData(String value); 
  when(response.getStaus).thenReturn(200); 
}

Could anyone help me to resolve this issue?

Jens Dibbern
  • 1,434
  • 2
  • 13
  • 20
user2816424
  • 73
  • 2
  • 3
  • 9
  • Please post the full test class so we can see more background details... – mrkernelpanic Apr 11 '19 at 12:54
  • [Spring test](https://docs.spring.io/spring/docs/current/spring-framework-reference/testing.html#mock-objects-jndi) ships with a [mock JNDI environment](https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/mock/jndi/package-summary.html). Or use something like [Simple JNDI](https://github.com/h-thurow/Simple-JNDI) to provide a JNDI environment for testing. – M. Deinum Apr 11 '19 at 12:55
  • Please find the test method below. public void getdetails() { MainclassObj mainclassObj=new MainclassObj(); InitialContext ctx = Mockito.mock(InitialContext.class); when((DataSource) ctx.lookup("Database name")).thenReturn(dataSource); //This is the manin class where DB call is made. mainclassObj.getRequiredData(String value); when(response.getStaus).thenReturn(200); } – user2816424 Apr 11 '19 at 13:01
  • Did you read https://stackoverflow.com/questions/36734275/how-to-mock-initialcontext-constructor-in-unit-testing? – Jens Dibbern Apr 12 '19 at 14:31

0 Answers0