Unit testing datasources without hibernate

I’ve got some code in my current project that uses JDBC rather than Hibernate. I’m using datasources, so using simple JDBC connection was not going to work. Most of the datasource-related code for junit that I’ve found on the web assumes hibernate, so it was a bit difficult to solve this problem. I found a good solution: Spring framework’s DriverManagerDataSource, which creates a simple datasource on-the-fly:

try {
Context init = new InitialContext();
Context ctx = null;
ctx = (Context) init.lookup("java:comp/env");
dataSource = (DataSource) ctx.lookup("jdbc/myDB");
} catch (NamingException e) {
DriverManagerDataSource ds = new DriverManagerDataSource();
ds.setDriverClassName("com.mysql.jdbc.Driver");
ds.setUrl("jdbc:mysql://localhost/myProject");
ds.setUsername("username");
ds.setPassword("password");
dataSource = ds;
}

I’m not using Spring for this project but I simply added spring.jar to my classpath, and Bob’s yer uncle. Works fine!

On a related manner, logging was not working - I was getting a FileNotFoundException. Here’s my log4j.properties entry for the logfile:

log4j.appender.R.File=${catalina.home}/logs/my.log

${catalina.home} was not getting initialized, so I simply set the path manually:

log4j.appender.R.File=/tomcat/logs/my.log

When I get a chance, I’ll figure out how to declare that variable manually so I don’t have to change my log4j when I deploy.

Comments are closed.