gpt4 book ai didi

java - 如何为所有测试初始化​​一次 Spring applicationContext

转载 作者:行者123 更新时间:2023-11-29 07:03:06 25 4
gpt4 key购买 nike

我有一组需要 spring 上下文的测试。

为了快速执行测试,我想确保 Spring 上下文只初始化一次,然后所有测试都应该针对这个上下文运行,然后它应该关闭。

我已经尝试过以下方法:

  1. 使用@RunWith(SpringJUnit4ClassRunner.class)@ContextConfiguration(MyAnnotatedConfig.class)初始化spring context
  2. @RunWith(SpringJUnit4ClassRunner.class)@TestExecutionListeners({MyTestExecutionListener.class}) 与手写的测试执行监听器一起使用,该监听器初始化 spring 上下文并注入(inject)它进入具体的测试类
  3. 在基类中使用一个@BeforeClass 监听器和一个静态字段来存储spring 上下文,并使用一个@AfterClass 来关闭

这三种方式,spring context好像都初始化了不止一次,耗费了很多时间。似乎JUnit在运行测试时会卸载类,所以有时会丢失静态字段的内容。

有没有办法确保 spring 上下文只初始化一次?

最佳答案

For fast test execution I want to make sure that the Spring context is initialized just once, then all the tests should be run against this context, then it should shut down.

我不想问显而易见的问题,但是...

你读过Testing chapter of the Spring Reference Manual吗? ?

具体来说,这些部分解释了正在发生的事情:

太棒了,TestContext 框架当然支持在测试套件内 跨测试缓存,我应该知道,因为它是我写的。 ;)

现在至于为什么缓存对您不起作用,我只能假设您已将构建框架配置为针对每个测试进行 fork (或者您正在 IDE 中单独和手动运行测试)。以下是上面最后一个链接的摘录,可能会对您有所帮助:

Test suites and forked processes

The Spring TestContext framework stores application contexts in a static cache. This means that the context is literally stored in a static variable. In other words, if tests execute in separate processes the static cache will be cleared between each test execution, and this will effectively disable the caching mechanism.

To benefit from the caching mechanism, all tests must run within the same process or test suite. This can be achieved by executing all tests as a group within an IDE. Similarly, when executing tests with a build framework such as Ant, Maven, or Gradle it is important to make sure that the build framework does not fork between tests. For example, if the forkMode for the Maven Surefire plug-in is set to always or pertest, the TestContext framework will not be able to cache application contexts between test classes and the build process will run significantly slower as a result.

如果在考虑以上因素后您仍然遇到问题,请考虑 submitting a project这证明了你的问题。

干杯,

山姆

关于java - 如何为所有测试初始化​​一次 Spring applicationContext,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22939226/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com