2017-04-06 36 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屬性是什麼做到底的伎倆。

這應該繞過您遇到的類加載重寫問題。