我应该在每个类上使用@DirtiesContext吗?

问题描述 投票:0回答:1

我有几个联合测试,

@ContextConfiguration(locations = { "file:../business/src/test/resources/application-context-test.xml",
        "file:src/main/webapp/WEB-INF/confA.xml", "classpath:/mvc-dispatcher-servlet-test.xml"})
@WebAppConfiguration
@RunWith(SpringJUnit4ClassRunner.class)
public class ProductContentControllerTest {
...
}

在类内部,所有测试都必须在相同的上下文中运行(就是这种情况)。

但我希望我所有的测试类都是独立的。 我假设这是默认行为,但是当我一起运行所有测试时,它似乎运行得太快了。

它是如何运作的?每个测试类的应用程序上下文是否只启动一次?

我应该添加:

@DirtiesContext(classMode= ClassMode.AFTER_CLASS)

每个测试班?

spring junit spring-test
1个回答
39
投票

Spring 在运行测试时默认缓存应用程序上下文。 Spring 用于缓存的密钥由以下部分组成:

  • 位置(来自@ContextConfiguration)
  • 类(来自@ContextConfiguration)
  • contextInitializerClasses(来自@ContextConfiguration)
  • contextLoader(来自@ContextConfiguration)
  • activeProfiles(来自@ActiveProfiles)
  • resourceBasePath(来自@WebAppConfiguration)

缓存的所有详细信息都可以在文档中找到。

根据我的经验,很少需要使用

@DirtiesContext
来强制 Spring 重新创建上下文。我还没有遇到太多需要它的情况 - 唯一容易想到的就是使用共享缓存管理器。

您最好仅在绝对需要它的测试中使用它。如果您在每次测试中都使用

@DirtiesContext
,那么执行速度将会太慢,而且您不会得到任何回报。

© www.soinside.com 2019 - 2024. All rights reserved.