java - 无法在 JUnit 测试类中 Autowiring Spring bean

标签 java spring junit hsqldb embedded-database

我想尝试使用嵌入式数据库在 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/

相关文章:

Java(JLabel间距)

java - 如何在 Spring Boot 应用程序启动时避免或忽略 schema.sql 的 SQLExceptions

java - 模拟函数在指定 return 后返回 null

java - spring boot 启动rest服务失败

java - 插入 Spring Boot 属性源的层次结构

android - 如何在 android 单元测试中创建位置?

android - 如何编写android jUnit功能测试

java - 从 HTML 表中提取数据并转换为 JSON

Java 从集合中删除会导致 IllegalStateException

java - filterWhen 与 flatMap 结合使用时会在 Reactor 中抛出异常