2009-08-05 110 views
2

我使用春季和休眠我的数据访问层 我想有一些关于如何构建我的单元测试,以测试hibernate是否有效地插入到子表(父Hibernate映射在集合上都有级联)。 什么,我知道我不应该混道的单位testing.So假设在我测试的家长DAO方法saveWithChild:测试休眠父母/子女关系

public void testSaveWithChild() { 
    Child c1 = new Child("prop1", "prop2", prop3); 
    Child c2 = new Child("prop4", "prop4", prop3); 
    Parent p = new Parent("prop6","prop7"); 
    p.addChild(c1); 
    p.addChild(c2); 
    Session session = MysessionImplementation.getSession(); 
    Transaction tx = session.begingTransaction(); 
    ParentDAO.saveWithChild(p); 
    tx.commit(); 

    Session session1 = MysessionImplementation.getSession(); 
    //now it is right to call child table in here? 
    Child c1fromdb = (Child)session1.get(ChildClass.class,c1.getID()); 
    Child c2fromdb = (Child)session1.get(ChildClass.class,c2.getID()); 
    //parent asserts goes here 
    //children asserts goes here. 
} 

我不知道,但我不觉得舒适做this.Isn有没有更好的办法? 你将如何检查这些东西?谢谢阅读。 ;)

回答

0

你可以做,而不是:

public void testSaveWithChild() { 
    Child c1 = new Child("prop1", "prop2", prop3); 
    Child c2 = new Child("prop4", "prop4", prop3); 
    Parent p = new Parent("prop6","prop7"); 
    p.addChild(c1); 
    p.addChild(c2); 
    Session session = MysessionImplementation.getSession(); 
    Transaction tx = session.begingTransaction(); 
    ParentDAO.saveWithChild(p); 
    tx.commit(); 

    Session session1 = MysessionImplementation.getSession(); 
    Parent p2 = session1.get(ParentClass.class,p.getID()); 
    // children from db should be in p2.getChildren() 
} 

这样一来,至少不要混用不同的DAO。

+0

谢谢你会尝试 – 2009-08-05 17:16:51

0

首先,您应该在拨打tx.commit()后确定关闭会话。

如果MysessionImplementation.getSession()回报活动会话(类似于SessionFactory.getCurrentSession()),那么您的测试甚至不打算打数据库session1是一样session和两个孩子仍然会绑定到它。

如果MysessionImplementation.getSession()每次都会返回一个新的会话,那么您正在泄漏资源。其次,是你的例子中的孩子TRUE孩子(是他们的生命周期绑定到父母)?如果是这种情况,你根本不应该有ChildDAO(也许你没有),你的ParentDAO中可能有也可能没有getChildInstance(id)方法(不管它叫什么)。因为您正在测试ParentDao的功能,所以在ParentDAOTest中调用此方法(或者,如果您没有它,请使用session.load())是完全正确的。

最后,请记住,只是测试插入的孩子是不够的。您还需要测试他们是否插入了正确的父母(如果您的父母与子女之间的关系是双向的,您可以通过child.getParent()方法或您的案例中所称的任何方法来完成)。如果你的dao支持,你也应该测试子删除。

+0

非常好的洞察力。谢谢你的答案。 MysessionImplementation每次都会返回一个新的会话。那么如何防止资源泄漏? – 2009-08-05 17:08:57

+0

关闭会话。使用try/finally:Session session = MysessionImplementation.getSession();尝试{do stuff} finally {if(session!= null)session.close()}; – ChssPly76 2009-08-05 17:15:00

+0

感谢dude.really欣赏它 – 2009-08-05 17:18:43