Spring Cloud应用程序与AWS参数存储的集成测试

时间:2020-03-29 14:08:19

标签: spring amazon-web-services spring-boot spring-cloud aws-parameter-store

如何执行Spring Boot应用程序的集成测试,以从AWS Parameter Store(依赖项org.springframework.cloud:spring-cloud-starter-aws-parameter-store-config)中读取属性。

是否应在集成测试中禁用AWS Parameter Store集成?

如何在集成测试中使用本地服务器(或模拟)代替真正的AWS参数存储?

1 个答案:

答案 0 :(得分:3)

通常应在集成测试中禁用与AWS Parameter Store的集成,以简化操作和提高性能。而是从文件(例如src/test/resources/test.properties)中加载测试属性

@SpringBootTest(properties = "aws.paramstore.enabled=false")
@TestPropertySource("classpath:/test.properties")
public class SampleTests {
  //...
}

如果单个测试需要检查与AWS Parameter Store的集成,请使用TestcontainersLocalStack(适用于Docker的易于使用的本地AWS云堆栈)。

添加一个配置类,以创建类型为ssmClient的自定义AWSSimpleSystemsManagement bean,配置为使用LocalStack而不是使用实际的AWS参数存储在org.springframework.cloud.aws.autoconfigure.paramstore.AwsParamStoreBootstrapConfiguration中声明的默认bean。

@Configuration(proxyBeanMethods = false)
public class AwsParamStoreBootstrapConfiguration {

  public static final LocalStackContainer AWS_SSM_CONTAINER = initContainer();

  public static LocalStackContainer initContainer() {
    LocalStackContainer container = new LocalStackContainer().withServices(SSM);
    container.start();
    Runtime.getRuntime().addShutdownHook(new Thread(container::stop));
    return container;
  }

  @Bean
  public AWSSimpleSystemsManagement ssmClient() {
    return AWSSimpleSystemsManagementClientBuilder.standard()
        .withEndpointConfiguration(AWS_SSM_CONTAINER.getEndpointConfiguration(SSM))
        .withCredentials(AWS_SSM_CONTAINER.getDefaultCredentialsProvider())
        .build();
  }
}

只要AwsParamStorePropertySourceLocator是由Spring Cloud“引导”上下文加载的,您就需要通过将以下条目添加到文件src/test/resources/META-INF/spring.factories中来向引导上下文添加配置类

org.springframework.cloud.bootstrap.BootstrapConfiguration=\
com.example.test.AwsParamStoreBootstrapConfiguration

可以使用相同的方法使用Mockito模拟ssmClient