Mocking JNDI calls for Unit Test

Mocking JNDI calls for Unit Test


Sometimes, on the rarer cases the properties data that usually drive a server based application resides in the JNDI calls instead of something.properties file. In such scenario, mocking the JNDI calls using Mockito or Powermock are inherently difficult. Luckily the Spring Framework provides a way to "mock" the context by using SimpleNamngContextBuilder.

By declaring the JNDI calls in a static method (because the Builder needs to be activated before any other autowiring could take place):

@BeforeClass    
public static void oneTimeSetUp() throws Exception {
        SimpleNamingContextBuilder builder = new SimpleNamingContextBuilder();        
        builder.bind("sampleJndiKey", "sampleJndiiValue");
        builder.activate();    
}


Here's a full sample:

@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration
public class TestIT {

    @Autowired    
    Environment env;

    @Configuration    
    static class ContextConfiguration {

    }

    @BeforeClass    
    public static void oneTimeSetUp() throws Exception {
        SimpleNamingContextBuilder builder = new SimpleNamingContextBuilder();        
        builder.bind("sampleJndiKey", "sampleJndiValue");
        builder.activate();    
    }

    @Test
    public void testJNDI() throws Exception {
        assertEquals("sampleJndiValue", env.getProperty("sampleJndiKey"));    
    }

}

Happy mocking!

Comments

Popular posts from this blog

Spring Boot 2: Parallelism with Spring WebFlux

Spring Boot Reactive API Part 2