我正在对基于 spring 的应用程序 atm 进行单元测试。首先问题是,如果我没有在服务器上启动应用程序一次,单元测试都会失败。如果我确实首先在服务器上启动应用程序(然后停止它),那么我的单元测试正在运行。
在不启动服务器的情况下,我收到以下错误:
... java.io.FileNotFoundException: class path resource [META-INF/spring/applicationContext-test.xml] cannot be opened because it does not exist
我的单元测试定义如下:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "/META-INF/spring/applicationContext-test.xml" })
@TransactionConfiguration
@Transactional
public class InventoryControllerTest extends AbstractTransactionalJUnit4SpringContextTests {
private MockHttpServletRequest request;
private MockHttpServletResponse response;
private AnnotationMethodHandlerAdapter handlerAdapter;
@Before
public void setUp() throws Exception {
request = new MockHttpServletRequest();
response = new MockHttpServletResponse();
handlerAdapter = applicationContext
.getBean(AnnotationMethodHandlerAdapter.class);
}
//... tests
}
所以就像我说的,如果我之前启动过一次应用程序,一切正常。
所以我将配置位置更改为 locations = { "classpath/META-INF/spring/applicationContext-test.xml" }) 但毫不费力,与上面提到的相同异常。
更进一步的唯一方法是这个位置:locations = {"classpath*:applicationContext-test.xml"}) 然后我得到这个异常:没有找到类型为 [javax.sql.DataSource] 的匹配 bean 依赖项:至少预期1 个有资格作为此依赖项的自动装配候选者的 bean。依赖注释:{}
但这很令人困惑,因为我的测试上下文文件中肯定有一个数据源:
<bean class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close" id="dataSource">
<property name="driverClassName" value="org.hsqldb.jdbcDriver" />
<property name="url" value="jdbc:hsqldb:mem:testdb;sql.syntax_ora=true" />
<property name="username" value="some" />
<property name="password" value="some" />
</bean>
EIDT 2
认识到问题在于 RunWith(...) 并同时扩展 spring 类并从位置路径中删除所有通配符。我得到这个例外:
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'transactionManager' defined in class path resource [META-INF/spring/applicationContext-test.xml]: Cannot resolve reference to bean 'entityManagerFactory' while setting bean property 'entityManagerFactory'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [META-INF/spring/applicationContext-test.xml]: Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: No persistence unit with name 'persistenceUnitTest' found
... 24 more
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [META-INF/spring/applicationContext-test.xml]: Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: No persistence unit with name 'persistenceUnitTest' found
... 40 more
Caused by: java.lang.IllegalArgumentException: No persistence unit with name 'persistenceUnitTest' found)
... 47 more
我真的很感激任何帮助!
提前致谢