spring-bootjpaspring-data-jpaspring-dataeclipselink

@ExpectedDatabase not working as expected


I have a JUnit test which does a basic check of the repository layer which deletes an entry from the db.

I am using @DatabaseSetup annotation to provide initial configuration and using @ExpectedDatabase to verify the contents of DB post the deletion.

Following is the code

    @Test
    @ExpectedDatabase(
            table = "OBJECT_ALIAS",
            value = "classpath:dbunit/data/object_alias_deleted_2115_ALIAS_5.xml")
    public void testDeleteObjectAlias() {
        ObjectAlias objectAlias = new ObjectAlias(2115, 5, "NewAlias");
        objectAliasRepository.deleteObjectAlias(objectAlias);
        //objectAliasRepository.findByPartyNo(5); //runs a select query on DB
    }

The above test fails but if I uncomment the commented line, the test passes. I am using eclipseLink as a JPA provider.

What causes this behaviour?


Solution

  • I was able to find a solution to this.

    This is not an issue but a way JPA behaves/works. When performing any db operations, the changes are kept in first level cache until the transaction is committed or the persistence context is explicitly flushed.

    The scenario in the question when it worked was because when a select query was run, it caused the JPA to flush the changes to the db.

    The solution was to explicitly run entityManager.flush() in the test class so that the changes are committed to the database.