数据库相关单元测试代码怎么做?
对于一个重度耦合系统的数据库DAO部分的单元测试怎么来做呢?Mock? 很难吧,而且你怎么测试出这个SQL写的对还是不对。
下面介绍一个很好的jar,可以实现内存中启动数据库,这样单元测试就简单多了。
添加依赖
ch.vorburger.mariaDB4j
mariaDB4j
2.2.3
怎么使用呢?
配置DB
DBConfigurationBuilder configBuilder = DBConfigurationBuilder.newBuilder();
configBuilder.setPort(3306);
configBuilder.setDataDir("/home/theapp/db");
DB db = DB.newEmbeddedDB(configBuilder.build());
启动DB
db.start();
准备测试数据
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/test", "root", "");
db.source("path/to/resource.sql");
单元测试
@Test
public void testGetType() throws Exception {
//prepare data
Connection conn = null;
try {
conn = DriverManager.getConnection(getConfig().getURL(getDbName()), "root", "");
QueryRunner qr = new QueryRunner();
// Should be able to insert into a table
qr.update(conn, "INSERT INTO `test` (`id`, `type`,value) VALUES (NULL, 'haha', '300');");
} finally {
DbUtils.closeQuietly(conn);
}
//test
dao = (DaoImpl) SpringContextUtil.getBean("Dao");
Map typeValueMap = dao.getType();
String value = typeValueMap.get("haha");
Assert.assertEquals("300", value);
//delete data
try {
conn = DriverManager.getConnection(getConfig().getURL(getDbName()), "root", "");
QueryRunner qr = new QueryRunner();
// Should be able to insert into a table
qr.update(conn, "delete from `test` where type='haha'");
} finally {
DbUtils.closeQuietly(conn);
}
}
怎么样,是不是既简单有给力呢。
打开App,阅读手记