Pages

Friday, August 19, 2011

How to mock JNDI(SimpleNamingContextBuilder)

Simple implementation of a JNDI naming context builder.

Mocking the JNDI naming context with "SimpleNamingContextBuilder" class.

Mainly targeted at test environments, where each test case can configure JNDI appropriately, so that new InitialContext() will expose the required objects. Also usable for standalone applications, e.g. for binding a JDBC DataSource to a well-known JNDI location, to be able to use traditional J2EE data access code outside of a J2EE container.

import javax.naming.NamingException;
import javax.sql.DataSource;

import junit.framework.TestCase;

import org.apache.commons.dbcp.BasicDataSource;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.mock.jndi.SimpleNamingContextBuilder;

import com.code.rfs.common.db.JndiDatasource;
import com.code.ejb.search.util.ApplicationConstants;
import com.code.ejb.search.util.PropertiesUtil;

public class JNDIControllerTest extends TestCase {
private JndiDatasource bean1;
private DataSource ds;

/* protected String[] getConfigLocations() {

return new String[] { "ApplicationContextTest.xml" };
}
*/


public void JNDIControllerTest() throws IllegalStateException, NamingException {
//setDependencyCheck(false);

SimpleNamingContextBuilder builder = new SimpleNamingContextBuilder();
org.apache.commons.dbcp.BasicDataSource dataSource = new BasicDataSource();
dataSource.setDriverClassName("oracle.jdbc.driver.OracleDriver");
dataSource.setUsername("XXXX");
dataSource.setPassword("XXXXXXXX");
dataSource.setUrl("jdbc:oracle:thin:@XYZ.XY.Z.XYZ.net:1111:ABCD");
builder.bind("java:comp/env/jdbc/Keely_DS",dataSource);
builder.bind("url/HLFSAppConfigFolder","file:///c:/ModifWorkspace/keely/fs-ejb/ejbModule");
builder.activate();
// setAutowireMode(AUTOWIRE_BY_TYPE);

}

public void testJNDI() throws Exception {
JNDIControllerTest();
ApplicationContext context = new ClassPathXmlApplicationContext("ApplicationContextTest.xml");
bean1 = (JndiDatasource)context.getBean("datacon");
System.out.println(bean1);
PropertiesUtil pUtil = new PropertiesUtil();

}


No comments:

Post a Comment