Dave
Dave

Reputation: 21924

JPA DAO integration test not throwing exception when duplicate object saved?

I am in the process of unit testing a DAO built with Spring/JPA and Hibernate as the provider.

Prior to running the test, DBUnit inserted a User record with username "poweruser" -- username is the primary key in the users table. Here is the integration test method:

@Test
@ExpectedException(EntityExistsException.class)
public void save_UserTestDataSaveUserWithPreExistingId_EntityExistsException() {
    User newUser = new UserImpl("poweruser");

    newUser.setEmail("[email protected]");
    newUser.setFirstName("New");
    newUser.setLastName("User");
    newUser.setPassword("secret");

    dao.persist(newUser);
}

I have verified that the record is in the database at the start of this method. Not sure if this is relevant, but if I do a dao.flush() at the end of this method I get the following exception:

javax.persistence.PersistenceException: org.hibernate.exception.ConstraintViolationException: 
    Could not execute JDBC batch update

Upvotes: 0

Views: 1283

Answers (2)

Dick Chesterwood
Dick Chesterwood

Reputation: 2659

I assume you're using the transactional integration tests? These tests rollback at the end of each test method, so you are indeed missing the flush.

I don't know if this is useful, but if you were autogenerating the ID, then a flush would happen at the persist() because a trip to the database is needed to get the generated ID. But if you're assigning your own ID's, then the flush is delayed until the commit, as you've seen.

Upvotes: 1

Dave
Dave

Reputation: 21924

Apparently unless flush is called explicitly or implicitly (via a query or a commit) then any potential exception will not be thrown. So I guess I am going to have to call flush() in all of my integration tests that modify data.

Upvotes: 1

Related Questions