Reputation: 40357
I have written a repository class that takes a javax.sql.DataSource
as a constructor arg, and has some basic CRUD operations on it. I now want to write junit tests for it. I want to use HSQL as my DB for these tests, but I'm not sure how to set up the DB the way I want. With a Spring app, I've put something like this in my app-context for the test:
<jdbc:embedded-database id="dataSource">
<jdbc:script location="classpath:mySQLForDB.sql"/>
</jdbc:embedded-database>
However, what I'm wanting to test isn't in a Spring app. Is there anyway in code to setup the datasource and setup up the DB from a sql file? Basically something that would be functionally equivalent to what Spring is doing with the <jdbc:embedded-database>
tag.
Upvotes: 1
Views: 2063
Reputation: 2094
Would you consider trying h2?
public static void main(String[] args) throws ClassNotFoundException,
SQLException {
Class.forName("org.h2.Driver");
Connection conn = DriverManager.getConnection("jdbc:h2:mem:mytestdb",
"sa", "");
Statement st = conn.createStatement();
st.execute("create table foo (id integer)");
st.execute("insert into foo (id) values (1)");
ResultSet rs = st.executeQuery("select * from foo");
while (rs.next()) {
int result = rs.getInt("id");
System.out.println(result);
}
conn.close();
}
HSQL has the same way but haven't tried it. Look at this link
I hope this helps.
Upvotes: 1