Uploaded image for project: 'Spring Framework'
  1. Spring Framework
  2. SPR-7873

Add wrapper class for SimpleNamingContextBuilder to allow mocking JNDI through Spring Application Configuration

    Details

    • Type: Improvement
    • Status: Resolved
    • Priority: Minor
    • Resolution: Won't Fix
    • Affects Version/s: None
    • Fix Version/s: None
    • Component/s: Test
    • Labels:
      None

      Description

      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.

      SimpleNamingContextBuilderConfigurator.java
      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.

        Attachments

          Activity

            People

            • Assignee:
              sbrannen Sam Brannen
              Reporter:
              cbenjamin Christopher Benjamin
              Last updater:
              Juergen Hoeller
            • Votes:
              0 Vote for this issue
              Watchers:
              1 Start watching this issue

              Dates

              • Created:
                Updated:
                Resolved:
                Days since last comment:
                5 years, 27 weeks, 6 days ago