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

jpp*_*ade 19 junit spring spring-test spring-junit

我有几个junit测试,

@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 {
...
}
Run Code Online (Sandbox Code Playgroud)

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

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

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

我应该添加:@DirtiesContext(classMode = ClassMode.AFTER_CLASS)

在每个测试类?

谢谢

geo*_*and 32

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

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

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

根据我的经验,很少需要使用@DirtiesContext以强制Spring重新创建上下文.我没有遇到需要的太多情况 - 唯一容易想到的是使用共享缓存管理器.

你最好只在你绝对需要的测试中使用它.如果您@DirtiesContext在每次测试中使用,执行速度将太慢,并且您将无法获得任何回报.

  • 我有一个相反的问题,我什么都没用,但是我为每个测试创建了spring上下文,我在做什么错呢? (2认同)