views:

513

answers:

2

Here's what I'm trying to do. I'm using JPA persistence in a web application, but I have a set of unit tests that I want to run outside of a container.

I have my primary persistence.xml in the META_INF folder of my main app and it works great in the container (Glassfish).

I placed a second persistence.xml in the META-INF folder of my test-classes directory. This contains a separate persistence unit that I want to use for test only. In eclipse, I placed this folder higher in the classpath than the default folder and it seems to work.

Now when I run the maven build directly from the command line and it attempts to run the unit tests, the persistence.xml override is ignored. I can see the override in the META-INF folder of the maven generated test-classes directory and I expected the maven tests to use this file, but it isn't. My Spring test configuration overrides, achieved in a similar fashion are working.

I'm confused at to whether the persistence.xml is located through the classpath. If it were, my override should work like the spring override since the maven surefire plugin explains "[The test class directory] will be included at the beginning the test classpath".

Did I wrongly anticipate how the persistence.xml file is located?

I could (and have) create a second persistence unit in the production persistence.xml file, but it feels dirty to place test configuration into this production file. Any other ideas on how to achieve my goal is welcome.

+2  A: 

persistence.xml is loaded from the classpath; in the past, I've done exactly what you described.

It's most likely an issue with maven. You can debug the maven classpath by running it with the -X option.

Ken Liu
OK - Thanks for the feedback. At least I know I'm not doing something that's totally out there.
Vinnie
OK - this is working now. Before I had named each persistence unit in the different files with the same name. I changed the test persistence unit to have a different name. It doesn't seem right to me, but maybe this is a limitation I didn't know about.
Vinnie
I went and dug up the code where I had done this before, and I did have a different persistence unit defined for unit tests, although my test persistence.xml file did have the same (non-test) persistence unit also defined. It probably wasn't necessary though. I think the unit tests use the test persistence unit when creating the entity manager.
Ken Liu
A: 

It is unclear where you placed the "second" persistence.xml (the test version) but you should place it in src/test/resources/META-INF. Test resources are automatically added to the classpath set up by Maven for your unit tests and take precedence over resources placed in src/main/resources.

Pascal Thivent
right. that's where it is.
Vinnie