0

I have this JUnit test in which I want to mock the datasource which uses JNDI:

@SpringBootTest(classes = Application.class)
@RunWith(SpringJUnit4ClassRunner.class)
public class BinCountryCheckFilterImplTest    {

    @MockBean
    private static DataSource dataSource;

    @BeforeClass
    public static void setupJndi() throws Exception {
        SimpleNamingContextBuilder.emptyActivatedContextBuilder();
        Context context = new InitialContext();
        context.bind("java:global/production", dataSource);
    }

    @BeforeEach
    public void beforeEachTest() throws IOException {
        ......
    }

    @Test
    public void testBinCountryCheckFilterImpl() throws JsonProcessingException, JAXBException {
         ...
    }    
}

When I run the ode I get error:

Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [javax.sql.DataSource]: Factory method 'dataSource' threw exception; nested exception is org.springframework.jdbc.datasource.lookup.DataSourceLookupFailureException: Failed to look up JNDI DataSource with name 'java:global/production'; nested exception is javax.naming.NoInitialContextException: Need to specify class name in environment or system property, or in an application resource file: java.naming.factory.initial
 Failed to look up JNDI DataSource with name 'java:global/production'; nested exception is javax.naming.NoInitialContextException: Need to specify class name in environment or system property, or in an application resource file: java.naming.factory.initial

Do you know how I can fix this issue?

Peter Penzov
  • 1,126
  • 134
  • 430
  • 808
  • You might want to read [this](https://stackoverflow.com/questions/4099095/what-does-javacomp-env-do). Does it work if you write just `global/production` (without the `java:` prefix)? Typically in an EJB Container, you'd define JDBC data sources as `jdbc/` and then refer to them by that same string. Outside of a container, you may have to use `java:comp/env/jdbc/` in your lookup. – Alexander Wessel Oct 31 '19 at 23:44
  • The error message you get seems to imply that you haven't got an active JNDI provider. Do you need to call `SimpleNamingContextBuilder.activate()` after the bind? Also note that the SimpleNamingContextBuilder is deprecated. You should use [Simple-JNDI](https://github.com/h-thurow/Simple-JNDI) instead. I am happy with it. – Alexander Wessel Nov 01 '19 at 00:03

0 Answers0