【问题标题】:Spring + JPA + Hibernate Testing with H2 and @ContextConfiguration使用 H2 和 @ContextConfiguration 进行 Spring + JPA + Hibernate 测试
【发布时间】:2013-09-14 13:10:39
【问题描述】:

我有一个 Spring + JPA + Hibernate 应用程序,我正在尝试通过子类化代码进行测试>AbstractJUnit4SpringContextTests。该类允许使用 @ContextConfiguration 注释指定 Spring 上下文文件。在此文件中,使用 SQL 脚本通过 <jdbc:embedded-database> 元素创建和初始化数据库(模式 + 数据)。

现在我有两个类加载两个不同的 spring 上下文文件,但它们都包含这个元素。如果我单独运行每个测试类,所有测试方法都可以正常工作。但是,如果我从 ant 脚本运行它们,运行的第二个测试会报错,因为数据库已经初始化!这很奇怪,因为我的 Ant JUnit 目标中有 fork="yes" forkmode="perTest"。我不确定为什么会这样。有什么想法吗?

编辑:这是我的 ant 脚本的片段:

<junit printsummary="withOutAndErr" haltonfailure="yes" fork="yes" forkmode="perTest" maxmemory="512m">
  <classpath refid="mvn.classpath"/>
  <classpath location="${classes-core}"/>
  <classpath location="${classes-pentaho}"/>
  <classpath location="${classes-plugins}"/>
  <classpath location="${junit.classes}"/>
  <classpath location="${junit.resources}"/>
  <sysproperty key="ant.home" value="${ant.home}"/>
  <formatter type="xml"/>
  <batchtest fork="yes" todir="${junit.out.dir.xml}">
    <fileset dir="${junit.classes}" includes="**/*TestSuite.class"/>
  </batchtest>
</junit>

谢谢

乔瓦尼

【问题讨论】:

    标签: spring ant junit h2


    【解决方案1】:

    我找到了一个快速而优雅的解决方案。显然 Spring 没有为每个测试重新初始化上下文,所以我的 H2 数据库以某种方式幸存下来。我仍然有点困惑,但在我的测试类中添加以下内容解决了它:

    @DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-02-03
      • 2019-04-01
      • 2017-05-04
      • 2019-05-29
      • 1970-01-01
      • 1970-01-01
      • 2011-12-31
      • 2019-02-02
      相关资源
      最近更新 更多