You have to understand the following, the cache is linked to the PersistenceContext that is created when you create an EntityManager.
You can seamlessly use JUnit with EntityManager to test your DAO. What you should do is:
Add HSQLDB as a dependency or some other bank in memory
To have a persistence.xml just for the test, in that case, it would be enough to add it inside a test directory, in the case of maven, that this context switch would be automatically made.
Create a static EntityManagerFactory:
private static EntityManagerFactory entityManagerFactory;
Create a static method annotated with @BeforeClass that will create the EntityManagerFactory:
@BeforeClass
public static void createPersistenceUnit () {
entityManagerFactory = Persistence.createEntityManagerFactory ("PU")
}
Create a static method annotated with @AfterClass to kill the EntityManagerFactory:
@AfterClass
public static void closePersistenceUnit () {
entityManagerFactory.close ();
}
Create a method annotated with @Before to start the EntityManager with each test:
@Before
public void beforeTest () {
entityManager = getEntityManagerFactory (). createEntityManager ();
}
Create a method with @After to end the EntityManager after each test:
@After
public void finishTest () {
entityManager.close ();
}
This way you will have an EntityManager for each test and your first level cache will be no problem.
This post is a bit old, but talk about it: link