开发者

OpenJPA, Jersey, JUnit: Using a different persistence unit for my unit tests?

I'm building an application using OpenJPA 2.0.0, Jersey 1.3, and JUnit 4.8.1.

I've set it up so I have two different persistence units defined in 开发者_运维知识库my persistence.xml: "default" and "unittest." Default is set up to connect to an Oracle instance, while unittest is set up to connect to a local H2DB embedded database file. I do this so that I always start my unit tests with a clean database which has certain known data in it, which can be overwritten between each run of the unit tests.

The problem is that now I want to use the Jersey Testing Framework to test my actual webservices, rather than just the lower layers of the program. My root resource classes don't load the unittest persistence unit, they always load the default.

So what I probably need to do is to inject into the root resource classes which persistence unit should be used to instantiate the EntityManager, and then have some way to inject unittest when I'm running my tests but inject default otherwise. But I can't think of any good way to do that.

I'm brand new to Java EE development, which might be obvious.

Any help?


I think it should be possible to create a second persistence.xml in src/test/resources/META-INF.

If I understand things correctly, maven will put target/test-classes in the classpath ahead of target/classes, so that in a unit test, only your test persistence.xml will be read. That way you can use the same persistence unit name, but with a different configuration.

src/main/resources/
    META-INF
        persistence.xml  <-- for actual application

src/test/resources/
    META-INF
        persistence.xml  <-- for unit tests

EDIT:

oops, I was tricked into believing you used maven by the other answer. If you are not, forget what I said...


Are you using Maven ? If yes, there is a trick that allows you to "read" a POM value in your Java class. It was very useful for me, you would just have to set your Persistence Unit Name in your POM, a different one during the test, and that's it.

Maven variables in java context

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜