简体   繁体   中英

How to use setup datasource for HSQL for junit test

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM