1

I'm using this code snippet to mock JDBC Datasources from within Junit4:

@Before
public void setUp() throws Exception {
    try {
        SimpleNamingContextBuilder builder = new SimpleNamingContextBuilder();
        BasicDataSource ds = new BasicDataSource();
        ds.setDriverClassName("org.postgresql.Driver");
        ds.setUrl("jdbc:postgresql://address:port/db");
        ds.setUsername("user");
        ds.setPassword("pass");
        builder.bind("jdbc/db", ds);

        builder.activate();

        System.out.println("connected");
    } catch (NamingException ex) {
        System.err.println("error: " + ex.getMessage());
    }

}

Specific imports:

import org.apache.commons.dbcp2.BasicDataSource;
import org.springframework.mock.jndi.SimpleNamingContextBuilder;

Question: how should I close the DataSource connections in a tearDown method?

The problem is that neither builder nor ds are class variables which could be referenced, perhaps should I just move ds to a class scope and then use it to close it's Connection objects?

Should I also "de-bind" the DataSource from the NamingContext or, that part doesn't really matter at all?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.