0

We are working with gradle and have the default project structure:

/src
   /main
     /java
     /resources
       /META-INF
         persistence.xml
   /test
     /java
     /resources
       /META-INF
         persistence.xml

While we run our junit tests with gradle, all is fine (we do not have any special gradle configuration concerning source paths or the like): the persistence.xml from 'test' is used.

But if we try to run our junit tests with eclipse, always the peristence.xml from 'main' is used.

How can we configure eclipse to use the persistence.xml from 'main' for one launch configuration, but the persistence.xml from 'test' for all junit tests?

2 Answers2

1

Another thing to try, if this is a general problem about resources loaded from your classpath:

In Eclipse's project properties, Java Build Path->Order and Export, put your test folder above your src folder.

Then under Deployment Assembly, exclude your test folder

That will ensure that when you launch tests directly from within Eclipse, you will search the test folder first for classpath resources. But when you launch as a webapp instead, the test folders would be excluded from WEB-INF/classes.

wrschneider
  • 17,913
  • 16
  • 96
  • 176
  • I'll try that at work ;-) WEB-INF/classes sounds like JEE stuff. I'm in a J2SE environment. – Markus Frauenfelder Aug 10 '15 at 16:22
  • My suggestion probably won't work then if it's all J2SE, and Eclipse is launching both your main method and unit tests directly rather than assembling a webapp first. – wrschneider Aug 10 '15 at 16:25
  • I'll be working with classpath definitions and their orders. I can imagine that this will work. In the worst case I'll have to duplicate some classpath stuff for the execution of the main method so that the 'main' classpath gets loaded first. – Markus Frauenfelder Aug 10 '15 at 16:28
0

I've solved this problem with a single persistence.xml and different persistence units.

<persistence-unit name="MAIN">
  ...
</persistence-unit>

<persistence-unit app="TEST">
  ...
</persistence-unit>

Then in your app, you would inject the main persistence unit with

@PersistenceContext(name="MAIN", unitName="MAIN")
private EntityManager entityManager;

And for unit tests, you would explicitly create an EntityManager using the TEST persistence unit, and inject it manually into the object under test:

EntityManager em = Persistence.createEntityManagerFactory("TEST").createEntityManager();
bean.setEntityManager(em);
wrschneider
  • 17,913
  • 16
  • 96
  • 176