【问题标题】:How to inject dataSource to jUnit for Integration Testing in SpringFramework 2如何将数据源注入 jUnit 以在 SpringFramework 2 中进行集成测试
【发布时间】:2014-01-23 00:23:46
【问题描述】:

我在 spring-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 集成测试。从这些测试中调用的一些函数使用这个数据源来访问我的数据库。当我部署我的项目时,数据源是根据我所做的 bean 配置注入的。

对于这些将独立于 Web 应用程序运行的测试,我如何注入此数据源以访问数据库?

我使用 SpringFramework 2.5.6 版本和 jUnit4 进行测试。

【问题讨论】:

  • "SpringFramework 2.5.6" 那是一个相当老的版本..

标签: java spring junit datasource integration-testing


【解决方案1】:

与 Spring 的集成测试

示例 jUnit 集成测试

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

   @Autowired
   DataSource dataSource;

}

阅读更多内容Spring Framework Reference Documentation > Integration Testing > JDBC Testing Support

Database testingUnitils

Unitils 大大降低了这种复杂性,使数据库测试变得简单且可维护。

Unitils 提供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();
}

【讨论】:

  • 正确添加了数据源,但是当我执行测试时,我得到一个:java.lang.NoClassDefFoundError: org/junit/Assume$AssumptionViolatedException ... 这个异常可以指向哪个类?
  • 这看起来像类路径问题 - stackoverflow.com/questions/9874369/…
  • 可能你在类路径上有两个版本的junit,发布新问题并提供更多信息。
  • 好吧,在我的类路径中,我只有一个版本的 junit,版本 4.8.1 ...我在这里读到 stackoverflow.com/questions/12497857/…,该错误的解决方案是降级到 junit 4.4,但是当我这样做时我收到此错误“java.io.FileNotFoundException:类路径资源 [tests/spring-beans.xml] 无法打开,因为它不存在”这真的很奇怪,因为它与我之前的位置相同(相同包含我的测试用例的文件夹)
猜你喜欢
  • 1970-01-01
  • 2022-01-01
  • 2015-08-08
  • 2015-11-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-05-02
  • 2023-03-21
相关资源
最近更新 更多