我试图让 JUnit 运行,但它不断抛出以下错误:
class path resource [META-INF/persistence.xml] cannot be opened because it does not exist
整个堆栈跟踪可以在这里找到:http://codepad.org/OhlyjQKn 。这是一个 Spring 项目,带有 Hibernate(也使用 JPA)。该项目运行良好 - 正常运行时(不运行 JUnit 测试)不会提示任何丢失的文件
我尝试运行以下测试:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "file:src/main/webapp/WEB-INF/classes/applicationContext.xml",
"file:src/main/webapp/WEB-INF/config/spring-security.xml"})
public class KeyServiceTests {
@Test
public void testKeyCreation() {
ConfigurableApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
KeyService keyService = (KeyService) context.getBean("keyService");
// Some testing goes on here
}
}
applicationContext.xml中的entityManagerFactory定义如下: (整个文件在这里:http://codepad.org/UrCtj0pW)
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="persistenceUnitName" value="hsqldb-ds" />
<property name="persistenceXmlLocation" value="classpath:META-INF/persistence.xml"/>
</bean>
我的类路径是src/main/webapp/WEB-INF/classes
- 它包含applicationContext.xml以及META-INF/persistence.xml
persistence.xml 定义如下:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="2.0"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
<persistence-unit name="hsqldb-ds" transaction-type="RESOURCE_LOCAL">
<description>HSQLDB Persistence Unit</description>
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<properties>
<property name="javax.persistence.jdbc.driver" value="org.hsqldb.jdbcDriver" />
<property name="javax.persistence.jdbc.url" value="jdbc:hsqldb:mem:demodb" />
<property name="javax.persistence.jdbc.user" value="sa" />
<property name="javax.persistence.jdbc.password" value="" />
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect" />
<property name="hibernate.hbm2ddl.auto" value="validate" />
<property name="hibernate.show_sql" value="false" />
<property name="hibernate.format_sql" value="true" />
<property name="hibernate.transaction.flush_before_completion" value="true" />
</properties>
</persistence-unit>
所以是的。它找不到 persistence.xml,但它存在于它应该存在的地方(相对于类路径),并且项目仅在运行 JUnit 时提示该文件。有谁知道发生了什么事,或者我应该做什么才能让 JUnit 正常运行?我刚开始使用 JUnit 和 Spring/Hibernate,所以我可能做错了一些事情。
亲切的问候
最佳答案
我需要将 META-INF/persistence.xml 和 applicationContext.xml 移动到 src/main/resources 以使 JUnit 找出必要文件的位置。 JUnit 测试用例中的以下行更改为:
@ContextConfiguration(locations = {"classpath:applicationContext.xml"})
(我还删除了对 spring-security.xml 的引用,因为它有点不必要)
非常感谢用户 Wintermute!
关于java - JUnit 和 Spring : Cannot find persistence. xml - 但它确实存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23022331/