有没有办法在 Maven 项目中设置第二个 persistence.xml 文件,以便用于测试而不是用于部署的普通文件?
我尝试将 persistence.xml 放入 src/test/resources/META-INF,它会被复制到 target/test-classes/META-INF,但似乎是 target/classes/META-INF(来自src/main/resources) 成为首选,尽管 mvn -X test
以正确的顺序列出类路径条目:
[DEBUG] Test Classpath :
[DEBUG] /home/uqpbecke/dev/NetBeansProjects/UserManager/target/test-classes
[DEBUG] /home/uqpbecke/dev/NetBeansProjects/UserManager/target/classes
[DEBUG] /home/uqpbecke/.m2/repository/junit/junit/4.5/junit-4.5.jar
...
我希望能够针对简单的 hsqldb 配置运行测试,而无需更改 JPA 配置的部署版本,最好是在项目 checkout 后直接进行,无需进行任何本地调整。
最佳答案
以下内容适用于 Maven 2.1+(在此之前,测试和包之间没有可以将执行绑定(bind)到的阶段)。
您可以在测试期间使用 maven-antrun-plugin 将 persistence.xml 替换为测试版本,然后在项目打包之前恢复正确的版本。
这个例子假设生产版本是src/main/resources/META-INF/persistence.xml,测试版本是src/test/resources/META-INF/persistence.xml,所以它们会被复制到target/classes/META-INF 和 target/test-classes/META-INF。
将其封装到 mojo 中会更优雅,但由于您只是复制一个文件,这似乎有点矫枉过正。
<plugin>
<artifactId>maven-antrun-plugin</artifactId>
<version>1.3</version>
<executions>
<execution>
<id>copy-test-persistence</id>
<phase>process-test-resources</phase>
<configuration>
<tasks>
<!--backup the "proper" persistence.xml-->
<copy file="${project.build.outputDirectory}/META-INF/persistence.xml" tofile="${project.build.outputDirectory}/META-INF/persistence.xml.proper"/>
<!--replace the "proper" persistence.xml with the "test" version-->
<copy file="${project.build.testOutputDirectory}/META-INF/persistence.xml" tofile="${project.build.outputDirectory}/META-INF/persistence.xml"/>
</tasks>
</configuration>
<goals>
<goal>run</goal>
</goals>
</execution>
<execution>
<id>restore-persistence</id>
<phase>prepare-package</phase>
<configuration>
<tasks>
<!--restore the "proper" persistence.xml-->
<copy file="${project.build.outputDirectory}/META-INF/persistence.xml.proper" tofile="${project.build.outputDirectory}/META-INF/persistence.xml"/>
</tasks>
</configuration>
<goals>
<goal>run</goal>
</goals>
</execution>
</executions>
</plugin>
关于java - 如何配置 JPA 以在 Maven 中进行测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/385532/