下面列出了怎么用org.springframework.boot.test.util.TestPropertyValues的API类实例代码及写法,或者点击链接到github查看源代码。
@Test
public void kinesisCollectorCreatedWhenAllRequiredValuesAreProvided() {
TestPropertyValues.of(
"zipkin.collector.kinesis.stream-name: zipkin-test",
// The yaml file has a default for this
"zipkin.collector.kinesis.app-name: zipkin")
.applyTo(context);
context.register(
PropertyPlaceholderAutoConfiguration.class,
ZipkinKinesisCollectorModule.class,
ZipkinKinesisCredentialsConfiguration.class,
InMemoryConfiguration.class);
context.refresh();
assertThat(context.getBean(KinesisCollector.class)).isNotNull();
assertThat(context.getBean(ZipkinKinesisCollectorProperties.class)).isNotNull();
}
@Test
public void sunnyDayWithNoSuchLabelAndFailFast() {
ConfigClientProperties defaults = new ConfigClientProperties(this.environment);
defaults.setFailFast(true);
this.locator = new ConfigServicePropertySourceLocator(defaults);
mockRequestResponseWithLabel(
new ResponseEntity<>((Void) null, HttpStatus.NOT_FOUND),
"release(_)v1.0.0");
this.locator.setRestTemplate(this.restTemplate);
TestPropertyValues.of("spring.cloud.config.label:release/v1.0.1")
.applyTo(this.environment);
this.expected.expect(IsInstanceOf.instanceOf(IllegalStateException.class));
this.expected.expectMessage(
"Could not locate PropertySource and the fail fast property is set, failing: None of labels [release/v1.0.1] found");
this.locator.locateCollection(this.environment);
}
@Test
public void usingUserWithViewRolesWithOauth() {
context = new AnnotationConfigApplicationContext();
TestPropertyValues.of(
"spring.cloud.dataflow.client.server-uri=" + "http://localhost:"
+ localDataflowResource.getDataflowPort(),
"spring.cloud.dataflow.client.authentication.client-id=myclient",
"spring.cloud.dataflow.client.authentication.client-secret=mysecret",
"spring.cloud.dataflow.client.authentication.token-uri=" + "http://localhost:"
+ oAuth2ServerResource.getOauth2ServerPort() + "/oauth/token",
"spring.cloud.dataflow.client.authentication.scope=dataflow.view").applyTo(context);
context.register(TestApplication2.class);
context.refresh();
final DataFlowOperations dataFlowOperations = context.getBean(DataFlowOperations.class);
final AboutResource about = dataFlowOperations.aboutOperation().get();
assertNotNull(about);
assertEquals("myclient", about.getSecurityInfo().getUsername());
assertEquals(1, about.getSecurityInfo().getRoles().size());
}
@Test
public void shouldReadNewPrefixesPropertyAndIncludeOldPrefixProperty() {
this.context.register(EnableAutoConfig.class);
TestPropertyValues
.of("edison.application.management.base-path=/internal")
.and("edison.ldap.enabled=true")
.and("edison.ldap.host=localhost")
.and("edison.ldap.rdn-identifier=test-rdn")
.and("edison.ldap.base-dn=test-dn")
.and("edison.ldap.prefix=/deprecatedTestPrefix")
.and("edison.ldap.prefixes=/newTestPrefix")
.applyTo(context);
this.context.refresh();
final FilterRegistrationBean<?> filterRegistrationBean = this.context.getBean("ldapAuthenticationFilter", FilterRegistrationBean.class);
final ArrayList<String> urlPatterns = new ArrayList<String>(filterRegistrationBean.getUrlPatterns());
assertThat(urlPatterns, hasSize(2));
assertThat(urlPatterns, containsInAnyOrder("/deprecatedTestPrefix/*", "/newTestPrefix/*"));
}
@Test
public void testOnlyDecryptIfNotOverridden() {
ConfigurableApplicationContext context = new AnnotationConfigApplicationContext();
TextEncryptor encryptor = mock(TextEncryptor.class);
when(encryptor.decrypt("bar2")).thenReturn("bar2");
EnvironmentDecryptApplicationInitializer initializer = new EnvironmentDecryptApplicationInitializer(
encryptor);
TestPropertyValues.of("foo: {cipher}bar", "foo2: {cipher}bar2").applyTo(context);
context.getEnvironment().getPropertySources().addFirst(new MapPropertySource(
"test_override", Collections.singletonMap("foo", "spam")));
initializer.initialize(context);
then(context.getEnvironment().getProperty("foo")).isEqualTo("spam");
then(context.getEnvironment().getProperty("foo2")).isEqualTo("bar2");
verify(encryptor).decrypt("bar2");
verifyNoMoreInteractions(encryptor);
}
@Override
public void initialize(ConfigurableApplicationContext configurableApplicationContext) {
WireMockServer wireMockServer = new WireMockServer(new WireMockConfiguration().dynamicPort());
wireMockServer.start();
configurableApplicationContext.getBeanFactory().registerSingleton("wireMockServer", wireMockServer);
configurableApplicationContext.addApplicationListener(applicationEvent -> {
if (applicationEvent instanceof ContextClosedEvent) {
wireMockServer.stop();
}
});
TestPropertyValues
.of("todo_url:http://localhost:" + wireMockServer.port() + "/todos")
.applyTo(configurableApplicationContext);
}
@Test
public void shouldThrowExceptionOnMissingBucket() {
//given
when(mock.listObjects(any(ListObjectsRequest.class))).thenThrow(NoSuchBucketException.builder().build());
this.context.register(TogglzAutoConfiguration.class);
this.context.register(S3TestConfiguration.class);
TestPropertyValues
.of("edison.togglz.s3.enabled=true")
.and("edison.togglz.s3.bucket-name=togglz-bucket")
.and("edison.togglz.s3.check-bucket=true")
.applyTo(context);
//expect
Assertions.assertThrows(BeanCreationException.class, this.context::refresh);
}
@Test
public void kinesisCollectorConfiguredForAWSWithGivenCredentials() {
TestPropertyValues.of(
"zipkin.collector.kinesis.stream-name: zipkin-test",
"zipkin.collector.kinesis.app-name: zipkin",
"zipkin.collector.kinesis.aws-sts-region: us-east-1",
"zipkin.collector.kinesis.aws-access-key-id: x",
"zipkin.collector.kinesis.aws-secret-access-key: x",
"zipkin.collector.kinesis.aws-sts-role-arn: test")
.applyTo(context);
context.register(
PropertyPlaceholderAutoConfiguration.class,
ZipkinKinesisCollectorModule.class,
ZipkinKinesisCredentialsConfiguration.class,
InMemoryConfiguration.class);
context.refresh();
assertThat(context.getBean(KinesisCollector.class)).isNotNull();
assertThat(context.getBean(AWSSecurityTokenService.class)).isNotNull();
assertThat(context.getBean(AWSCredentialsProvider.class))
.isInstanceOf(STSAssumeRoleSessionCredentialsProvider.class);
}
@Test
@DirtiesContext
public void testRefresh() throws Exception {
then(this.service.getMessage()).isEqualTo("Hello scope!");
String id1 = this.service.toString();
// Change the dynamic property source...
TestPropertyValues.of("message:Foo").applyTo(this.environment, Type.MAP,
"morerefreshtests");
// ...and then refresh, so the bean is re-initialized:
this.scope.refreshAll();
String id2 = this.service.toString();
String message = this.service.getMessage();
then(message).isEqualTo("Foo");
then(TestService.getInitCount()).isEqualTo(1);
then(TestService.getDestroyCount()).isEqualTo(1);
then(id2).isNotSameAs(id1);
}
@Test
public void testAuthorizationServerOverride() {
this.context = new AnnotationConfigServletWebServerApplicationContext();
TestPropertyValues.of("security.oauth2.resourceId:resource-id").applyTo(this.context);
this.context.register(AuthorizationAndResourceServerConfiguration.class, CustomAuthorizationServer.class,
MinimalSecureWebApplication.class);
this.context.refresh();
BaseClientDetails config = new BaseClientDetails();
config.setClientId("client");
config.setClientSecret("secret");
config.setResourceIds(Arrays.asList("resource-id"));
config.setAuthorizedGrantTypes(Arrays.asList("password"));
config.setAuthorities(AuthorityUtils.commaSeparatedStringToAuthorityList("USER"));
config.setScope(Arrays.asList("read"));
assertThat(countBeans(AUTHORIZATION_SERVER_CONFIG)).isEqualTo(1);
assertThat(countBeans(CustomAuthorizationServer.class)).isEqualTo(1);
assertThat(countBeans(RESOURCE_SERVER_CONFIG)).isEqualTo(1);
verifyAuthentication(config);
}
@Test
public void statusPageUrl_and_healthCheckUrl_contain_management_context_path()
throws Exception {
TestPropertyValues
.of("server.port=8989",
"management.server.servlet.context-path=/management")
.applyTo(this.context);
setupContext(RefreshAutoConfiguration.class);
EurekaInstanceConfigBean instance = this.context
.getBean(EurekaInstanceConfigBean.class);
assertThat(instance.getStatusPageUrl().endsWith(":8989/management/actuator/info"))
.as("Wrong status page: " + instance.getStatusPageUrl()).isTrue();
assertThat(
instance.getHealthCheckUrl().endsWith(":8989/management/actuator/health"))
.as("Wrong health check: " + instance.getHealthCheckUrl())
.isTrue();
}
@Override
public void initialize(ConfigurableApplicationContext configurableApplicationContext) {
final ServerControls serverControls = TestServerBuilders.newInProcessBuilder().newServer();
configurableApplicationContext
.addApplicationListener((ApplicationListener<ContextClosedEvent>) event -> serverControls.close());
TestPropertyValues.of(
"org.neo4j.driver.uri=" + serverControls.boltURI().toString()
).applyTo(configurableApplicationContext.getEnvironment());
}
@Test
public void consulConfigNotLoadedWhenDiscoveryClientDisabled() {
TestPropertyValues.of("spring.cloud.discovery.enabled=false")
.applyTo(this.context);
setupContext();
assertBeanNotPresent(ConsulDiscoveryProperties.class);
assertBeanNotPresent(ConsulDiscoveryClient.class);
assertBeanNotPresent(HeartbeatProperties.class);
}
@Override
public void initialize(ConfigurableApplicationContext configurableApplicationContext) {
final Neo4jContainer<?> neo4jContainer = new Neo4jContainer<>("neo4j:4.0").withoutAuthentication();
neo4jContainer.start();
configurableApplicationContext
.addApplicationListener((ApplicationListener<ContextClosedEvent>) event -> neo4jContainer.stop());
TestPropertyValues.of("org.neo4j.driver.uri=" + neo4jContainer.getBoltUrl())
.applyTo(configurableApplicationContext.getEnvironment());
}
@Test void doesNotProvidesStorageComponent_whenStorageTypeNotKafka() {
TestPropertyValues.of("zipkin.storage.type:elasticsearch").applyTo(context);
Access.registerKafka(context);
context.refresh();
assertThatThrownBy(() -> context.getBean(KafkaStorage.class))
.isInstanceOf(NoSuchBeanDefinitionException.class);
}
@Test
public void sunnyDayWithLabelThatContainsASlash() {
Environment body = new Environment("app", "master");
mockRequestResponseWithLabel(new ResponseEntity<>(body, HttpStatus.OK),
"release(_)v1.0.0");
this.locator.setRestTemplate(this.restTemplate);
TestPropertyValues.of("spring.cloud.config.label:release/v1.0.0")
.applyTo(this.environment);
assertThat(this.locator.locateCollection(this.environment)).isNotNull();
}
private SanitizingEurekaInstanceConfigBean createBeanWithProps(String... pairs) {
this.ctx = new AnnotationConfigApplicationContext();
List<String> pairs1 = new ArrayList<>(Arrays.asList(pairs));
pairs1.add("sanitizingEurekaInstanceConfigBean.integration.test:true");
pairs1.add("eureka.client.enabled:false");
TestPropertyValues.of(pairs1).applyTo(ctx);
this.ctx.register(Context.class);
this.ctx.refresh();
return this.ctx.getBean(SanitizingEurekaInstanceConfigBean.class);
}
@Test
void placeHolder_customValueSeparator_createInstanceDataResolverThatResolvesWithCustomValueSeparator()
throws Exception {
// Arrange
HttpServer httpServer = MetaDataServer.setupHttpServer();
HttpContext instanceIdHttpContext = httpServer.createContext(
"/latest/meta-data/instance-id",
new MetaDataServer.HttpResponseWriterHandler("testInstanceId"));
HttpContext userDataHttpContext = httpServer.createContext("/latest/user-data",
new MetaDataServer.HttpResponseWriterHandler("a=b;c=d"));
this.context = new AnnotationConfigApplicationContext();
TestPropertyValues.of("cloud.aws.instance.data.valueSeparator:=")
.applyTo(this.context);
this.context.register(ContextInstanceDataAutoConfiguration.class);
// Act
this.context.refresh();
// Assert
assertThat(this.context.getEnvironment().getProperty("a")).isEqualTo("b");
assertThat(this.context.getEnvironment().getProperty("c")).isEqualTo("d");
httpServer.removeContext(instanceIdHttpContext);
httpServer.removeContext(userDataHttpContext);
}
@Test void canOverridesProperty_aggregationStreamConfigs() {
TestPropertyValues.of(
"zipkin.storage.type:kafka",
"zipkin.storage.kafka.span-aggregation.overrides.application.id:agg1"
).applyTo(context);
Access.registerKafka(context);
context.refresh();
assertThat(context.getBean(KafkaStorage.class)
.aggregationStreamConfig.get(StreamsConfig.APPLICATION_ID_CONFIG))
.isEqualTo("agg1");
}
@Test void canOverridesProperty_traceStoreStreamConfigs() {
TestPropertyValues.of(
"zipkin.storage.type:kafka",
"zipkin.storage.kafka.trace-storage.overrides.application.id:store1"
).applyTo(context);
Access.registerKafka(context);
context.refresh();
assertThat(context.getBean(KafkaStorage.class)
.traceStoreStreamConfig.getProperty(StreamsConfig.APPLICATION_ID_CONFIG))
.isEqualTo("store1");
}
@Test
@DirtiesContext
public void testUpdateHikari() throws Exception {
then(this.properties.getMessage()).isEqualTo("Hello scope!");
TestPropertyValues.of("spring.datasource.hikari.read-only=true")
.applyTo(this.environment);
// ...and then refresh, so the bean is re-initialized:
this.refresher.refresh();
then(this.properties.getMessage()).isEqualTo("Hello scope!");
}
@Test
public void shouldUseInMemoryStateRepositoryIfMongoDisabled() {
this.context.register(MongoTogglzTestConfiguration.class);
TestPropertyValues
.of("edison.togglz.mongo.enabled=false")
.and("edison.mongo.db=db")
.and("edison.mongo.user=test")
.and("edison.mongo.password=test")
.applyTo(context);
this.context.refresh();
assertThat(this.context.containsBean("stateRepository"), is(true));
assertThat(this.context.getBean("stateRepository", StateRepository.class), is(instanceOf(InMemoryStateRepository.class)));
}
@Test void canOverridesProperty_aggregationSpansTopic() {
TestPropertyValues.of(
"zipkin.storage.type:kafka",
"zipkin.storage.kafka.span-aggregation.spans-topic:zipkin-spans-1"
).applyTo(context);
Access.registerKafka(context);
context.refresh();
assertThat(context.getBean(KafkaStorage.class).aggregationSpansTopic).isEqualTo(
"zipkin-spans-1");
}
@Test
public void eurekaConfigNotLoadedWhenDiscoveryClientDisabled() {
TestPropertyValues.of("spring.cloud.discovery.enabled=false")
.applyTo(this.context);
setupContext(TestConfiguration.class);
assertBeanNotPresent(EurekaClientConfigBean.class);
assertBeanNotPresent(EurekaInstanceConfigBean.class);
assertBeanNotPresent(DiscoveryClient.class);
assertBeanNotPresent(EurekaServiceRegistry.class);
assertBeanNotPresent(EurekaClient.class);
assertBeanNotPresent(EurekaDiscoveryClientConfiguration.Marker.class);
}
@Test void canOverridesProperty_storageSpansTopic() {
TestPropertyValues.of(
"zipkin.storage.type:kafka",
"zipkin.storage.kafka.trace-storage.spans-topic:zipkin-spans-1"
).applyTo(context);
Access.registerKafka(context);
context.refresh();
assertThat(context.getBean(KafkaStorage.class).storageSpansTopic)
.isEqualTo("zipkin-spans-1");
}
@Test void canOverridesProperty_storageDependencyTopic() {
TestPropertyValues.of(
"zipkin.storage.type:kafka",
"zipkin.storage.kafka.dependency-storage.dependency-topic:zipkin-dependencies-1"
).applyTo(context);
Access.registerKafka(context);
context.refresh();
assertThat(context.getBean(KafkaStorage.class).storageDependencyTopic)
.isEqualTo("zipkin-dependencies-1");
}
@Test
public void shouldDisableEndpoint() {
TestPropertyValues.of("endpoints.someTest.enabled=true").applyTo(ctx);
ctx.register(TestEndpointConfiguration.class);
ctx.register(RemoveTestEndpointConfiguration.class);
ctx.refresh();
assertThat(ctx.getEnvironment().getProperty("endpoints.someTest.enabled"), is("false"));
}
@Test
public void addClientIdUnderscores() {
TestPropertyValues.of("vcap.services.sso.credentials.client-id:foo")
.applyTo(this.environment);
this.listener.postProcessEnvironment(this.environment, new SpringApplication());
assertThat(this.environment
.resolvePlaceholders("${security.oauth2.client.client-id}"))
.isEqualTo("foo");
}
@Test
@DirtiesContext
public void testReplaceProperties() throws Exception {
then("[one, two]").isEqualTo(this.properties.getMessages().toString());
then(this.properties instanceof Advised).isTrue();
Map<String, Object> map = findTestProperties();
map.clear();
TestPropertyValues.of("test.messages[0]:foo").applyTo(this.environment);
this.scope.refreshAll();
then(this.properties.getMessages().toString()).isEqualTo("[foo]");
}
@Before
public void init() {
TestPropertyValues.of(
"kafka.consumer.bootstrap.servers=" + bootstrapServers(kafka),
"webhook.url=http://localhost:" + webhook.getPort() + "/hook"
).applyTo(this.context);
context.register(PropertyPlaceholderAutoConfiguration.class, NotifierConfig.class, Notifier.class);
context.refresh();
notifier = context.getBean(Notifier.class);
notifierConfig = context.getBean(NotifierConfig.class);
}