为了简单性和性能,通常应在集成测试中禁用与 AWS Parameter Store 的集成。相反,从文件加载测试属性(例如,src/test/resources/test.properties)
@SpringBootTest(properties = "aws.paramstore.enabled=false")
@TestPropertySource("classpath:/test.properties")
public class SampleTests {
//...
}
如果个别测试需要检查与 AWS Parameter Store 的集成,请使用 Testcontainers 和 LocalStack 用于 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。