Junit Testing JNDI InitialContext outside the application server

how to mock jndi lookup using mockito
jndi example mkyong
junit mock jndi datasource
junit mock new initialcontext
how to bind lookup datasource via jndi without container
javax naming noinitialcontextexception junit
Context context = new InitialContext();
dataSource = (DataSource) context.lookup("java:comp/env/jdbc/multiDS");
connection = dataSource.getConnection();

Please help me to mock the above code.

Hi Tom Anderson

I tried the below code

 public static void setUpClass() throws Exception {
        // rcarver - setup the jndi context and the datasource
        try {
            // Create initial context
            Context ic = new InitialContext();

            // Construct DataSource
            OracleConnectionPoolDataSource ds = new OracleConnectionPoolDataSource();
        } catch (NamingException ex) {

But its giving error as:

com.hp.corona.common.exception.CacheException: org.apache.naming.NamingContext cannot be cast to javax.sql.DataSource

Please help me to test the code i just want connection from JNDI datasource

The orthodox thing to do here would be to change you code so that the Context is injected into it (by a dependency injection framework, or manually). Then, you simply pass in a mock in your unit test.

If you can't do this, and your code must create the IntialContext itself, then you will need to set up a fake JNDI implementation into which you can inject mocks. If you search the web for in-memory JNDI implementation or mock JNDI implementation, you will find various options, or you could write one yourself. Basically, you will need an implementation of InitialContextFactory which simply returns a suitable mock, which you then select by setting the java.naming.factory.initial system property.

I had a crack at writing the necessary classes. Here you go:

public class MockInitialContextFactory implements InitialContextFactory {

    private static final ThreadLocal<Context> currentContext = new ThreadLocal<Context>();

    public Context getInitialContext(Hashtable<?, ?> environment) throws NamingException {
        return currentContext.get();

    public static void setCurrentContext(Context context) {

    public static void clearCurrentContext() {


public class MockInitialContextRule implements TestRule {

    private final Context context;

    public MockInitialContextRule(Context context) {
        this.context = context;

    public Statement apply(final Statement base, Description description) {
        return new Statement() {
            public void evaluate() throws Throwable {
                System.setProperty(Context.INITIAL_CONTEXT_FACTORY, MockInitialContextFactory.class.getName());
                try {
                } finally {

Use as follows:

public class FooTest {

    private final Context context = mock(Context.class);

    public MockInitialContextRule mockInitialContextRule = new MockInitialContextRule(context);

    public void testName() throws Exception {
        // set up stubbings on the context mock
        // invoke the code under test

How to bind / lookup DataSource via JNDI without container, Connection instance or creating persistence.xml for unit testing. database to java:comp/env/jdbc/database , then lookup it via InitialContext and EntityManagerFactory . server platform: org.eclipse.persistence.platform.server. User: APP Database: Apache Derby Version: - (1704137) Driver:  Junit Testing JNDI InitialContext outside the application server (2) The orthodox thing to do here would be to change you code so that the Context is injected into it (by a dependency injection framework, or manually). Then, you simply pass in a mock in your unit test.

You can use the Spring implementation, it works like this:

import org.springframework.mock.jndi.SimpleNamingContextBuilder;


SimpleNamingContextBuilder builder = new SimpleNamingContextBuilder();
builder.bind("jdbc/myDataSource", myDS);

Mockito for jndi lookups?, stub(initialContext.lookup("java:comp/env/service/WorkspaceService")) Anyway, I would want to do jndi lookup test out of the container and I am looking at MockEJB try again by starting the application server (Websphere 6.1) just for the Junit Testing JNDI InitialContext outside the application server. it really depends on your app server . any ways take a look at this JUnit test for System

This is easily done with Simple-JNDI. Create a property file "jdbc/multiDS.properties" in your working directory to configure your datasource with these properties:


Then instantiate the context with

final Hashtable<String, String> env = new Hashtable<String, String>();
env.put("org.osjava.sj.root", "working_dir");
env.put("org.osjava.sj.jndi.shared", "true");
env.put("java.naming.factory.initial", "org.osjava.sj.SimpleContextFactory");
env.put("org.osjava.sj.delimiter", "/");
env.put("org.osjava.sj.space", "java:comp/env")
Context ctx = new InitialContext(env);

After that you can call

dataSource = (DataSource) context.lookup("java:comp/env/jdbc/multiDS");

Find more info about Simple-JNDI here https://github.com/h-thurow/Simple-JNDI

Tomcat DataSource JNDI Example in Java, 1.1 Tomcat DataSource JNDI Configuration Example – server.xml your application needs to be deployed in different testing environments such as QA, IT​, stmt = null; ResultSet rs = null; try{ ctx = new InitialContext(); DataSource ds Thus, I cannot unit-test my DB-code outside a running Tomcat, if the connection is to be  The application is using JBoss application server, so the hibernate.cfg.xml has data source and transaction lookup class configuration specific to JBoss. Since JUnit test cases are run outside the container, it had to be replaced with hibernate's default transaction and Database Connection pool configurations.

org.springframework.mock.jndi.SimpleNamingContextBuilder java , SimpleNamingContextBuilder (Showing top 20 results out of 315). Common ways to obtain Junit Testing JNDI InitialContext outside the application server. It can process Tomcat’s configuration files and creates the same JNDI environment as Tomcat does, but without starting a server. So you can run classes with dependencies on Tomcat’s JNDI environment in e. g. JUnit tests.

DataSource with SQL auth coming out of JNDI can't connect to , SQL Server version Microsoft SQL Server 2014 (SP2-GDR) ParentRunner$3.​run(ParentRunner.java:290) at org.junit.runners. lib/catalina.jar and bin/tomcat-​juli.jar // Create initial context System. (My impression is that is how it's done generally in a J2EE application server, and my test was an attempt  4 Answers 4. 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.

Chapter 11. Testing Enterprise JavaBeans, Testing session bean methods without the EJB container; Testing legacy session bean beans and JMS components; Verifying components deployed to a JNDI directory; that you are executing tests on the client side—that is, outside the application server—by InitialContext; import junit.cookbook.coffee.model.ejb. Tomcat DataSource JNDI Configuration Example – server.xml. Add below code in the tomcat server.xml file. The code should be added in the GlobalNamingResources element. Also make sure that database driver is present in the tomcat lib directory, so in this case mysql jdbc jar have to be present in the tomcat lib.

  • it really depends on your app server . any ways take a look at this codeproject.com/Articles/25741/…
  • Hi Mr Anderson.. i Just edited the testcode please give me suggestion
  • Your code isn't right. Compare it to Randy Carver's original code: blogs.oracle.com/randystuph/entry/… . You are doing a createSubcontext when you should be doing a bind. The exception message is hinting at that - you have created a NamingContext where you should have created a DataSource.
  • Hi Mr Anderson i dont know about JNDI .. so not getting what you suggesting me please help me to correct the code
  • You should do two things. Firstly, learn the basics of JNDI, perhaps by reading the JNDI trail of the Java tutorial. How can you hope to do this work without understanding JNDI? Secondly, as i said, compare your code with the original version of you have copied. There is a difference which you have added which is the cause of the problem.
  • Hi Mr Anderson i corrected the testcode by comparing ...its working Thanks a lot.
  • If you're using Tomcat as your container and doing all this to try and test some code you normally run in Tomcat, check out TomcatJNDI that Simple-JNDI points to.