spring引导集成测试autowired接口没有找到这样的bean

gdrx4gfi  于 2021-07-12  发布在  Java
关注(0)|答案(2)|浏览(483)

我有一个springboot应用程序,现在需要支持多个对象存储,并根据环境有选择地使用所需的存储。基本上,我所做的是创建一个接口,然后每个存储库实现这个接口。
我简化了示例的代码。我已经为每个商店类型创建了2个bean,基于spring概要文件来确定env:

@Profile("env1")
  @Bean
  public store1Sdk buildClientStore1() {
     return new store1sdk();
  }

  @Profile("env2")
  @Bean
  public store2Sdk buildClientStore2() {
     return new store2sdk();
  }

在服务层中,我自动连接了接口,然后在存储库中使用@profile指定要使用的接口示例。

public interface ObjectStore {
  String download(String fileObjectKey);
  ...
}

@Service
public class ObjectHandlerService {

  @Autowired
  private ObjectStore objectStore;

  public String getObject(String fileObjectKey) {
    return objectStore.download(fileObjectKey);
  }
  ...
}

@Repository
@Profile("env1")
public class Store1Repository implements ObjectStore {
  @Autowired
  private Store1Sdk store1client;

  public String download(String fileObjectKey) {
    return store1client.getObject(storeName, fileObjectKey);
  }
}

当我用配置好的“env”启动应用程序时,它实际上按预期运行。但是,在运行测试时,我得到了objectstore类型的“no qualification bean”。至少需要1个符合autowire候选条件的bean。“

@ExtendWith({ SpringExtension.class })
@SpringBootTest(classes = Application.class)
@ActiveProfiles("env1,test")
public class ComposerServiceTest {
  @Autowired
  private ObjectHandlerService service;

  @Test
  void download_success() {
    String response = service.getObject("testKey");
    ...
  }
}

正如在test类的@activeprofile中所指出的,还有一些其他的环境,例如dev、test、prod。我尝试过使用component scan,将impl和interface放在同一个包中,等等,但都没有成功。我觉得我错过了一些明显的测试设置。但我的整个应用程序配置可能有问题?我的解决方案的主要目的是避免有一个很长的线

if (store1Sdk != null) {
      store1Sdk.download(fileObjectKey);
    }
    if (store2Sdk != null) {
      store2Sdk.download(fileObjectKey);
    }
9vw9lbht

9vw9lbht1#

尝试 @ActiveProfiles({"env1", "test"}) .
使用激活多个配置文件 @ActiveProfiles 并将配置文件指定为数组。

mm5n2pyu

mm5n2pyu2#

这个问题是因为store1repository的使用 @Profile("env1") ,当您使用 @test ,该类不调用。尝试删除 @Profile("env1")Store1Repository .
如果你使用 @test ,两者 store1Sdk/store2Sdk 不示例化,尝试添加默认值 instanse.eg :

@Bean    
public store2Sdk buildClientStoreDefault() {
    return new store2sdk();
}

相关问题