问题
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