@Test(expected=ResourceNotFoundException.class)
public void testQueryNonExistUser() throws Exception {
new TransactionCallback() {
protected Object doInTransaction() throws Exception {
userDao.queryUser("nonexist");
return null;
}
}.execute();
}
到此為止,對DAO組件的單元測試已經實現完畢。下一步,我們需要使用HibernateTool自動生成數據庫腳本,免去維護SQL語句的麻煩。相關的Ant腳本片段如下:
<target name="make-schema" depends="build" description="create schema">
<taskdef name="hibernatetool" classname="org.hibernate.tool.ant.HibernateToolTask">
<classpath refid="build-classpath"/>
</taskdef>
<taskdef name="annotationconfiguration" classname="org.hibernate.tool.ant.AnnotationConfigurationTask">
<classpath refid="build-classpath"/>
</taskdef>
<annotationconfiguration configurationfile="${src.dir}/hibernate.cfg.xml"/>
<hibernatetool destdir="${gen.dir}">
<classpath refid="build-classpath"/>
<annotationconfiguration configurationfile="${src.dir}/hibernate.cfg.xml"/>
<hbm2ddl
export="false"
drop="true"
create="true"
delimiter=";"
outputfilename="schema.sql"
destdir="${src.dir}"
/>
</hibernatetool>
</target>
完整的Ant腳本以及Hibernate配置文件請參考項目工程源代碼。
利用HSQLDB,我們已經成功地簡化了對DAO組件進行單元測試。我發現這種方式能夠找出許多常見的bug:
HQL語句的語法錯誤,包括SQL關鍵字和實體類屬性的錯誤拼寫,反復運行單元測試就可以不斷地修復許多這類錯誤,而不需要等到通過Web頁面請求而調用DAO時才發現問題;
傳入了不一致或者順序錯誤的HQL參數數組,導致Hibernate在運行期報錯;
一些邏輯錯誤,包括不允許的null屬性(常常由于忘記設置實體類的屬性),更新實體時引發的數據邏輯狀態不一致。
總之,單元測試需要根據被測試類的實際情況,編寫最簡單最有效的測試用例。本文旨在給出一種編寫DAO組件單元測試的有效方法。
文章來源于領測軟件測試網 http://www.kjueaiud.com/