【问题标题】:Spring @TestConfiguration affecting other test classesSpring @TestConfiguration 影响其他测试类
【发布时间】:2021-12-23 13:16:34
【问题描述】:

我有几个集成测试类,它们都从单个 @Configuration 类导入配置,该类以特定方式创建 externalApi 模拟 bean(出于说明目的,将 true 作为构造函数参数传递):

@Configuration
public class TestConfig {
  
  @Bean
  @Primary
  ExternalApi externalApi() {
    return new MockExternalApi(true); // <-- true by default for all test classes
  }
}

但是对于特定的集成测试类,我需要以不同的方式创建该 bean(假设将 false 作为构造函数参数传递)。为此,我尝试在静态内部类中使用@TestConfiguration,如下所示:

@RunWith(SpringRunner.class)
@SpringBootTest("spring.main.allow-bean-definition-overriding=true")
@Import(TestConfig.class)
@ActiveProfiles("test")
public class ExampleIT {

  @TestConfiguration
  public static class ExternalApiConfig {

    @Bean
    @Primary
    ExternalApi externalApi() {
      return new MockExternalApi(false); // <-- false for this particular test class
    }
  }

  @Test
  public void someTest() {...}
}

但是,当一次执行我的所有集成测试类时(例如,maven verify),所有测试类都在这一次中断之后执行。由于它们共享相同的上下文,似乎在更改该 bean 之后,对于所有后续测试类,它仍然保持更改(即,使用 false 参数)。我尝试在类级别使用@DirtiesContext 来解决这个问题,以便可以为下一个测试类重新加载上下文,但它不起作用。

有没有办法实现我想要做的事情?

注意:如果我将相同的 @TestConfiguration 静态内部类添加到所有其他集成测试类中,则相反,即使用 true arg 创建 externalApi bean,然后他们都工作。但我当然不希望这样做。

【问题讨论】:

  • 对于这个特定的测试删除@Import(TestConfig.class) 怎么样?或者那里有多个bean定义?此外,您能否尝试为这个集成测试命名 externalApi 不同的名称,也许是 innerExternalApi。不知何故,Spring Context 缓存机制必须识别出您在这里使用的是不同的上下文。

标签: java spring spring-boot spring-test


【解决方案1】:

似乎像 Spring runner 中的一个错误; @TestConfiguration 不应该被传播。作为一种解决方法,请尝试将 @DirtiesContext 添加到您的测试中以强制刷新。

【讨论】:

    【解决方案2】:

    这行得通:

    配置类:

    // @TestConfiguration
    // Put this class in a separate file
    // NB! Do not annotate this class with @TestConfiguration,
    // or else the configuration will be propagated to other tests!
    public class UkvServiceTestContextConfiguration {
    

    使用此配置的测试套件:

    @RunWith(SpringRunner.class)
    
    // NB! Do not use a nested static configuration class, use an external configuration class.
    // Nested static configuration class gets propagated to other tests!
    @Import(UkvServiceTestContextConfiguration.class)
    

    公共类 UkvServiceTest {

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-09
      • 2018-07-07
      • 2011-11-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多