【问题标题】:Modify the bean created in main application context during Integration test修改集成测试期间在主应用程序上下文中创建的 bean
【发布时间】:2023-04-10 19:30:01
【问题描述】:

在我的 springboot 应用程序中,我正在使用以下类执行集成测试

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = AccountLoadApplication.class,
    loader = SpringApplicationContextLoader.class)
@WebIntegrationTest(randomPort = true)
public class LoaderTest {

AccountLoadApplication.class 是一个 Spring Boot 主类,实际应用程序有一个如下定义的 bean:

  @Bean
  public ResourceLoader recapMvsFileResourceLoader() {
    return new RemoteFileResourceLoader(remoteHostProperties(), new SFTPRemoteFileService());

  }

我还有一个如下所示的测试配置类

@Configuration
public class AtddTestConfig {


  @Bean
  public ResourceLoader mvsFileResourceLoader() {
   ResourceLoader recapMvsFileResourceLoader =
        new RemoteFileResourceLoader(remoteHostProperties(), new FakeSFTPRemoteFileService());
    return recapMvsFileResourceLoader;
  }

我的想法是我想使用测试配置文件中定义的新 bean 覆盖在主应用程序中创建的 bean。

但是在集成测试期间,主应用程序 bean 被考虑而不是测试应用程序上下文中定义的 bean?

还有其他方法可以实现我想要实现的目标吗?

其他信息:

这是我的应用程序配置类中定义的 bean

@Bean
  public RemoteFileService remoteFileService() {
    return new SFTPRemoteFileService();
  }

  @Bean
  public ResourceLoader recapMvsFileResourceLoader() {
    return new RemoteFileResourceLoader(remoteHostProperties(), remoteFileService());

  }

这是我的测试配置类中定义的 bean

  @Bean
  @Profile("local")
  @Primary
  public RemoteFileService remoteFileService() {
    return new FakeSFTPRemoteFileService();
  }

仍然只创建生产 bean 而不是这个主 bean。

【问题讨论】:

    标签: spring-boot spring-test


    【解决方案1】:
    1. 使用@Profile 注解仅在测试上下文中启用测试bean
    2. 在测试 bean 上使用 @Primary 注释,这样 spring 将使用测试 bean 而不是生产 bean。

    Here is my Github repository with working example 使用这种机制。

    【讨论】:

    • 做了同样的事情,但仍然无法在原始帖子的附加信息下添加更多信息
    • 似乎我的问题出在 cucumber jvm 上,正常情况下工作正常,就像您给出的示例一样
    【解决方案2】:

    也许当您将测试配置添加为@ContextConfiguration 的参数时,它可以解决问题,例如

    @ContextConfiguration(classes = {AccountLoadApplication.class, AtddTestConfig.class},
        loader = SpringApplicationContextLoader.class)
    

    【讨论】:

      【解决方案3】:

      除了@luboskrnac 建议的其他更改,您还必须声明@ActiveProfiles;否则,您的 local 个人资料将被忽略。

      @RunWith(SpringJUnit4ClassRunner.class)
      @ActiveProfiles("local")
      @SpringApplicationConfiguration(AccountLoadApplication.class)
      @WebIntegrationTest(randomPort = true)
      public class LoaderTest { /* ... */ }
      

      请注意,以上假设您的 AtddTestConfig 类通过组件扫描被您的 AccountLoadApplication 类拾取。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-06-26
        • 1970-01-01
        • 2019-04-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多