Spring + Hibernate + TestNG + Mockito无法转换为javax.sql.DataSource

时间:2016-12-01 07:52:00

标签: spring hibernate testng

我正在尝试为我的应用编写单元测试。测试需要使用来自sql文件的数据。 Maven给了我一个例外

org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseFactoryBean$$EnhancerBySpringCGLIB$$c65a0afd cannot be cast to javax.sql.DataSource

Hibernate DataSource配置:

@Bean
public DataSource dataSource() {
    BasicDataSource dataSource = new BasicDataSource();
    dataSource.setDriverClassName(environment.getRequiredProperty("jdbc.driverClassName"));
    dataSource.setUrl(environment.getRequiredProperty("jdbc.url"));
    dataSource.setUsername(environment.getRequiredProperty("jdbc.username"));
    dataSource.setPassword(environment.getRequiredProperty("jdbc.password"));
    return dataSource;
}

TestConfiguration

@Configuration
@ImportResource("classpath:test-context.xml")
public class TestConfiguration {

}

测试context.xml中

<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:jdbc="http://www.springframework.org/schema/jdbc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
    http://www.springframework.org/schema/jdbc
    http://www.springframework.org/schema/jdbc/spring-jdbc.xsd">


<!-- Set up H2 database -->
<jdbc:embedded-database id="dataSource" type="H2">
    <jdbc:script location="classpath:import.sql" />
</jdbc:embedded-database>

我找不到答案,或者是一个恰当的例子。最重要的是,当我删除测试时,app工作正常。

更新

堆栈跟踪

https://jpst.it/PY4v

1 个答案:

答案 0 :(得分:0)

您正在尝试使用标识为dataSource的bean作为数据源(即将其注入到期望javax.sql.DataSource的字段中),但它不是数据源,而是{{1}实现EmbeddedDatabaseFactoryBean

FactoryBean<DataSource>注入entityManagerFactory时,需要调用FactoryBean.getObject(),可能是这样的:

<bean id="entityManagerFactory" class="...">
    <property name="...">
        <bean factory-bean="dataSource" factory-method="getObject" />
    </property>
</bean>