24

我有几个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)

在每个测试课上?

谢谢

4

1 回答 1

36

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

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

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

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

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

于 2014-08-18T10:26:38.217 回答