OpenJPA、Jersey、JUnit:为我的单元测试使用不同的持久性单元?
我正在使用 OpenJPA 2.0.0、Jersey 1.3 和 JUnit 4.8.1 构建一个应用程序。
我已经进行了设置,因此在 persistence.xml 中定义了两个不同的持久性单元:“default”和“unittest”。默认设置为连接到 Oracle 实例,而 unittest 设置为连接到本地 H2DB 嵌入式数据库文件。我这样做是为了始终使用一个干净的数据库开始单元测试,该数据库中包含某些已知数据,这些数据可以在每次运行单元测试之间被覆盖。
问题是,现在我想使用 Jersey 测试框架来测试我的实际 Web 服务,而不仅仅是程序的较低层。我的根资源类不加载unittest持久性单元,它们总是加载默认单元。
所以我可能需要做的就是注入根资源类哪个持久性单元应该用于实例化EntityManager,然后在我运行测试时通过某种方式注入unittest,但注入否则默认。但我想不出有什么好的方法来做到这一点。
我是 Java EE 开发的新手,这可能是显而易见的。
有什么帮助吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我认为应该可以在 src/test/resources/META-INF 中创建第二个 persistence.xml 。
如果我理解正确,maven 会将 target/test-classes 放在类路径中 target/classes 之前,这样在单元测试中,只会读取您的测试 persistence.xml。这样您就可以使用相同的持久性单元名称,但具有不同的配置。
编辑:
哎呀,我被另一个答案欺骗相信你使用了 Maven。如果你不是,请忘记我说的话......
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.
EDIT:
oops, I was tricked into believing you used maven by the other answer. If you are not, forget what I said...
你在使用 Maven 吗?
如果是,有一个技巧可以让您“读取”Java 类中的 POM 值。
这对我来说非常有用,您只需在 POM 中设置持久性单元名称(在测试期间设置不同的名称)即可。
java 上下文中的 Maven 变量
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