0

these days I write some code without spring support, and try write code like this In Service..

c = ds.getConnection();
c.setAutoCommit(false);
try {
    dao.findXX(c, id);
    c.commit();
} catch (Exception ex) {
    c.rollback();
}

but, I meet some problem when I try to mock DAO, and test my service. because getConnection is called, it will connect to a db which doesn't want to see for our.

how to write service/dao with jdbc to easy test?

4

1 回答 1

0

我建议使用其中一种内存数据库(HSQL、Derby、H2)。
测试开始时,您只需创建与内存数据库的连接并模拟您的连接,ds以便在调用 getConnection 时返回此连接。

使用以下连接字符串之一:

public static final String JDBC_URL_DERBY = "jdbc:derby:memory:some_db_name;drop=true";
public static final String JDBC_URL_HSQL = "jdbc:hsqldb:mem:some_db_name;shutdown=true";
public static final String JDBC_URL_H2 = "jdbc:h2:mem:some_db_name";

所有这些连接都会创建名为 *some_db_name* 的内存数据库实例

于 2012-07-30T06:35:09.000 回答