How can I test database transaction logic?
I often find error handling is one of the hardest things to test. Thankfully with dependency injection and mocking frameworks it's getting much easier.
However, I'm still having trouble testing data access objects, especially the error handling and rollback aspects. Suppose I have a two queries in a DAO method like so:
INSERT INTO A(AID, AVAL)
VALUES (1, 'TEST');
INSERT INTO B(AID, BVAL)
VALUES (1, 'TEST');
And I want transaction logic, implemented in Spring's transaction management, such that if the insert into B
fails the insert into A
is开发者_如何转开发 rolled back.
How can I test this?
Have two DAOs (both interface based, of course):
public interface GenericDao<T, K extends Serializable> {
public T find(K key);
public List<T> find();
public K save(T value);
public void update(T value);
public void delete(T value);
}
The GenericDao<B>
is mocked to throw a RuntimeException
from its save method. You should see the Spring transaction manager roll back the transaction.
精彩评论