ORMUnit下载链接:
http://code.google.com/p/ormunit/
在做面向关系数据库的应用系统的时候,db表结构在开发过程中,可能会由于前期的设计不足导致不断的修改表结构。如果Java层面采用类似Hibernate ORM,随之对应的是maps & pojos的修改。此时修改后的简单测试就显得尤为重要。
ORMUnit功能比较多,本文只取其少数几个类,完成上面的功能。
1.首先改写:HibernateORMTestCase类,指定加载的hibernate.cfg.xml位置
public abstract class HibernateORMTestCase extends TestCase {
protected Log logger = LogFactory.getLog(getClass());
protected SessionFactory sessionFactory;
//Location of hibernate.cfg.xml file.
private static String CONFIG_FILE_LOCATION = "com/mmm/china/xxx/dbtest/hibernate.cfg.xml";
protected Configuration cfg;
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
/**
* make configuration
* @return
*/
protected Configuration getConfiguration() {
if (cfg == null) {
cfg=new Configuration().configure(CONFIG_FILE_LOCATION);
}
return cfg;
}
}
2.HibernateSchemaChecker类(检查db schema map pojo):改写输出不符合map关系的表以及变更脚本,并增加计数功能
List getSignificantDifferences(
String[] script) {
int num=0;
List differences = new ArrayList();
for (int i = 0; i < script.length; i++) {
String line = script[i];
if (line.indexOf("add constraint") == -1)
{
differences.add(line);
logger.error("DIFF_LINE>>>>>>>>>>="+line);
}
else{
num++;//计算有多少个外键有问题
logger.info("CONSTRAINT_LINE>>>>>>>>>>"+num+"="+line);
}
}
return differences;
}
注:ORMUnit 检查CONSTRAINT 有问题,在db为sqlserver时,生成的外键约束的名称是自动命名的,与实际数据库的命名不一致,ORMUnit就认为不匹配,所以,要过滤add constraint的error信息
3.使用HibernateSchemaTests 进行junit测试
public class HibernateSchemaTests extends HibernateORMTestCase {
private HibernateSchemaChecker schemaChecker;
protected void setUp() throws Exception {
super.setUp();
schemaChecker = new HibernateSchemaChecker(getConfiguration(), getConfiguration().buildSessionFactory());
}
/**
* Verifies all tables and columns referenced by the object/relational
* mapping exist
*
* @throws Exception
*/
public void assertDatabaseSchema() throws Exception {
schemaChecker.assertDatabaseSchema();
}
}
总结:只需要三个类,即可测试数据库schema与hibernate maps & pojo的map关系是否完全匹配,事半功倍。