Unit Testing Hibernate's Optimistic Locking (within Spring)
- by Michal Bachman
I'd like to write a unit test to verify that optimistic locking is properly set up (using Spring and Hibernate).
I'd like to have the test class extend Spring's AbstractTransactionalJUnit4SpringContextTests.
What I want to end up with is a method like this:
@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");
}
This test fails. What do you recommend as a best practice?
The reason I am trying to do this is that I want to transfer the version to the client (using a DTO). I want to prove that when the DTO is sent back to the server and merged with a freshly loaded entity, saving that entity will fail if it's been updated by somebody else in the meantime.