Avoid querying stale data when running integration tests against the database
The default behavior of ORMs is to load the entity from the in-memory cache to spare a query to the database.
This behavior is fine overall but does not fully test the persistence of the entity. Therefore, it's important to evict the entity from the cache in order to force the ORM to re-load the entity from the db. This is the case for ORMs in either Java or .Net environments.
In Spring, if you have properly configured the JPA, you evict entities from the cache by doing the following:
((Session)entityManager.
You can access the entityManager by getting it from the container as follows:
@PersistenceContext
private EntityManager entityManager;
private EntityManager entityManager;
Below you may find a simple, yet complete example of a persistence integration test with this technique applied: