Wednesday 30 April 2014

Spring Context Unit Testing

It is always a good idea to unit test the spring contexts that define an application.  This can be as simple as a unit test

    @RunWith(SpringJUnit4ClassRunner.class)
    @ContextConfiguration(locations = { "classpath:com/me/my_context.xml" })
    public class SpringContextTest implements ApplicationContextAware
    {
        /**
         * The spring context.
         */
        private ApplicationContext applicationContext;

        /**
         * Test the spring wiring.
         */
        @Test
        public void testSpringWiring()
        {
            final Object obj = applicationContext.getBean("myBean");
            assertTrue(obj instanceof MyBean);
        }

        /**
         * {@inheritDoc}
         */
        @Override
        public void setApplicationContext(final ApplicationContext applicationContext)
        {
            this.applicationContext = applicationContext;
        }
    }


However, where there is interaction with a JNDI resource as part of the spring start up this needs to be modified to make the JNDI resource available.  Adding this @Before method will set up a JNDI resource for a MySql database.

    /**
     * Set up the jndi data source so that the wiring tests still work.
     */
    @BeforeClass
    public static void setUpClass()
    {
        // Setup the jndi context and the datasource
        try
        {
            // Create a database connection to satisfy the data loading requirements.
            final DriverManagerDataSource dataSource = new DriverManagerDataSource();
            dataSource.setDriverClassName("com.mysql.jdbc.Driver");
            dataSource.setUrl("jdbc:mysql://server:port");
            dataSource.setUsername("username");
            dataSource.setPassword("password");

            final SimpleNamingContextBuilder builder = SimpleNamingContextBuilder.emptyActivatedContextBuilder();
            builder.bind("jdbc/MY_JNDI_NAME", dataSource);
            builder.activate();
        }
        catch (final NamingException ex)
        {
            LOG.error("Error creating JNDI resource", ex);
        }
    }