【问题标题】:how to prevent spring application context from being loaded over and over during unit tests如何防止在单元测试期间反复加载spring应用程序上下文
【发布时间】:2013-08-05 14:12:46
【问题描述】:

我有一个基于 Spring 的 Java EE Web 应用程序。我正在测试我的“存储库”,它们只是使用 junit 的数据访问对象 (DAO)。我使用 maven 来构建和测试我的项目。我的单元测试示例如下所示:

@ContextConfiguration(locations = {"classpath:spring/business-objects.xml"})
@RunWith(SpringJUnit4ClassRunner.class)
public class JpaUserRepositoryTests {
 @AutoWired
 UserRepository userRepository;

 @Test
 @Transactional
 public void testCreate() {
  boolean result = userRepository.create(new User("name","pass"));
  Assert.assertTrue(result);
 }
}

我的 maven-surefire-plugin 配置如下所示。

<plugin>
 <groupId>org.apache.maven.plugins</groupId>
 <artifactId>maven-surefire-plugin</artifactId>
 <version>2.13</version>
 <configuration>
  <includes>
   <include>**/*Tests.java</include>
  </includes>
 </configuration>
</plugin>

我的问题是我有多个存储库测试,每次运行“mvn clean test”时,对于每个存储库测试类,都会一遍又一遍地加载 spring 应用程序上下文。有什么方法可以配置我的测试,以便我的所有存储库测试只加载一次 Spring 应用程序上下文?

【问题讨论】:

    标签: spring maven junit


    【解决方案1】:

    是的,设置选项 forkMode=once (目前,在 2.15 版本中,此选项已经默认为“一次”。我不知道从什么时候开始,但我知道它是“总是”在早期版本中)。

    【讨论】:

    • 谢谢,我想就是这样。我只是从 2.13 更新到 2.15。
    【解决方案2】:

    很奇怪,spring有一个singleton用来缓存上下文进行测试,只要你使用相同的上下文配置,spring就会重用上下文(see docs

    我能想象的唯一两个选择是,您使用的是旧版本的 spring,它没有此功能(我不确定何时引入此功能,但我认为大约是 2.5 版。 x)

    另一种选择是您的项目继承自 maven pom,该 pom 将 Surefire 配置为使用 forkMode=always,这将为每个测试类生成一个新的 jvm。

    我不知道其他哪种情况可能会导致这种情况...希望以上内容有所帮助。

    【讨论】:

    • 我正在使用 spring-framework.version=3.2.2.RELEASE 和 spring-data-jpa.version=1.3.1.RELEASE。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-23
    • 2013-02-03
    • 1970-01-01
    • 2018-07-11
    • 2014-02-28
    • 2020-02-25
    相关资源
    最近更新 更多