Puce Puce - 6 months ago 40
Java Question

JUnit + Derby + Spring: drop in-memory db after every test

In my unit tests I autowired some DataSources, which use URLs like

jdbc:derby:memory:mydb;create=true


to create an in-memory DBs.

To drop an in-memory Derby db you have to connect with:

jdbc:derby:memory:mydb;drop=true


I would like this to happen after every test and start with a fresh db. How can I do this using Spring?

Answer

How to shutdown Derby In Memory Database Properly

gave me a hint to a solution:

    mydb.drop.url = jdbc:derby:memory:mydb;drop=true

    ...

    <bean id="mydbDropUrl" class="java.lang.String">
    <constructor-arg value="${mydb.drop.url}" />
</bean>

    ...

    @Resource
private String mydbDropUrl;        

    @After
public void tearDown() {
    try {
        DriverManager.getConnection(mydbDropUrl);
    } catch (SQLException e) {
        // ignore
    }
}

A downside is the use of the String constructor which accepts a String (an immutable String object around an immutable String object). I read that there is a @Value annotation in Spring 3, which might help here, but I'm using Spring 2.5.

Please let me know if you have a nicer solution.

Comments