【发布时间】:2014-04-11 20:50:16
【问题描述】:
我正在尝试让 JUnit 运行,但它不断抛出以下错误:
class path resource [META-INF/persistence.xml] cannot be opened because it does not exist
可以在此处找到整个堆栈跟踪:http://codepad.org/OhlyjQKn。这是一个带有 Hibernate 的 Spring 项目(也使用 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 正常运行?我是在 Spring/Hibernate 中使用 JUnit 的新手,所以我可能做错了一些事情。
亲切的问候
【问题讨论】:
标签: java spring jpa junit persistence.xml