How to inject dataSource to jUnit for Integration Testing in SpringFramework 2

给你一囗甜甜゛ 提交于 2019-12-11 15:39:36

问题


I have the following dataSource defined in my spring-beans.xml file which I use in order to connect in my remote database :

<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. 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.

For these tests that will run independently of the web application how can I inject this dataSource in order to access the database ?

I use the SpringFramework 2.5.6 version and jUnit4 for my tests.


回答1:


Integration test with Spring

Sample jUnit Integration test

@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

Database testing with Unitils

Unitils greatly reduces this complexity, making database testing easy and maintainable.

Unitils offers features for unit testing when working with Spring.

public abstract class BaseDAOTest extends UnitilsJUnit4 {

    @TestDataSource
    private DataSource dataSource;

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

    protected abstract BaseDAO getDaoUnderTest();
}


来源:https://stackoverflow.com/questions/20935729/how-to-inject-datasource-to-junit-for-integration-testing-in-springframework-2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!