我在我的弹簧beans.xml的文件中定义的数据源之后,我才能用在我的远程数据库连接:
<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>
我建立了几个,我想运行JUnit集成测试。 有些是那些获得这些测试所调用的函数,以访问我的数据库使用此数据源。 当我部署我的项目的数据源是根据我做了豆子配置注入。
对于这些测试中,我该怎么才能访问数据库注入这个数据源,将独立于Web应用程序的运行?
我用的是2.5.6 springframework的版本和jUnit4对我的测试。
与Spring集成测试
样品JUnit的集成测试
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "spring-beans.xml")
public class MyIntegrationTest {
@Autowired
DataSource dataSource;
}
详情请阅读Spring Framework的参考文档 > 集成测试 > JDBC测试支持
数据库测试与Unitils
Unitils大大降低了这种复杂性,使得数据库测试方便,易于维护。
Unitils提供与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();
}
文章来源: How to inject dataSource to jUnit for Integration Testing in SpringFramework 2