citress
citress

Reputation: 909

Commit/Flush transactions during unit test?

I am using Spring and JUnit to write some integration tests for my DAO. I set up my test data in the beginning of the test method, and then test my DAO methods later in the same test method. The problem is that if I don't flush/commit the transaction, the EntityManager returns the same instance of the entities that I have just created in my data setup - rendering my test useless as they will always pass.

E.g.

@Test   
@Transactional()
public void loadTreeBasicCase() {
    // creates and saved node to DB
    Node n = createNode();

    // test DAO
    Node result = dao.lookup(n.getId());

    // verify
    assertThat(n, equalTo(result));
}

One way is to expose commit() and/or flush() methods in my DAO. But I would prefer not to do that because in production code, this almost never needs to happen (let EntityManager do it's thing). Is there a way to configure this via annotations or in Spring config? I am using Spring, JPA2 with Hibernate.

Upvotes: 2

Views: 6538

Answers (1)

Jeanne Boyarsky
Jeanne Boyarsky

Reputation: 12266

You can set the defaultRollback attribute on @Transactional to reset things between tests. This doesn't sound like what you are asking for, just throwing it out there first.

Within the test, the entity manager is behaving correctly. You want to inject different behavior for testing to "disconnect" the setup from the rest of the test. One thing I did in some tests was to call flush on the entity manager directly from the test. I only had to do it a few times, but it was valuable in those cases. I did it in the test (not the DAO) so as to not provide a method on the DAO that I don't want people calling.

Upvotes: 2

Related Questions