简体   繁体   English

如何在SpringFramework 2中将dataSource注入到jUnit以进行集成测试

[英]How to inject dataSource to jUnit for Integration Testing in SpringFramework 2

I have the following dataSource defined in my spring-beans.xml file which I use in order to connect in my remote database : 我在spring-beans.xml文件中定义了以下dataSource,用于连接远程数据库:

<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">

    <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
    <property name="url" value="jdbc:mysql://localhost:3306/sample"/>
    <property name="username" value="root"/>
    <property name="password" value="root"/>

</bean>

I am building a couple of jUnit integration tests that I want to run. 我正在构建一些我想运行的jUnit集成测试。 Some of the functions that get called from these tests use this datasource in order to access my database. 这些测试中调用的某些功能使用此数据源来访问我的数据库。 When I deploy my project the dataSource is injected according to beans configuration that I have done. 当我部署项目时,数据源是根据我完成的bean配置注入的。

For these tests that will run independently of the web application how can I inject this dataSource in order to access the database ? 对于将独立于Web应用程序运行的这些测试,如何注入此dataSource以便访问数据库?

I use the SpringFramework 2.5.6 version and jUnit4 for my tests. 我使用SpringFramework 2.5.6版本和jUnit4进行测试。

Integration test with Spring 与Spring的集成测试

Sample jUnit Integration test 样本jUnit集成测试

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "spring-beans.xml")
public class MyIntegrationTest {

   @Autowired
   DataSource dataSource;

}

Read more in Spring Framework Reference Documentation > Integration Testing > JDBC Testing Support Spring Framework参考文档 > 集成测试 > JDBC测试支持中了解更多信息

Database testing with Unitils 使用Unitils进行 数据库测试

Unitils greatly reduces this complexity, making database testing easy and maintainable. Unitils大大降低了这种复杂性,使数据库测试变得容易且可维护。

Unitils offers features for unit testing when working with Spring . 当使用Spring时, Unitils提供用于单元测试的功能

public abstract class BaseDAOTest extends UnitilsJUnit4 {

    @TestDataSource
    private DataSource dataSource;

    @Before    
    public void initializeDao() {
        BaseDAO dao = getDaoUnderTest();
        dao.setDataSource(dataSource);
    }

    protected abstract BaseDAO getDaoUnderTest();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM