Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JPA 2.0 disable session cache for unit tests

I am writing unit test for my services e. g. :

@Test
@Rollback(value = true)
public void testMethod()
{
   // insert test data

    myService.Method(); // read/write from DB

   // asserts go here
}

While application running, a new transaction is created every time method A entered. But during the unit test execution - when test testMethod entered. So method A doesn't create new one. For proper testing I need to clear cache before every call to service inside test.I don't want to write Session.clear() before any call to service in each unit test. What is the best best practices here?

like image 814
Mark Carmark Avatar asked Jul 23 '13 15:07

Mark Carmark


1 Answers

The EntityManager has a method clear() that will drop all persistence context:

Clear the persistence context, causing all managed entities to become detached. Changes made to entities that have not been flushed to the database will not be persisted.

If you call a query right after that method it will come directly from the database. Not from a cache.

If you want to run this before every test, consider using a JUnit @Rule by subclassing ExternalResource and running the method on every before() or after(). You can reuse that in al you database tests.

like image 106
Alex Avatar answered Oct 08 '22 10:10

Alex