【问题标题】:Integration testing of a Spring Cloud application with the AWS Parameter StoreSpring Cloud 应用程序与 AWS Parameter Store 的集成测试
【发布时间】:2020-07-09 22:12:44
【问题描述】:

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

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

如何在集成测试中使用本地服务器(或模拟)而不是真正的 AWS Parameter Store?

【问题讨论】:

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


    【解决方案1】:

    为了简单性和性能,通常应在集成测试中禁用与 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 云堆栈。

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

    @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

    【讨论】:

      猜你喜欢
      • 2019-05-31
      • 2010-11-21
      • 2021-03-22
      • 1970-01-01
      • 2017-08-17
      • 1970-01-01
      • 2017-12-21
      • 1970-01-01
      • 2017-01-17
      相关资源
      最近更新 更多