gpt4 book ai didi

multithreading - 与 maven 并行运行 Spring 测试

转载 作者:行者123 更新时间:2023-12-04 04:31:38 24 4
gpt4 key购买 nike

我有一组使用 SpringJUnit4ClassRunner 运行的集成测试.我正在尝试使用 maven surefire 并行运行这些。但是,我注意到代码在进入 CacheAwareContextLoaderDelegate.loadContext() 中的同步块(synchronized block)之前被阻塞了。 .

有没有办法绕过这个缓存?我试过这样做,但似乎有更多的共享状态而不仅仅是缓存本身,因为我的应用程序在 Spring 代码中死锁了。或者可以通过某种方式在 map 键上而不是整个 map 上同步来使同步更加细粒度?

我并行化测试的动机是双重的:

  • 在一些测试中,我用模拟替换了 bean。由于 mock 本质上是有状态的,因此我必须使用 @DirtiesContext 为每个测试方法构建一个新的 ApplicationContext .
  • 在其他测试中,我只想部署 Jersey 资源的一个子集。为此,我指定了 Spring 配置类的一个子集。由于 Spring 使用 MergedContextConfiguration作为上下文缓存中的键,这些测试将无法共享 ApplicationContexts。
  • 最佳答案

    如果禁用并行测试执行,您的测试套件可能会获得更好的周转时间。在 Spring 的引用文档的测试章节中,有一段关于 Context caching :

    Once the TestContext framework loads an ApplicationContext (or WebApplicationContext) for a test, that context will be cached and reused for all subsequent tests that declare the same unique context configuration within the same test suite.


    为什么要这样实现?

    This means that the setup cost for loading an application context is incurred only once (per test suite), and subsequent test execution is much faster.


    缓存是如何工作的?

    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.

    关于multithreading - 与 maven 并行运行 Spring 测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16415234/

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