2017-04-06 83 views
1

我有两个持久性文件,非常适用于基于maven的项目。用于测试和生产的JPA资源

  • 的src /主/资源/ persistence.xml中(JNDI)
  • 的src /测试/资源/ persistence.xml中(LOCAL_RESOURCE)

Eclipse和行家未能提供到的junit在测试运行时失败我的测试。

+1

它应该在META-INF下,而不是在根。 –

+0

这可能不是Eclipse的失败。其他人报告说,使用maven-failsafe插件触发的测试不会将'target/test-classes'放在class/target之前的classpath中,因为它应该覆盖META-INF/persistence.xml(btw ,它应该在META-INF中,而不是根资源)。我使用maven-surefire-plugin运行测试,并加载了正确的'persistence.xml'。 – coladict

+0

你如何加载你的persistence.xml文件?通过类路径? – khmarbaise

回答

0

作为最后的手段,试图迫使副本maven-resources-plugin

<project> 
    ... 
    <build> 
    <plugins> 
     <plugin> 
     <artifactId>maven-resources-plugin</artifactId> 
     <version>3.0.2</version> 
     <executions> 
      <execution> 
      <id>copy-resources</id> 
      <!-- here the phase you need --> 
      <phase>validate</phase> 
      <goals> 
       <goal>copy-resources</goal> 
      </goals> 
      <configuration> 
       <outputDirectory>${project.build.directory}</outputDirectory> 
       <resources>   
       <resource> 
        <directory>src/**/*.xml/directory> 
        <filtering>true</filtering> 
       </resource> 
       </resources>    
      </configuration>    
      </execution> 
     </executions> 
     </plugin> 
    </plugins> 
    ... 
    </build> 
    ... 
</project> 

未经测试。

0

虽然正如我在评论中解释的那样,但我相信问题出现在maven插件中。如果可能,请尝试使用maven-surefire-plugin而不是maven-failsafe-plugin。但是即使你使用第二个persistence.xml,你在维护时会遇到一个不同的问题(至少在Hibernate 5.2中)。它不会检测来自主要来源的注释类,但只能从测试中检测出来,并且您必须将它们列入<class>标记中,并尽量不要忘记每次都做。我找到了解决方案,为我的作品是只有主XML和实例我EntityManagerFactory这样的:

@BeforeClass 
public static void initJpa() throws Exception { 
    TreeMap<String, Object> props = new TreeMap<>(); 
    props.put("javax.persistence.jdbc.driver", "org.postgresql.Driver"); 
    props.put("javax.persistence.jdbc.url", "jdbc:postgresql://127.0.0.1:5432/projectdb"); 
    props.put("javax.persistence.jdbc.user", "testuser"); 
    props.put("javax.persistence.jdbc.password", "testpass"); 
    props.put("javax.persistence.nonJtaDataSource", null); // important to override the data-source! 
    emf = Persistence.createEntityManagerFactory("persistance.unit.name", props); 
} 

javax.persistence.nonJtaDataSource属性是什么做到底的伎俩。

这应该绕过您遇到的类加载重写问题。