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

时间:2014-08-18 10:17:24

标签: spring junit 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 {
...
}

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

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

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

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

每个测试类?

感谢

1 个答案:

答案 0 :(得分:26)

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

  • locations(来自@ContextConfiguration)
  • classes(来自@ContextConfiguration)
  • contextInitializerClasses(来自@ContextConfiguration)
  • contextLoader(来自@ContextConfiguration)
  • activeProfiles(来自@ActiveProfiles)
  • resourceBasePath(来自@WebAppConfiguration)

可以在documentation

中找到缓存的所有详细信息

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

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