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("kuser@null.com");
    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

Answers


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.


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.


Need Your Help

Easily convert MM/DD to DD/MM including time in excel

excel date time format

Need to easily convert Excel date-time format from mm/dd/yyyy HH:mm:ss to dd/mm/yyyy HH:mm:ss

Run two SKActions repeatedly in sequence?

ios swift sprite-kit

I'm relatively new to sprite kit and am making a simple game where a ball moves back and forth accrues the screen and moves down when the screen is tapped. I am unable to find a way to run two acti...