Skip to content

Add wrapper class for SimpleNamingContextBuilder to allow mocking JNDI through Spring Application Configuration [SPR-7873] #12530

@spring-projects-issues

Description

@spring-projects-issues

Christopher Benjamin opened SPR-7873 and commented

I wanted to share a class that I wrote that I think might be useful to others. for allowing mocking JNDI datasource or JMS Connection factory directly from a Spring configuration file.

public class SimpleNamingContextBuilderConfigurator implements InitializingBean {

    private Map<String, Object> jndiMap;

    public void setJndiMap(Map<String, Object> jndiMap) {
        this.jndiMap = jndiMap;
    }

    public Map<String, Object> getJndiMap() {
        return jndiMap;
    }

    public void afterPropertiesSet() throws Exception {
        SimpleNamingContextBuilder builder = new SimpleNamingContextBuilder();
        for (String jndiName : jndiMap.keySet()) {
            builder.bind(jndiName, jndiMap.get(jndiName));
        }
        builder.activate();
    }

}

Having this class allows us to specify the mocking within a Spring configuration file, instead of hardcoding it in the Test class.

<bean id="jndiDatasourceMocker" class="com.xxx.SimpleNamingContextBuilderConfigurator" scope="singleton">
  <property name="jndiMap">
    <map>
      <entry key="java:/comp/env/jdbc/ds" value-ref="jdbcDS" />   
    </map>
  </property>
</bean>
<bean id="jdbcDS" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
  <property name="driverClassName" value="oracle.jdbc.driver.OracleDriver" />
  <property name="url" value="jdbc:oracle:thin:@localhost:1521:TESTDB" />
  <property name="username" value="test" />
  <property name="password" value="test" />
</bean>

We've used this a lot in our component tests by including the spring configuration above in our AbstractTransactionalJUnit4SpringContextTests based tests.


Reference URL: http://forum.springsource.org/showthread.php?131910-improve-JNDI-lookup-in-test-phase

Metadata

Metadata

Assignees

Labels

in: testIssues in the test modulestatus: declinedA suggestion or change that we don't feel we should currently applytype: enhancementA general enhancement

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions