我想尝试使用嵌入式数据库在 Spring 应用程序中测试我的 DAO 对象。
在应用上下文中我有这个标签:
<jdbc:embedded-database id="dataSourceEmbedded" type="HSQL">
<jdbc:script location="classpath:/embeddeddb/schema.sql" />
<jdbc:script location="classpath:/embeddeddb/data.sql" />
</jdbc:embedded-database>
我的 JUnit 测试类需要使用这个 bean:
import org.apache.log4j.Logger;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabase;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:/applicationContext.xml")
public class PartnerDAOTest {
@Autowired
@Qualifier("dataSourceEmbedded")
public EmbeddedDatabase dataSourceEmbedded;
@Test
public void testSavePartner() {
}
}
一切正常(“dataSourceEmbedded”bean 已创建)但是当我尝试在 PartnerDAOTest 类中 Autowiring 它们时,Spring 抛出此异常:
testSavePartner(sandbox.PartnerDAOTest): Error creating bean with name 'sandbox.PartnerDAOTest': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: public org.springframework.jdbc.datasource.embedded.EmbeddedDatabase sandbox.PartnerDAOTest.dataSourceEmbedded; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.springframework.jdbc.datasource.embedded.EmbeddedDatabase] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true), @org.springframework.beans.factory.annotation.Qualifier(value=dataSourceEmbedded)}
我的代码有什么问题?
最佳答案
正如@M.Deinum 在他的评论中注意到的那样:
There is no bean of the type EmbeddedDatabase there is a DataSource. The embedded-database eventually creates a DataSource not an EmbeddedDatabase.
关于java - 无法在 JUnit 测试类中 Autowiring Spring bean,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21732187/