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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25360963/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 00:00:49  来源:igfitidea点击:

spring Should I use @DirtiesContext on every class

springjunitspring-testspring-junit

提问by jpprade

I have several junit tests,

我有几个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 {
...
}

Inside a class all tests have to run in the same context (which is the case).

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

But I want all my tests classes to be independent. I was assuming that it was the default behavior, but when I run all the test together, it seems to run too fast.

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

How does it work? Is the application context started only once for every test class ?

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

Should I add : @DirtiesContext(classMode= ClassMode.AFTER_CLASS)

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

on each test class ?

在每个测试课上?

thanks

谢谢

回答by geoand

Spring caches the application context by default when running tests. The key that Spring uses for the cache is made of the following:

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

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

All the details of the caching can be found in the documentation.

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

In my experience, there is rarely a need to use @DirtiesContextin order to force Spring to recreate the context. I haven't come across too many situations where it's needed - the only one that comes to mind easily is the use of a shared cache manager.

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

You are better using it only on tests that you absolutely positively need it. Execution speed will be far too slow if you use @DirtiesContexton every test and you won't be getting anything in return.

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