【发布时间】:2010-03-16 15:43:52
【问题描述】:
我想编写一个单元测试来验证乐观锁定是否已正确设置(使用 Spring 和 Hibernate)。
我想让测试类扩展 Spring 的 AbstractTransactionalJUnit4SpringContextTests。
我最终想要的是这样的方法:
@Test (expected = StaleObjectStateException.class)
public void testOptimisticLocking() {
A a = getCurrentSession().load(A.class, 1);
a.setVersion(a.getVersion()-1);
getCurrentSession().saveOrUpdate(a);
getCurrentSession().flush();
fail("Optimistic locking does not work");
}
此测试失败。您推荐的最佳做法是什么?
我尝试这样做的原因是我想将version 传输到客户端(使用 DTO)。我想证明,当 DTO 被发送回服务器并与新加载的实体合并时,如果同时其他人更新了该实体,则保存该实体将失败。
【问题讨论】: