对中的组件编写单元测试计划
下面是UserDaoImpl的单元测试类:
public class UserDaoImplTest extends DatabaseFixture {
private UserDao userDao = new UserDaoImpl();
private UserDao proxy = (UserDao)createProxy(userDao);
@Test
public void testQueryUser() {
User user = newUser(\"test\");
eateUser(user);
User t = eryUser(\"test\");
assertEquals(tEmail(), tEmail());
}
}
注意到UserDaoImplTest持有两个UserDao引用,userDao是普通的UserDaoImpl对象,而proxy则是将userDao进行了事务封装的对象。
由于UserDaoImplTest从DatabaseFixture继承,因此,@Before方法在每个@Test方法调用前自动调用,这样,每个@Test方法执行前,数据库都是一个经过初始化的“干净”的表。
对于普通的测试,如eryUser()方法,直接调用eryUser()即可在事务内执行查询,获得返回结果。
对于异常测试,例如期待一个ResourceNotFoundException,就不能直接调用eryUser()方法,否则,将得到一个UndeclaredThrowableException:
498)this.style.width=498;\">图3这是因为通过反射调用抛出的异常被代理类包装为UndeclaredThrowableException,因此,对于异常测试,只能使用原始的userDao对象配合TransactionCallback实现:
@Test(expected=ass)
public void testQueryNonExistUser() throws Exception {
new TransactionCallback() {
protected Object doInTransaction() throws Exception {
拥有销售和商业产品管理经验 eryUser(\"nonexist\");
return null;
}
}.execute();
}
到此为止,对DAO组件的单元测试已经实现完毕。下一步,我们需要使用HibernateTool自动生成数据库脚本,免去维护SQL语句的麻烦。相关的Ant脚本片段如下:
target name=\"make-schema\" depends=\"build\" description=\"create schema\"
taskdef name=\"hibernatetool\"
classname=\"bernateToolTask\"
classpath refid=\"build-classpath\"/
/taskdef
taskdef name=\"annotationconfiguration\"
classname=\"notationConfigurationTask\"
classpath refid=\"build-classpath\"/
/taskdef
annotationconfiguration configurationfile=\"${r}/l\"/
hibernatetool destdir=\"${r}\"
classpath refid=\"build-classpath\"/
annotationconfiguration configurationfile=\"${r}/l\"/
hbm2ddl
export=\"false\"
drop=\"true\"
create=\"true\"
delimiter=\";\"
outputfilename=\"l\"
destdir=\"${r}\"
/
/hibernatetool
/target
完整的Ant脚本以及Hibernate配置文件请参考项目工程源代码。
利用HSQLDB,我们已经成功地简化了对DAO组件进行单元测试。我发现这种方式能够找出许多常见的bug:
◆HQL语句的语法错误,包括SQL关键字和实体类属性的错误拼写,反复运行单元测试就可以不断地修复许多这类错误,而不需要等到通过Web页面请求而调用DAO时才发现问题;
◆传入了不一致或者顺序错误的HQL参数数组,导致Hibernate在运行期报错;
◆一些逻辑错误,包括不允许的null属性(常常由于忘记设置实体类的属性),更新实体时引发的数据逻辑状态不一致。
总之,单元测试需要根据被测试类的实际情况,编写最简单最有效的测试用例。本文旨在给出一种编写DAO组件单元测试的有效方法。
查看本文来源
吉林治疗白癜风费用海口医院男科
米诺地尔治疗效果
- 上一篇:对中的组件编写单元测试物业
- 下一篇:对几点的理解覆盖
-
你知道除了散步和跑步之外还可以带金毛做什位置
主食2022年06月13日
-
清洁剂对狗狗的危害位置
主食2022年06月13日
-
使用纱布帮助猫咪刷牙的方法位置
主食2022年06月13日
-
使用什么训练方法可以不让拉布拉多犬乱叫位置
主食2022年06月13日
-
你的吉娃娃知道怎样与别人握手吗位置
主食2022年06月13日
-
你正在犯哪些冬季饲养松狮犬的错误位置
主食2022年06月13日