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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With