DbUnit 简介和使用 (puts your database into a known state)

来源:互联网 发布:linux下删除用户命令 编辑:程序博客网 时间:2024/05/18 02:01

DbUnit简介

1. 引言

在写持久层测试用例的时候,由于我们的测试是要依赖于外部的数据库,数据库里面的数据影响我们测试,往往是要在数据库中去查询得到数据表数据的状态,然后才能在TestCase里面写断言。数据表的状态又是可变的,所以经常要在此来回切换。可能产生如下场景:

1) 要测试findAll方法,这个时候我们要去数据库里去先写个count(*)之后,才能写assertEquals(result.size(),size)

2) 要测试updateMember(),要先去数据库里查一条数据,并记下之前的状态,然后才能写upadateTestCase

3) 要测试insert,要先去数据库要先看下某主键是否已经被使用。

4) 要测试delete,要先去数据库里面去查找是否某条数据存在。

如果说我们在跑某一个测试用例的时候,总是已经知道了数据表里面当前的数据状态,那么就省了这种频繁的来回切换。DbUnit就是为了这个而产生。

2. dbunit基本原理

DbUnit is a JUnit extension (also usable with Ant) targeted at database-driven projects that, among other things, puts your database into a known state between test runs. This is an excellent way to avoid the myriad of problems that can occur when one test case corrupts the database and causes subsequent tests to fail or exacerbate the damage.(DbunitJunit的一个扩张。用于基于数据的项目。在测试时,使你的数据库处于一种已知的状态。是一种避免因为某些测试用例失败导致相关的测试失败而产生的大量的问题。)

Dbunit基本原理就是在跑测试用例运行之前对数据表做用户定义的操作,清空不想要的数据,插入用户自定义的数据,使得该数据表处于用户知道的一种状态。而用户自定义的数据使用项目里的一个xml文件来表示。Xml文件里面的数据代表了当前的数据状态,用户可以通过xml文件了解当前数据表的状态。同时在测试用例跑完之后,用户可以定义使得数据表处于一种用户想要的状态。一个测试用例的运行过程如下:

 

dbunit

1:测试用例运行过程。

一般的一个测试用例结构如下:

关于getSetUpOperationgetTearDownOperation的个解释:

DatabaseOperation.CLEAN_INSERT:先清空数据表里的数据,再插入getDataSet返回的数据到数据表中。是getSetUpOperation的默认状态(这个操作会使得数据库始终处于只有几条固定数据的状态,也是我们最常用的一种方式)

DatabaseOperation.NONE:不做任何事情。

还有DatabaseOperation.UPDATEDatabaseOperation.INSERTDatabaseOperation.REFRESHDatabaseOperation.DELETEDatabaseOperation.DELETE_ALLDatabaseOperation.TRUNCATECompositeOperationTransactionOperationIdentityInsertOperation等几个状态,具体参考官网:http://dbunit.sourceforge.net/components.html#cleanInsert

3. 例子

假设有这样一张表:

我们要对IMemberDao的实现类做如下三个方法的测试:

public List<Member> listAllMember(); //list all Members.

public Member findMemberById(long id); //find a Member by Id.

public boolean insertMember(Member member); //insert a member record.

假设我们要使数据表member处于如下状态:有三条用户自定义的记录,我们可以写一个MemberSet.xml:

<?xml version='1.0' encoding='UTF-8'?>

<dataset>

<member id="1" memberid="ant" name="sky" pass="123"

email="abing37@126.com" gender="male" birthday="1985-06-21" />

<member id="2" memberid="ant" name="abing" pass="123"

email="abing37@126.com" gender="male" birthday="1985-06-21" />

<member id="3" memberid="ant" name="yblin" pass="123"

email="abing37@126.com" gender="male" birthday="1985-06-21" />

</dataset>

我们的测试用例可以这样写:

通过以上的测试用例,我们只需要关注工程里的MemberSet.xml文件就可以完全了解数据库当前的状态了。