2016-12-01 5 views
0

私のアプリの単体テストを作成しようとしています。テストは、SQLファイルからデータを使用する必要があります。Spring + Hibernate + TestNG + Mockitoはjavax.sql.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> 

:Mavenは私exeption

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

休止DataSource設定を提供します

答えが見つからないか、適切な例が見つかりません。そして、最も重要なのは、私がテストを削除すると、アプリは正常に動作します。

UPDATE

スタックトレース

https://jpst.it/PY4v

+0

正確に例外が起こるのでしょうか?スタックトレースと関連するコードを表示してください。 –

答えて

0

、あなたがデータソースとしてID dataSourceでBeanを使用しようとしている(つまり、あなたが期待してフィールドjavax.sql.DataSourceにそれを注入)が、これはデータソースではなく、EmbeddedDatabaseFactoryBeanで、FactoryBean<DataSource>を実装しています。

あなたは、おそらくこのような何かによって、 entityManagerFactory Beanにそれを注入する際 FactoryBean.getObject()を呼び出す必要があり

<bean id="entityManagerFactory" class="..."> 
    <property name="..."> 
     <bean factory-bean="dataSource" factory-method="getObject" /> 
    </property> 
</bean> 
関連する問題