pull/9725/merge
Phillip Webb 7 years ago
parent eac4c7e882
commit a869d25dbb

@ -59,7 +59,7 @@ public class SpringApplicationAdminJmxAutoConfigurationTests {
@Rule @Rule
public final ExpectedException thrown = ExpectedException.none(); public final ExpectedException thrown = ExpectedException.none();
private final MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer(); private final MBeanServer server = ManagementFactory.getPlatformMBeanServer();
private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() private final ApplicationContextRunner contextRunner = new ApplicationContextRunner()
.withConfiguration(AutoConfigurations.of(JmxAutoConfiguration.class, .withConfiguration(AutoConfigurations.of(JmxAutoConfiguration.class,
@ -70,7 +70,7 @@ public class SpringApplicationAdminJmxAutoConfigurationTests {
throws MalformedObjectNameException, InstanceNotFoundException { throws MalformedObjectNameException, InstanceNotFoundException {
this.contextRunner.run((context) -> { this.contextRunner.run((context) -> {
this.thrown.expect(InstanceNotFoundException.class); this.thrown.expect(InstanceNotFoundException.class);
this.mBeanServer.getObjectInstance(createDefaultObjectName()); this.server.getObjectInstance(createDefaultObjectName());
}); });
} }
@ -78,7 +78,7 @@ public class SpringApplicationAdminJmxAutoConfigurationTests {
public void registeredWithProperty() throws Exception { public void registeredWithProperty() throws Exception {
this.contextRunner.withPropertyValues(ENABLE_ADMIN_PROP).run((context) -> { this.contextRunner.withPropertyValues(ENABLE_ADMIN_PROP).run((context) -> {
ObjectName objectName = createDefaultObjectName(); ObjectName objectName = createDefaultObjectName();
ObjectInstance objectInstance = this.mBeanServer.getObjectInstance(objectName); ObjectInstance objectInstance = this.server.getObjectInstance(objectName);
assertThat(objectInstance).as("Lifecycle bean should have been registered") assertThat(objectInstance).as("Lifecycle bean should have been registered")
.isNotNull(); .isNotNull();
}); });
@ -87,18 +87,20 @@ public class SpringApplicationAdminJmxAutoConfigurationTests {
@Test @Test
public void registerWithCustomJmxName() throws InstanceNotFoundException { public void registerWithCustomJmxName() throws InstanceNotFoundException {
String customJmxName = "org.acme:name=FooBar"; String customJmxName = "org.acme:name=FooBar";
this.contextRunner.withSystemProperties( this.contextRunner
"spring.application.admin.jmx-name=" + customJmxName) .withSystemProperties(
"spring.application.admin.jmx-name=" + customJmxName)
.withPropertyValues(ENABLE_ADMIN_PROP).run((context) -> { .withPropertyValues(ENABLE_ADMIN_PROP).run((context) -> {
try { try {
this.mBeanServer.getObjectInstance(createObjectName(customJmxName)); this.server.getObjectInstance(createObjectName(customJmxName));
} }
catch (InstanceNotFoundException ex) { catch (InstanceNotFoundException ex) {
fail("Admin MBean should have been exposed with custom name"); fail("Admin MBean should have been exposed with custom name");
} }
this.thrown.expect(InstanceNotFoundException.class); // Should not be exposed this.thrown.expect(InstanceNotFoundException.class); // Should not be
this.mBeanServer.getObjectInstance(createDefaultObjectName()); // exposed
}); this.server.getObjectInstance(createDefaultObjectName());
});
} }
@Test @Test
@ -110,7 +112,7 @@ public class SpringApplicationAdminJmxAutoConfigurationTests {
SpringApplicationAdminJmxAutoConfiguration.class) SpringApplicationAdminJmxAutoConfiguration.class)
.run("--" + ENABLE_ADMIN_PROP, "--server.port=0")) { .run("--" + ENABLE_ADMIN_PROP, "--server.port=0")) {
assertThat(context).isInstanceOf(ServletWebServerApplicationContext.class); assertThat(context).isInstanceOf(ServletWebServerApplicationContext.class);
assertThat(this.mBeanServer.getAttribute(createDefaultObjectName(), assertThat(this.server.getAttribute(createDefaultObjectName(),
"EmbeddedWebApplication")).isEqualTo(Boolean.TRUE); "EmbeddedWebApplication")).isEqualTo(Boolean.TRUE);
int expected = ((ServletWebServerApplicationContext) context).getWebServer() int expected = ((ServletWebServerApplicationContext) context).getWebServer()
.getPort(); .getPort();
@ -128,11 +130,10 @@ public class SpringApplicationAdminJmxAutoConfigurationTests {
.child(JmxAutoConfiguration.class, .child(JmxAutoConfiguration.class,
SpringApplicationAdminJmxAutoConfiguration.class) SpringApplicationAdminJmxAutoConfiguration.class)
.web(WebApplicationType.NONE); .web(WebApplicationType.NONE);
try (ConfigurableApplicationContext parent = parentBuilder try (ConfigurableApplicationContext parent = parentBuilder
.run("--" + ENABLE_ADMIN_PROP); .run("--" + ENABLE_ADMIN_PROP);
ConfigurableApplicationContext child = childBuilder ConfigurableApplicationContext child = childBuilder
.run("--" + ENABLE_ADMIN_PROP)) { .run("--" + ENABLE_ADMIN_PROP)) {
BeanFactoryUtils.beanOfType(parent.getBeanFactory(), BeanFactoryUtils.beanOfType(parent.getBeanFactory(),
SpringApplicationAdminMXBeanRegistrar.class); SpringApplicationAdminMXBeanRegistrar.class);
this.thrown.expect(NoSuchBeanDefinitionException.class); this.thrown.expect(NoSuchBeanDefinitionException.class);
@ -155,7 +156,7 @@ public class SpringApplicationAdminJmxAutoConfigurationTests {
} }
private String getProperty(ObjectName objectName, String key) throws Exception { private String getProperty(ObjectName objectName, String key) throws Exception {
return (String) this.mBeanServer.invoke(objectName, "getProperty", return (String) this.server.invoke(objectName, "getProperty",
new Object[] { key }, new String[] { String.class.getName() }); new Object[] { key }, new String[] { String.class.getName() });
} }

@ -77,25 +77,29 @@ public class RabbitAutoConfigurationTests {
@Test @Test
public void testDefaultRabbitConfiguration() { public void testDefaultRabbitConfiguration() {
this.contextRunner this.contextRunner.withUserConfiguration(TestConfiguration.class)
.withUserConfiguration(TestConfiguration.class).run((context) -> { .run((context) -> {
RabbitTemplate rabbitTemplate = context.getBean(RabbitTemplate.class); RabbitTemplate rabbitTemplate = context.getBean(RabbitTemplate.class);
RabbitMessagingTemplate messagingTemplate = context RabbitMessagingTemplate messagingTemplate = context
.getBean(RabbitMessagingTemplate.class); .getBean(RabbitMessagingTemplate.class);
CachingConnectionFactory connectionFactory = context CachingConnectionFactory connectionFactory = context
.getBean(CachingConnectionFactory.class); .getBean(CachingConnectionFactory.class);
DirectFieldAccessor dfa = new DirectFieldAccessor(connectionFactory); DirectFieldAccessor dfa = new DirectFieldAccessor(connectionFactory);
RabbitAdmin amqpAdmin = context.getBean(RabbitAdmin.class); RabbitAdmin amqpAdmin = context.getBean(RabbitAdmin.class);
assertThat(rabbitTemplate.getConnectionFactory()).isEqualTo(connectionFactory); assertThat(rabbitTemplate.getConnectionFactory())
assertThat(getMandatory(rabbitTemplate)).isFalse(); .isEqualTo(connectionFactory);
assertThat(messagingTemplate.getRabbitTemplate()).isEqualTo(rabbitTemplate); assertThat(getMandatory(rabbitTemplate)).isFalse();
assertThat(amqpAdmin).isNotNull(); assertThat(messagingTemplate.getRabbitTemplate())
assertThat(connectionFactory.getHost()).isEqualTo("localhost"); .isEqualTo(rabbitTemplate);
assertThat(dfa.getPropertyValue("publisherConfirms")).isEqualTo(false); assertThat(amqpAdmin).isNotNull();
assertThat(dfa.getPropertyValue("publisherReturns")).isEqualTo(false); assertThat(connectionFactory.getHost()).isEqualTo("localhost");
assertThat(context.containsBean("rabbitListenerContainerFactory")) assertThat(dfa.getPropertyValue("publisherConfirms"))
.as("Listener container factory should be created by default").isTrue(); .isEqualTo(false);
}); assertThat(dfa.getPropertyValue("publisherReturns")).isEqualTo(false);
assertThat(context.containsBean("rabbitListenerContainerFactory"))
.as("Listener container factory should be created by default")
.isTrue();
});
} }
@Test @Test
@ -105,38 +109,39 @@ public class RabbitAutoConfigurationTests {
"spring.rabbitmq.port:9000", "spring.rabbitmq.username:alice", "spring.rabbitmq.port:9000", "spring.rabbitmq.username:alice",
"spring.rabbitmq.password:secret", "spring.rabbitmq.password:secret",
"spring.rabbitmq.virtual_host:/vhost", "spring.rabbitmq.virtual_host:/vhost",
"spring.rabbitmq.connection-timeout:123").run((context) -> { "spring.rabbitmq.connection-timeout:123")
CachingConnectionFactory connectionFactory = context .run((context) -> {
.getBean(CachingConnectionFactory.class); CachingConnectionFactory connectionFactory = context
assertThat(connectionFactory.getHost()).isEqualTo("remote-server"); .getBean(CachingConnectionFactory.class);
assertThat(connectionFactory.getPort()).isEqualTo(9000); assertThat(connectionFactory.getHost()).isEqualTo("remote-server");
assertThat(connectionFactory.getVirtualHost()).isEqualTo("/vhost"); assertThat(connectionFactory.getPort()).isEqualTo(9000);
DirectFieldAccessor dfa = new DirectFieldAccessor(connectionFactory); assertThat(connectionFactory.getVirtualHost()).isEqualTo("/vhost");
com.rabbitmq.client.ConnectionFactory rcf = (com.rabbitmq.client.ConnectionFactory) dfa DirectFieldAccessor dfa = new DirectFieldAccessor(connectionFactory);
.getPropertyValue("rabbitConnectionFactory"); com.rabbitmq.client.ConnectionFactory rcf = (com.rabbitmq.client.ConnectionFactory) dfa
assertThat(rcf.getConnectionTimeout()).isEqualTo(123); .getPropertyValue("rabbitConnectionFactory");
assertThat((Address[]) dfa.getPropertyValue("addresses")).hasSize(1); assertThat(rcf.getConnectionTimeout()).isEqualTo(123);
}); assertThat((Address[]) dfa.getPropertyValue("addresses")).hasSize(1);
});
} }
@Test @Test
public void testConnectionFactoryEmptyVirtualHost() { public void testConnectionFactoryEmptyVirtualHost() {
this.contextRunner.withUserConfiguration(TestConfiguration.class) this.contextRunner.withUserConfiguration(TestConfiguration.class)
.withPropertyValues("spring.rabbitmq.virtual_host:").run((context) -> { .withPropertyValues("spring.rabbitmq.virtual_host:").run((context) -> {
CachingConnectionFactory connectionFactory = context CachingConnectionFactory connectionFactory = context
.getBean(CachingConnectionFactory.class); .getBean(CachingConnectionFactory.class);
assertThat(connectionFactory.getVirtualHost()).isEqualTo("/"); assertThat(connectionFactory.getVirtualHost()).isEqualTo("/");
}); });
} }
@Test @Test
public void testConnectionFactoryVirtualHostNoLeadingSlash() { public void testConnectionFactoryVirtualHostNoLeadingSlash() {
this.contextRunner.withUserConfiguration(TestConfiguration.class) this.contextRunner.withUserConfiguration(TestConfiguration.class)
.withPropertyValues("spring.rabbitmq.virtual_host:foo").run((context) -> { .withPropertyValues("spring.rabbitmq.virtual_host:foo").run((context) -> {
CachingConnectionFactory connectionFactory = context CachingConnectionFactory connectionFactory = context
.getBean(CachingConnectionFactory.class); .getBean(CachingConnectionFactory.class);
assertThat(connectionFactory.getVirtualHost()).isEqualTo("foo"); assertThat(connectionFactory.getVirtualHost()).isEqualTo("foo");
}); });
} }
@Test @Test
@ -154,37 +159,38 @@ public class RabbitAutoConfigurationTests {
public void testConnectionFactoryDefaultVirtualHost() { public void testConnectionFactoryDefaultVirtualHost() {
this.contextRunner.withUserConfiguration(TestConfiguration.class) this.contextRunner.withUserConfiguration(TestConfiguration.class)
.withPropertyValues("spring.rabbitmq.virtual_host:/").run((context) -> { .withPropertyValues("spring.rabbitmq.virtual_host:/").run((context) -> {
CachingConnectionFactory connectionFactory = context CachingConnectionFactory connectionFactory = context
.getBean(CachingConnectionFactory.class); .getBean(CachingConnectionFactory.class);
assertThat(connectionFactory.getVirtualHost()).isEqualTo("/"); assertThat(connectionFactory.getVirtualHost()).isEqualTo("/");
}); });
} }
@Test @Test
public void testConnectionFactoryPublisherSettings() { public void testConnectionFactoryPublisherSettings() {
this.contextRunner.withUserConfiguration(TestConfiguration.class) this.contextRunner.withUserConfiguration(TestConfiguration.class)
.withPropertyValues("spring.rabbitmq.publisher-confirms=true", .withPropertyValues("spring.rabbitmq.publisher-confirms=true",
"spring.rabbitmq.publisher-returns=true").run(context -> { "spring.rabbitmq.publisher-returns=true")
CachingConnectionFactory connectionFactory = context .run(context -> {
.getBean(CachingConnectionFactory.class); CachingConnectionFactory connectionFactory = context
RabbitTemplate rabbitTemplate = context.getBean(RabbitTemplate.class); .getBean(CachingConnectionFactory.class);
DirectFieldAccessor dfa = new DirectFieldAccessor(connectionFactory); RabbitTemplate rabbitTemplate = context.getBean(RabbitTemplate.class);
assertThat(dfa.getPropertyValue("publisherConfirms")).isEqualTo(true); DirectFieldAccessor dfa = new DirectFieldAccessor(connectionFactory);
assertThat(dfa.getPropertyValue("publisherReturns")).isEqualTo(true); assertThat(dfa.getPropertyValue("publisherConfirms")).isEqualTo(true);
assertThat(getMandatory(rabbitTemplate)).isTrue(); assertThat(dfa.getPropertyValue("publisherReturns")).isEqualTo(true);
}); assertThat(getMandatory(rabbitTemplate)).isTrue();
});
} }
@Test @Test
public void testRabbitTemplateMessageConverters() { public void testRabbitTemplateMessageConverters() {
this.contextRunner.withUserConfiguration( this.contextRunner.withUserConfiguration(MessageConvertersConfiguration.class)
MessageConvertersConfiguration.class).run((context) -> { .run((context) -> {
RabbitTemplate rabbitTemplate = context.getBean(RabbitTemplate.class); RabbitTemplate rabbitTemplate = context.getBean(RabbitTemplate.class);
assertThat(rabbitTemplate.getMessageConverter()) assertThat(rabbitTemplate.getMessageConverter())
.isSameAs(context.getBean("myMessageConverter")); .isSameAs(context.getBean("myMessageConverter"));
DirectFieldAccessor dfa = new DirectFieldAccessor(rabbitTemplate); DirectFieldAccessor dfa = new DirectFieldAccessor(rabbitTemplate);
assertThat(dfa.getPropertyValue("retryTemplate")).isNull(); assertThat(dfa.getPropertyValue("retryTemplate")).isNull();
}); });
} }
@Test @Test
@ -196,25 +202,25 @@ public class RabbitAutoConfigurationTests {
"spring.rabbitmq.template.retry.multiplier:1.5", "spring.rabbitmq.template.retry.multiplier:1.5",
"spring.rabbitmq.template.retry.maxInterval:5000", "spring.rabbitmq.template.retry.maxInterval:5000",
"spring.rabbitmq.template.receiveTimeout:123", "spring.rabbitmq.template.receiveTimeout:123",
"spring.rabbitmq.template.replyTimeout:456" "spring.rabbitmq.template.replyTimeout:456")
).run((context) -> { .run((context) -> {
RabbitTemplate rabbitTemplate = context.getBean(RabbitTemplate.class); RabbitTemplate rabbitTemplate = context.getBean(RabbitTemplate.class);
DirectFieldAccessor dfa = new DirectFieldAccessor(rabbitTemplate); DirectFieldAccessor dfa = new DirectFieldAccessor(rabbitTemplate);
assertThat(dfa.getPropertyValue("receiveTimeout")).isEqualTo(123L); assertThat(dfa.getPropertyValue("receiveTimeout")).isEqualTo(123L);
assertThat(dfa.getPropertyValue("replyTimeout")).isEqualTo(456L); assertThat(dfa.getPropertyValue("replyTimeout")).isEqualTo(456L);
RetryTemplate retryTemplate = (RetryTemplate) dfa RetryTemplate retryTemplate = (RetryTemplate) dfa
.getPropertyValue("retryTemplate"); .getPropertyValue("retryTemplate");
assertThat(retryTemplate).isNotNull(); assertThat(retryTemplate).isNotNull();
dfa = new DirectFieldAccessor(retryTemplate); dfa = new DirectFieldAccessor(retryTemplate);
SimpleRetryPolicy retryPolicy = (SimpleRetryPolicy) dfa SimpleRetryPolicy retryPolicy = (SimpleRetryPolicy) dfa
.getPropertyValue("retryPolicy"); .getPropertyValue("retryPolicy");
ExponentialBackOffPolicy backOffPolicy = (ExponentialBackOffPolicy) dfa ExponentialBackOffPolicy backOffPolicy = (ExponentialBackOffPolicy) dfa
.getPropertyValue("backOffPolicy"); .getPropertyValue("backOffPolicy");
assertThat(retryPolicy.getMaxAttempts()).isEqualTo(4); assertThat(retryPolicy.getMaxAttempts()).isEqualTo(4);
assertThat(backOffPolicy.getInitialInterval()).isEqualTo(2000); assertThat(backOffPolicy.getInitialInterval()).isEqualTo(2000);
assertThat(backOffPolicy.getMultiplier()).isEqualTo(1.5); assertThat(backOffPolicy.getMultiplier()).isEqualTo(1.5);
assertThat(backOffPolicy.getMaxInterval()).isEqualTo(5000); assertThat(backOffPolicy.getMaxInterval()).isEqualTo(5000);
}); });
} }
@Test @Test
@ -240,15 +246,16 @@ public class RabbitAutoConfigurationTests {
@Test @Test
public void testConnectionFactoryBackOff() { public void testConnectionFactoryBackOff() {
this.contextRunner.withUserConfiguration( this.contextRunner.withUserConfiguration(TestConfiguration2.class)
TestConfiguration2.class).run((context) -> { .run((context) -> {
RabbitTemplate rabbitTemplate = context.getBean(RabbitTemplate.class); RabbitTemplate rabbitTemplate = context.getBean(RabbitTemplate.class);
CachingConnectionFactory connectionFactory = context CachingConnectionFactory connectionFactory = context
.getBean(CachingConnectionFactory.class); .getBean(CachingConnectionFactory.class);
assertThat(connectionFactory).isEqualTo(rabbitTemplate.getConnectionFactory()); assertThat(connectionFactory)
assertThat(connectionFactory.getHost()).isEqualTo("otherserver"); .isEqualTo(rabbitTemplate.getConnectionFactory());
assertThat(connectionFactory.getPort()).isEqualTo(8001); assertThat(connectionFactory.getHost()).isEqualTo("otherserver");
}); assertThat(connectionFactory.getPort()).isEqualTo(8001);
});
} }
@Test @Test
@ -257,15 +264,18 @@ public class RabbitAutoConfigurationTests {
.withPropertyValues("spring.rabbitmq.cache.channel.size=23", .withPropertyValues("spring.rabbitmq.cache.channel.size=23",
"spring.rabbitmq.cache.channel.checkoutTimeout=1000", "spring.rabbitmq.cache.channel.checkoutTimeout=1000",
"spring.rabbitmq.cache.connection.mode=CONNECTION", "spring.rabbitmq.cache.connection.mode=CONNECTION",
"spring.rabbitmq.cache.connection.size=2").run((context) -> { "spring.rabbitmq.cache.connection.size=2")
CachingConnectionFactory connectionFactory = context .run((context) -> {
.getBean(CachingConnectionFactory.class); CachingConnectionFactory connectionFactory = context
DirectFieldAccessor dfa = new DirectFieldAccessor(connectionFactory); .getBean(CachingConnectionFactory.class);
assertThat(dfa.getPropertyValue("channelCacheSize")).isEqualTo(23); DirectFieldAccessor dfa = new DirectFieldAccessor(connectionFactory);
assertThat(dfa.getPropertyValue("cacheMode")).isEqualTo(CacheMode.CONNECTION); assertThat(dfa.getPropertyValue("channelCacheSize")).isEqualTo(23);
assertThat(dfa.getPropertyValue("connectionCacheSize")).isEqualTo(2); assertThat(dfa.getPropertyValue("cacheMode"))
assertThat(dfa.getPropertyValue("channelCheckoutTimeout")).isEqualTo(1000L); .isEqualTo(CacheMode.CONNECTION);
}); assertThat(dfa.getPropertyValue("connectionCacheSize")).isEqualTo(2);
assertThat(dfa.getPropertyValue("channelCheckoutTimeout"))
.isEqualTo(1000L);
});
} }
@Test @Test
@ -280,104 +290,114 @@ public class RabbitAutoConfigurationTests {
@Test @Test
public void testRabbitMessagingTemplateBackOff() { public void testRabbitMessagingTemplateBackOff() {
this.contextRunner.withUserConfiguration( this.contextRunner.withUserConfiguration(TestConfiguration4.class)
TestConfiguration4.class).run((context) -> { .run((context) -> {
RabbitMessagingTemplate messagingTemplate = context RabbitMessagingTemplate messagingTemplate = context
.getBean(RabbitMessagingTemplate.class); .getBean(RabbitMessagingTemplate.class);
assertThat(messagingTemplate.getDefaultDestination()).isEqualTo("fooBar"); assertThat(messagingTemplate.getDefaultDestination())
}); .isEqualTo("fooBar");
});
} }
@Test @Test
public void testStaticQueues() { public void testStaticQueues() {
this.contextRunner.withUserConfiguration(TestConfiguration.class) this.contextRunner.withUserConfiguration(TestConfiguration.class)
.withPropertyValues("spring.rabbitmq.dynamic:false").run((context) -> { .withPropertyValues("spring.rabbitmq.dynamic:false").run((context) -> {
// There should NOT be an AmqpAdmin bean when dynamic is switch to false // There should NOT be an AmqpAdmin bean when dynamic is switch to
this.thrown.expect(NoSuchBeanDefinitionException.class); // false
this.thrown.expectMessage("No qualifying bean of type"); this.thrown.expect(NoSuchBeanDefinitionException.class);
this.thrown.expectMessage(AmqpAdmin.class.getName()); this.thrown.expectMessage("No qualifying bean of type");
context.getBean(AmqpAdmin.class); this.thrown.expectMessage(AmqpAdmin.class.getName());
}); context.getBean(AmqpAdmin.class);
});
} }
@Test @Test
public void testEnableRabbitCreateDefaultContainerFactory() { public void testEnableRabbitCreateDefaultContainerFactory() {
this.contextRunner.withUserConfiguration( this.contextRunner.withUserConfiguration(EnableRabbitConfiguration.class)
EnableRabbitConfiguration.class).run((context) -> { .run((context) -> {
RabbitListenerContainerFactory<?> rabbitListenerContainerFactory = context RabbitListenerContainerFactory<?> rabbitListenerContainerFactory = context
.getBean("rabbitListenerContainerFactory", .getBean("rabbitListenerContainerFactory",
RabbitListenerContainerFactory.class); RabbitListenerContainerFactory.class);
assertThat(rabbitListenerContainerFactory.getClass()) assertThat(rabbitListenerContainerFactory.getClass())
.isEqualTo(SimpleRabbitListenerContainerFactory.class); .isEqualTo(SimpleRabbitListenerContainerFactory.class);
}); });
} }
@Test @Test
public void testRabbitListenerContainerFactoryBackOff() { public void testRabbitListenerContainerFactoryBackOff() {
this.contextRunner.withUserConfiguration( this.contextRunner.withUserConfiguration(TestConfiguration5.class)
TestConfiguration5.class).run((context) -> { .run((context) -> {
SimpleRabbitListenerContainerFactory rabbitListenerContainerFactory = context SimpleRabbitListenerContainerFactory rabbitListenerContainerFactory = context
.getBean("rabbitListenerContainerFactory", .getBean("rabbitListenerContainerFactory",
SimpleRabbitListenerContainerFactory.class); SimpleRabbitListenerContainerFactory.class);
rabbitListenerContainerFactory.setTxSize(10); rabbitListenerContainerFactory.setTxSize(10);
verify(rabbitListenerContainerFactory).setTxSize(10); verify(rabbitListenerContainerFactory).setTxSize(10);
DirectFieldAccessor dfa = new DirectFieldAccessor(rabbitListenerContainerFactory); DirectFieldAccessor dfa = new DirectFieldAccessor(
Advice[] adviceChain = (Advice[]) dfa.getPropertyValue("adviceChain"); rabbitListenerContainerFactory);
assertThat(adviceChain).isNull(); Advice[] adviceChain = (Advice[]) dfa.getPropertyValue("adviceChain");
}); assertThat(adviceChain).isNull();
});
} }
@Test @Test
public void testSimpleRabbitListenerContainerFactoryWithCustomSettings() { public void testSimpleRabbitListenerContainerFactoryWithCustomSettings() {
this.contextRunner.withUserConfiguration(MessageConvertersConfiguration.class, this.contextRunner
MessageRecoverersConfiguration.class).withPropertyValues( .withUserConfiguration(MessageConvertersConfiguration.class,
"spring.rabbitmq.listener.simple.retry.enabled:true", MessageRecoverersConfiguration.class)
"spring.rabbitmq.listener.simple.retry.maxAttempts:4", .withPropertyValues("spring.rabbitmq.listener.simple.retry.enabled:true",
"spring.rabbitmq.listener.simple.retry.initialInterval:2000", "spring.rabbitmq.listener.simple.retry.maxAttempts:4",
"spring.rabbitmq.listener.simple.retry.multiplier:1.5", "spring.rabbitmq.listener.simple.retry.initialInterval:2000",
"spring.rabbitmq.listener.simple.retry.maxInterval:5000", "spring.rabbitmq.listener.simple.retry.multiplier:1.5",
"spring.rabbitmq.listener.simple.autoStartup:false", "spring.rabbitmq.listener.simple.retry.maxInterval:5000",
"spring.rabbitmq.listener.simple.acknowledgeMode:manual", "spring.rabbitmq.listener.simple.autoStartup:false",
"spring.rabbitmq.listener.simple.concurrency:5", "spring.rabbitmq.listener.simple.acknowledgeMode:manual",
"spring.rabbitmq.listener.simple.maxConcurrency:10", "spring.rabbitmq.listener.simple.concurrency:5",
"spring.rabbitmq.listener.simple.prefetch:40", "spring.rabbitmq.listener.simple.maxConcurrency:10",
"spring.rabbitmq.listener.simple.defaultRequeueRejected:false", "spring.rabbitmq.listener.simple.prefetch:40",
"spring.rabbitmq.listener.simple.idleEventInterval:5", "spring.rabbitmq.listener.simple.defaultRequeueRejected:false",
"spring.rabbitmq.listener.simple.transactionSize:20").run((context) -> { "spring.rabbitmq.listener.simple.idleEventInterval:5",
SimpleRabbitListenerContainerFactory rabbitListenerContainerFactory = context "spring.rabbitmq.listener.simple.transactionSize:20")
.getBean("rabbitListenerContainerFactory", .run((context) -> {
SimpleRabbitListenerContainerFactory.class); SimpleRabbitListenerContainerFactory rabbitListenerContainerFactory = context
DirectFieldAccessor dfa = new DirectFieldAccessor(rabbitListenerContainerFactory); .getBean("rabbitListenerContainerFactory",
assertThat(dfa.getPropertyValue("concurrentConsumers")).isEqualTo(5); SimpleRabbitListenerContainerFactory.class);
assertThat(dfa.getPropertyValue("maxConcurrentConsumers")).isEqualTo(10); DirectFieldAccessor dfa = new DirectFieldAccessor(
assertThat(dfa.getPropertyValue("txSize")).isEqualTo(20); rabbitListenerContainerFactory);
checkCommonProps(context, dfa); assertThat(dfa.getPropertyValue("concurrentConsumers")).isEqualTo(5);
}); assertThat(dfa.getPropertyValue("maxConcurrentConsumers"))
.isEqualTo(10);
assertThat(dfa.getPropertyValue("txSize")).isEqualTo(20);
checkCommonProps(context, dfa);
});
} }
@Test @Test
public void testDirectRabbitListenerContainerFactoryWithCustomSettings() { public void testDirectRabbitListenerContainerFactoryWithCustomSettings() {
this.contextRunner.withUserConfiguration(MessageConvertersConfiguration.class, this.contextRunner
MessageRecoverersConfiguration.class).withPropertyValues( .withUserConfiguration(MessageConvertersConfiguration.class,
"spring.rabbitmq.listener.type:direct", MessageRecoverersConfiguration.class)
"spring.rabbitmq.listener.direct.retry.enabled:true", .withPropertyValues("spring.rabbitmq.listener.type:direct",
"spring.rabbitmq.listener.direct.retry.maxAttempts:4", "spring.rabbitmq.listener.direct.retry.enabled:true",
"spring.rabbitmq.listener.direct.retry.initialInterval:2000", "spring.rabbitmq.listener.direct.retry.maxAttempts:4",
"spring.rabbitmq.listener.direct.retry.multiplier:1.5", "spring.rabbitmq.listener.direct.retry.initialInterval:2000",
"spring.rabbitmq.listener.direct.retry.maxInterval:5000", "spring.rabbitmq.listener.direct.retry.multiplier:1.5",
"spring.rabbitmq.listener.direct.autoStartup:false", "spring.rabbitmq.listener.direct.retry.maxInterval:5000",
"spring.rabbitmq.listener.direct.acknowledgeMode:manual", "spring.rabbitmq.listener.direct.autoStartup:false",
"spring.rabbitmq.listener.direct.consumers-per-queue:5", "spring.rabbitmq.listener.direct.acknowledgeMode:manual",
"spring.rabbitmq.listener.direct.prefetch:40", "spring.rabbitmq.listener.direct.consumers-per-queue:5",
"spring.rabbitmq.listener.direct.defaultRequeueRejected:false", "spring.rabbitmq.listener.direct.prefetch:40",
"spring.rabbitmq.listener.direct.idleEventInterval:5").run((context) -> { "spring.rabbitmq.listener.direct.defaultRequeueRejected:false",
DirectRabbitListenerContainerFactory rabbitListenerContainerFactory = context "spring.rabbitmq.listener.direct.idleEventInterval:5")
.getBean("rabbitListenerContainerFactory", .run((context) -> {
DirectRabbitListenerContainerFactory.class); DirectRabbitListenerContainerFactory rabbitListenerContainerFactory = context
DirectFieldAccessor dfa = new DirectFieldAccessor(rabbitListenerContainerFactory); .getBean("rabbitListenerContainerFactory",
assertThat(dfa.getPropertyValue("consumersPerQueue")).isEqualTo(5); DirectRabbitListenerContainerFactory.class);
checkCommonProps(context, dfa); DirectFieldAccessor dfa = new DirectFieldAccessor(
}); rabbitListenerContainerFactory);
assertThat(dfa.getPropertyValue("consumersPerQueue")).isEqualTo(5);
checkCommonProps(context, dfa);
});
} }
@Test @Test
@ -387,12 +407,13 @@ public class RabbitAutoConfigurationTests {
"spring.rabbitmq.listener.simple.maxConcurrency:10", "spring.rabbitmq.listener.simple.maxConcurrency:10",
"spring.rabbitmq.listener.simple.prefetch:40", "spring.rabbitmq.listener.simple.prefetch:40",
"spring.rabbitmq.listener.direct.consumers-per-queue:5", "spring.rabbitmq.listener.direct.consumers-per-queue:5",
"spring.rabbitmq.listener.direct.prefetch:40").run((context) -> { "spring.rabbitmq.listener.direct.prefetch:40")
assertThat(context).hasSingleBean( .run((context) -> {
SimpleRabbitListenerContainerFactoryConfigurer.class); assertThat(context).hasSingleBean(
assertThat(context).hasSingleBean( SimpleRabbitListenerContainerFactoryConfigurer.class);
DirectRabbitListenerContainerFactoryConfigurer.class); assertThat(context).hasSingleBean(
}); DirectRabbitListenerContainerFactoryConfigurer.class);
});
} }
@Test @Test
@ -401,16 +422,18 @@ public class RabbitAutoConfigurationTests {
.withPropertyValues("spring.rabbitmq.listener.type:direct", .withPropertyValues("spring.rabbitmq.listener.type:direct",
"spring.rabbitmq.listener.simple.concurrency:5", "spring.rabbitmq.listener.simple.concurrency:5",
"spring.rabbitmq.listener.simple.maxConcurrency:10", "spring.rabbitmq.listener.simple.maxConcurrency:10",
"spring.rabbitmq.listener.simple.prefetch:40").run((context) -> { "spring.rabbitmq.listener.simple.prefetch:40")
SimpleRabbitListenerContainerFactoryConfigurer configurer = context .run((context) -> {
.getBean(SimpleRabbitListenerContainerFactoryConfigurer.class); SimpleRabbitListenerContainerFactoryConfigurer configurer = context
SimpleRabbitListenerContainerFactory factory = mock( .getBean(
SimpleRabbitListenerContainerFactory.class); SimpleRabbitListenerContainerFactoryConfigurer.class);
configurer.configure(factory, mock(ConnectionFactory.class)); SimpleRabbitListenerContainerFactory factory = mock(
verify(factory).setConcurrentConsumers(5); SimpleRabbitListenerContainerFactory.class);
verify(factory).setMaxConcurrentConsumers(10); configurer.configure(factory, mock(ConnectionFactory.class));
verify(factory).setPrefetchCount(40); verify(factory).setConcurrentConsumers(5);
}); verify(factory).setMaxConcurrentConsumers(10);
verify(factory).setPrefetchCount(40);
});
} }
@Test @Test
@ -418,15 +441,17 @@ public class RabbitAutoConfigurationTests {
this.contextRunner.withUserConfiguration(TestConfiguration.class) this.contextRunner.withUserConfiguration(TestConfiguration.class)
.withPropertyValues("spring.rabbitmq.listener.type:simple", .withPropertyValues("spring.rabbitmq.listener.type:simple",
"spring.rabbitmq.listener.direct.consumers-per-queue:5", "spring.rabbitmq.listener.direct.consumers-per-queue:5",
"spring.rabbitmq.listener.direct.prefetch:40").run((context) -> { "spring.rabbitmq.listener.direct.prefetch:40")
DirectRabbitListenerContainerFactoryConfigurer configurer = context .run((context) -> {
.getBean(DirectRabbitListenerContainerFactoryConfigurer.class); DirectRabbitListenerContainerFactoryConfigurer configurer = context
DirectRabbitListenerContainerFactory factory = mock( .getBean(
DirectRabbitListenerContainerFactory.class); DirectRabbitListenerContainerFactoryConfigurer.class);
configurer.configure(factory, mock(ConnectionFactory.class)); DirectRabbitListenerContainerFactory factory = mock(
verify(factory).setConsumersPerQueue(5); DirectRabbitListenerContainerFactory.class);
verify(factory).setPrefetchCount(40); configurer.configure(factory, mock(ConnectionFactory.class));
}); verify(factory).setConsumersPerQueue(5);
verify(factory).setPrefetchCount(40);
});
} }
private void checkCommonProps(AssertableApplicationContext context, private void checkCommonProps(AssertableApplicationContext context,
@ -468,13 +493,13 @@ public class RabbitAutoConfigurationTests {
@Test @Test
public void enableRabbitAutomatically() throws Exception { public void enableRabbitAutomatically() throws Exception {
this.contextRunner.withUserConfiguration( this.contextRunner.withUserConfiguration(NoEnableRabbitConfiguration.class)
NoEnableRabbitConfiguration.class).run((context) -> { .run((context) -> {
assertThat(context).hasBean( assertThat(context).hasBean(
RabbitListenerConfigUtils.RABBIT_LISTENER_ANNOTATION_PROCESSOR_BEAN_NAME); RabbitListenerConfigUtils.RABBIT_LISTENER_ANNOTATION_PROCESSOR_BEAN_NAME);
assertThat(context).hasBean( assertThat(context).hasBean(
RabbitListenerConfigUtils.RABBIT_LISTENER_ENDPOINT_REGISTRY_BEAN_NAME); RabbitListenerConfigUtils.RABBIT_LISTENER_ENDPOINT_REGISTRY_BEAN_NAME);
}); });
} }
@Test @Test
@ -482,7 +507,8 @@ public class RabbitAutoConfigurationTests {
this.contextRunner.withUserConfiguration(TestConfiguration.class) this.contextRunner.withUserConfiguration(TestConfiguration.class)
.withPropertyValues("spring.rabbitmq.requestedHeartbeat:20") .withPropertyValues("spring.rabbitmq.requestedHeartbeat:20")
.run((context) -> { .run((context) -> {
com.rabbitmq.client.ConnectionFactory rabbitConnectionFactory = getTargetConnectionFactory(context); com.rabbitmq.client.ConnectionFactory rabbitConnectionFactory = getTargetConnectionFactory(
context);
assertThat(rabbitConnectionFactory.getRequestedHeartbeat()) assertThat(rabbitConnectionFactory.getRequestedHeartbeat())
.isEqualTo(20); .isEqualTo(20);
}); });
@ -490,23 +516,26 @@ public class RabbitAutoConfigurationTests {
@Test @Test
public void noSslByDefault() { public void noSslByDefault() {
this.contextRunner.withUserConfiguration( this.contextRunner.withUserConfiguration(TestConfiguration.class)
TestConfiguration.class).run((context) -> { .run((context) -> {
com.rabbitmq.client.ConnectionFactory rabbitConnectionFactory = getTargetConnectionFactory(context); com.rabbitmq.client.ConnectionFactory rabbitConnectionFactory = getTargetConnectionFactory(
assertThat(rabbitConnectionFactory.getSocketFactory()) context);
.as("Must use default SocketFactory") assertThat(rabbitConnectionFactory.getSocketFactory())
.isEqualTo(SocketFactory.getDefault()); .as("Must use default SocketFactory")
}); .isEqualTo(SocketFactory.getDefault());
});
} }
@Test @Test
public void enableSsl() { public void enableSsl() {
this.contextRunner.withUserConfiguration(TestConfiguration.class) this.contextRunner.withUserConfiguration(TestConfiguration.class)
.withPropertyValues("spring.rabbitmq.ssl.enabled:true").run((context) -> { .withPropertyValues("spring.rabbitmq.ssl.enabled:true").run((context) -> {
com.rabbitmq.client.ConnectionFactory rabbitConnectionFactory = getTargetConnectionFactory(context); com.rabbitmq.client.ConnectionFactory rabbitConnectionFactory = getTargetConnectionFactory(
assertThat(rabbitConnectionFactory.getSocketFactory()) context);
.as("SocketFactory must use SSL").isInstanceOf(SSLSocketFactory.class); assertThat(rabbitConnectionFactory.getSocketFactory())
}); .as("SocketFactory must use SSL")
.isInstanceOf(SSLSocketFactory.class);
});
} }
@Test @Test
@ -517,11 +546,13 @@ public class RabbitAutoConfigurationTests {
"spring.rabbitmq.ssl.keyStore=foo", "spring.rabbitmq.ssl.keyStore=foo",
"spring.rabbitmq.ssl.keyStorePassword=secret", "spring.rabbitmq.ssl.keyStorePassword=secret",
"spring.rabbitmq.ssl.trustStore=bar", "spring.rabbitmq.ssl.trustStore=bar",
"spring.rabbitmq.ssl.trustStorePassword=secret").run((context) -> { "spring.rabbitmq.ssl.trustStorePassword=secret")
assertThat(context).hasFailed(); .run((context) -> {
assertThat(context).getFailure().hasMessageContaining("foo"); assertThat(context).hasFailed();
assertThat(context).getFailure().hasMessageContaining("does not exist"); assertThat(context).getFailure().hasMessageContaining("foo");
}); assertThat(context).getFailure()
.hasMessageContaining("does not exist");
});
} }
private com.rabbitmq.client.ConnectionFactory getTargetConnectionFactory( private com.rabbitmq.client.ConnectionFactory getTargetConnectionFactory(

@ -46,12 +46,12 @@ public class AopAutoConfigurationTests {
public void aopDisabled() { public void aopDisabled() {
this.contextRunner.withUserConfiguration(TestConfiguration.class) this.contextRunner.withUserConfiguration(TestConfiguration.class)
.withPropertyValues("spring.aop.auto:false").run((context) -> { .withPropertyValues("spring.aop.auto:false").run((context) -> {
TestAspect aspect = context.getBean(TestAspect.class); TestAspect aspect = context.getBean(TestAspect.class);
assertThat(aspect.isCalled()).isFalse(); assertThat(aspect.isCalled()).isFalse();
TestBean bean = context.getBean(TestBean.class); TestBean bean = context.getBean(TestBean.class);
bean.foo(); bean.foo();
assertThat(aspect.isCalled()).isFalse(); assertThat(aspect.isCalled()).isFalse();
}); });
} }
@Test @Test

@ -84,93 +84,100 @@ public class BatchAutoConfigurationTests {
public void testDefaultContext() throws Exception { public void testDefaultContext() throws Exception {
this.contextRunner.withUserConfiguration(TestConfiguration.class, this.contextRunner.withUserConfiguration(TestConfiguration.class,
EmbeddedDataSourceConfiguration.class).run((context) -> { EmbeddedDataSourceConfiguration.class).run((context) -> {
assertThat(context).hasSingleBean(JobLauncher.class); assertThat(context).hasSingleBean(JobLauncher.class);
assertThat(context).hasSingleBean(JobExplorer.class); assertThat(context).hasSingleBean(JobExplorer.class);
assertThat(context.getBean(BatchProperties.class) assertThat(context.getBean(BatchProperties.class).getInitializer()
.getInitializer().isEnabled()).isTrue(); .isEnabled()).isTrue();
assertThat(new JdbcTemplate(context.getBean(DataSource.class)) assertThat(new JdbcTemplate(context.getBean(DataSource.class))
.queryForList("select * from BATCH_JOB_EXECUTION")).isEmpty(); .queryForList("select * from BATCH_JOB_EXECUTION")).isEmpty();
}); });
} }
@Test @Test
public void testNoDatabase() throws Exception { public void testNoDatabase() throws Exception {
this.contextRunner.withUserConfiguration( this.contextRunner.withUserConfiguration(TestCustomConfiguration.class)
TestCustomConfiguration.class).run((context) -> { .run((context) -> {
assertThat(context).hasSingleBean(JobLauncher.class); assertThat(context).hasSingleBean(JobLauncher.class);
JobExplorer explorer = context.getBean(JobExplorer.class); JobExplorer explorer = context.getBean(JobExplorer.class);
assertThat(explorer.getJobInstances("job", 0, 100)).isEmpty(); assertThat(explorer.getJobInstances("job", 0, 100)).isEmpty();
}); });
} }
@Test @Test
public void testNoBatchConfiguration() throws Exception { public void testNoBatchConfiguration() throws Exception {
this.contextRunner.withUserConfiguration(EmptyConfiguration.class, this.contextRunner.withUserConfiguration(EmptyConfiguration.class,
EmbeddedDataSourceConfiguration.class).run((context) -> { EmbeddedDataSourceConfiguration.class).run((context) -> {
assertThat(context).doesNotHaveBean(JobLauncher.class); assertThat(context).doesNotHaveBean(JobLauncher.class);
assertThat(context).doesNotHaveBean(JobRepository.class); assertThat(context).doesNotHaveBean(JobRepository.class);
}); });
} }
@Test @Test
public void testDefinesAndLaunchesJob() throws Exception { public void testDefinesAndLaunchesJob() throws Exception {
this.contextRunner.withUserConfiguration(JobConfiguration.class, this.contextRunner.withUserConfiguration(JobConfiguration.class,
EmbeddedDataSourceConfiguration.class).run((context) -> { EmbeddedDataSourceConfiguration.class).run((context) -> {
assertThat(context).hasSingleBean(JobLauncher.class); assertThat(context).hasSingleBean(JobLauncher.class);
context.getBean(JobLauncherCommandLineRunner.class).run(); context.getBean(JobLauncherCommandLineRunner.class).run();
assertThat(context.getBean(JobRepository.class).getLastJobExecution("job", assertThat(context.getBean(JobRepository.class)
new JobParameters())).isNotNull(); .getLastJobExecution("job", new JobParameters())).isNotNull();
}); });
} }
@Test @Test
public void testDefinesAndLaunchesNamedJob() throws Exception { public void testDefinesAndLaunchesNamedJob() throws Exception {
this.contextRunner.withUserConfiguration( this.contextRunner
NamedJobConfigurationWithRegisteredJob.class, .withUserConfiguration(NamedJobConfigurationWithRegisteredJob.class,
EmbeddedDataSourceConfiguration.class).withPropertyValues( EmbeddedDataSourceConfiguration.class)
"spring.batch.job.names:discreteRegisteredJob").run((context) -> { .withPropertyValues("spring.batch.job.names:discreteRegisteredJob")
assertThat(context).hasSingleBean(JobLauncher.class); .run((context) -> {
context.getBean(JobLauncherCommandLineRunner.class).run(); assertThat(context).hasSingleBean(JobLauncher.class);
assertThat(context.getBean(JobRepository.class).getLastJobExecution( context.getBean(JobLauncherCommandLineRunner.class).run();
"discreteRegisteredJob", new JobParameters())).isNotNull(); assertThat(context.getBean(JobRepository.class).getLastJobExecution(
}); "discreteRegisteredJob", new JobParameters())).isNotNull();
});
} }
@Test @Test
public void testDefinesAndLaunchesLocalJob() throws Exception { public void testDefinesAndLaunchesLocalJob() throws Exception {
this.contextRunner.withUserConfiguration(NamedJobConfigurationWithLocalJob.class, this.contextRunner
EmbeddedDataSourceConfiguration.class).withPropertyValues( .withUserConfiguration(NamedJobConfigurationWithLocalJob.class,
"spring.batch.job.names:discreteLocalJob").run((context) -> { EmbeddedDataSourceConfiguration.class)
assertThat(context).hasSingleBean(JobLauncher.class); .withPropertyValues("spring.batch.job.names:discreteLocalJob")
context.getBean(JobLauncherCommandLineRunner.class).run(); .run((context) -> {
assertThat(context.getBean(JobRepository.class).getLastJobExecution( assertThat(context).hasSingleBean(JobLauncher.class);
"discreteLocalJob", new JobParameters())).isNotNull(); context.getBean(JobLauncherCommandLineRunner.class).run();
}); assertThat(context.getBean(JobRepository.class)
.getLastJobExecution("discreteLocalJob", new JobParameters()))
.isNotNull();
});
} }
@Test @Test
public void testDisableLaunchesJob() throws Exception { public void testDisableLaunchesJob() throws Exception {
this.contextRunner.withUserConfiguration(JobConfiguration.class, this.contextRunner
EmbeddedDataSourceConfiguration.class).withPropertyValues( .withUserConfiguration(JobConfiguration.class,
"spring.batch.job.enabled:false").run((context) -> { EmbeddedDataSourceConfiguration.class)
assertThat(context).hasSingleBean(JobLauncher.class); .withPropertyValues("spring.batch.job.enabled:false").run((context) -> {
assertThat(context).doesNotHaveBean(CommandLineRunner.class); assertThat(context).hasSingleBean(JobLauncher.class);
}); assertThat(context).doesNotHaveBean(CommandLineRunner.class);
});
} }
@Test @Test
public void testDisableSchemaLoader() throws Exception { public void testDisableSchemaLoader() throws Exception {
this.contextRunner.withUserConfiguration(TestConfiguration.class, this.contextRunner
EmbeddedDataSourceConfiguration.class).withPropertyValues( .withUserConfiguration(TestConfiguration.class,
"spring.datasource.generate-unique-name=true", EmbeddedDataSourceConfiguration.class)
"spring.batch.initializer.enabled:false").run((context) -> { .withPropertyValues("spring.datasource.generate-unique-name=true",
assertThat(context).hasSingleBean(JobLauncher.class); "spring.batch.initializer.enabled:false")
assertThat(context.getBean(BatchProperties.class).getInitializer() .run((context) -> {
.isEnabled()).isFalse(); assertThat(context).hasSingleBean(JobLauncher.class);
this.expected.expect(BadSqlGrammarException.class); assertThat(context.getBean(BatchProperties.class).getInitializer()
new JdbcTemplate(context.getBean(DataSource.class)).queryForList( .isEnabled()).isFalse();
"select * from BATCH_JOB_EXECUTION"); this.expected.expect(BadSqlGrammarException.class);
}); new JdbcTemplate(context.getBean(DataSource.class))
.queryForList("select * from BATCH_JOB_EXECUTION");
});
} }
@Test @Test
@ -178,85 +185,97 @@ public class BatchAutoConfigurationTests {
this.contextRunner.withUserConfiguration(TestConfiguration.class, this.contextRunner.withUserConfiguration(TestConfiguration.class,
EmbeddedDataSourceConfiguration.class, EmbeddedDataSourceConfiguration.class,
HibernateJpaAutoConfiguration.class).run((context) -> { HibernateJpaAutoConfiguration.class).run((context) -> {
PlatformTransactionManager transactionManager = context PlatformTransactionManager transactionManager = context
.getBean(PlatformTransactionManager.class); .getBean(PlatformTransactionManager.class);
// It's a lazy proxy, but it does render its target if you ask for toString(): // It's a lazy proxy, but it does render its target if you ask for
assertThat(transactionManager.toString().contains("JpaTransactionManager")) // toString():
.isTrue(); assertThat(transactionManager.toString()
assertThat(context).hasSingleBean(EntityManagerFactory.class); .contains("JpaTransactionManager")).isTrue();
// Ensure the JobRepository can be used (no problem with isolation level) assertThat(context).hasSingleBean(EntityManagerFactory.class);
assertThat(context.getBean(JobRepository.class).getLastJobExecution("job", // Ensure the JobRepository can be used (no problem with isolation
new JobParameters())).isNull(); // level)
}); assertThat(context.getBean(JobRepository.class)
.getLastJobExecution("job", new JobParameters())).isNull();
});
} }
@Test @Test
public void testRenamePrefix() throws Exception { public void testRenamePrefix() throws Exception {
this.contextRunner.withUserConfiguration(TestConfiguration.class, this.contextRunner
EmbeddedDataSourceConfiguration.class, .withUserConfiguration(TestConfiguration.class,
HibernateJpaAutoConfiguration.class).withPropertyValues( EmbeddedDataSourceConfiguration.class,
"spring.datasource.generate-unique-name=true", HibernateJpaAutoConfiguration.class)
"spring.batch.schema:classpath:batch/custom-schema-hsql.sql", .withPropertyValues("spring.datasource.generate-unique-name=true",
"spring.batch.tablePrefix:PREFIX_").run((context) -> { "spring.batch.schema:classpath:batch/custom-schema-hsql.sql",
assertThat(context).hasSingleBean(JobLauncher.class); "spring.batch.tablePrefix:PREFIX_")
assertThat(context.getBean(BatchProperties.class).getInitializer() .run((context) -> {
.isEnabled()).isTrue(); assertThat(context).hasSingleBean(JobLauncher.class);
assertThat(new JdbcTemplate(context.getBean(DataSource.class)) assertThat(context.getBean(BatchProperties.class).getInitializer()
.queryForList("select * from PREFIX_JOB_EXECUTION")).isEmpty(); .isEnabled()).isTrue();
JobExplorer jobExplorer = context.getBean(JobExplorer.class); assertThat(new JdbcTemplate(context.getBean(DataSource.class))
assertThat(jobExplorer.findRunningJobExecutions("test")).isEmpty(); .queryForList("select * from PREFIX_JOB_EXECUTION"))
JobRepository jobRepository = context.getBean(JobRepository.class); .isEmpty();
assertThat(jobRepository.getLastJobExecution("test", new JobParameters())) JobExplorer jobExplorer = context.getBean(JobExplorer.class);
.isNull(); assertThat(jobExplorer.findRunningJobExecutions("test")).isEmpty();
}); JobRepository jobRepository = context.getBean(JobRepository.class);
assertThat(jobRepository.getLastJobExecution("test",
new JobParameters())).isNull();
});
} }
@Test @Test
public void testCustomTablePrefixWithDefaultSchemaDisablesInitializer() public void testCustomTablePrefixWithDefaultSchemaDisablesInitializer()
throws Exception { throws Exception {
this.contextRunner.withUserConfiguration(TestConfiguration.class, this.contextRunner
EmbeddedDataSourceConfiguration.class, .withUserConfiguration(TestConfiguration.class,
HibernateJpaAutoConfiguration.class).withPropertyValues( EmbeddedDataSourceConfiguration.class,
"spring.datasource.generate-unique-name=true", HibernateJpaAutoConfiguration.class)
"spring.batch.tablePrefix:PREFIX_").run((context) -> { .withPropertyValues("spring.datasource.generate-unique-name=true",
assertThat(context).hasSingleBean(JobLauncher.class); "spring.batch.tablePrefix:PREFIX_")
assertThat(context.getBean(BatchProperties.class).getInitializer() .run((context) -> {
.isEnabled()).isFalse(); assertThat(context).hasSingleBean(JobLauncher.class);
this.expected.expect(BadSqlGrammarException.class); assertThat(context.getBean(BatchProperties.class).getInitializer()
new JdbcTemplate(context.getBean(DataSource.class)).queryForList( .isEnabled()).isFalse();
"select * from BATCH_JOB_EXECUTION"); this.expected.expect(BadSqlGrammarException.class);
}); new JdbcTemplate(context.getBean(DataSource.class))
.queryForList("select * from BATCH_JOB_EXECUTION");
});
} }
@Test @Test
public void testCustomizeJpaTransactionManagerUsingProperties() throws Exception { public void testCustomizeJpaTransactionManagerUsingProperties() throws Exception {
this.contextRunner.withUserConfiguration(TestConfiguration.class, this.contextRunner
EmbeddedDataSourceConfiguration.class, .withUserConfiguration(TestConfiguration.class,
HibernateJpaAutoConfiguration.class).withPropertyValues( EmbeddedDataSourceConfiguration.class,
"spring.transaction.default-timeout:30", HibernateJpaAutoConfiguration.class)
"spring.transaction.rollback-on-commit-failure:true").run((context) -> { .withPropertyValues("spring.transaction.default-timeout:30",
assertThat(context).hasSingleBean(BatchConfigurer.class); "spring.transaction.rollback-on-commit-failure:true")
JpaTransactionManager transactionManager = JpaTransactionManager.class.cast( .run((context) -> {
context.getBean(BatchConfigurer.class).getTransactionManager()); assertThat(context).hasSingleBean(BatchConfigurer.class);
assertThat(transactionManager.getDefaultTimeout()).isEqualTo(30); JpaTransactionManager transactionManager = JpaTransactionManager.class
assertThat(transactionManager.isRollbackOnCommitFailure()).isTrue(); .cast(context.getBean(BatchConfigurer.class)
}); .getTransactionManager());
assertThat(transactionManager.getDefaultTimeout()).isEqualTo(30);
assertThat(transactionManager.isRollbackOnCommitFailure()).isTrue();
});
} }
@Test @Test
public void testCustomizeDataSourceTransactionManagerUsingProperties() public void testCustomizeDataSourceTransactionManagerUsingProperties()
throws Exception { throws Exception {
this.contextRunner.withUserConfiguration(TestConfiguration.class, this.contextRunner
EmbeddedDataSourceConfiguration.class).withPropertyValues( .withUserConfiguration(TestConfiguration.class,
"spring.transaction.default-timeout:30", EmbeddedDataSourceConfiguration.class)
"spring.transaction.rollback-on-commit-failure:true").run((context) -> { .withPropertyValues("spring.transaction.default-timeout:30",
assertThat(context).hasSingleBean(BatchConfigurer.class); "spring.transaction.rollback-on-commit-failure:true")
DataSourceTransactionManager transactionManager = DataSourceTransactionManager.class .run((context) -> {
.cast(context.getBean(BatchConfigurer.class).getTransactionManager()); assertThat(context).hasSingleBean(BatchConfigurer.class);
assertThat(transactionManager.getDefaultTimeout()).isEqualTo(30); DataSourceTransactionManager transactionManager = DataSourceTransactionManager.class
assertThat(transactionManager.isRollbackOnCommitFailure()).isTrue(); .cast(context.getBean(BatchConfigurer.class)
}); .getTransactionManager());
assertThat(transactionManager.getDefaultTimeout()).isEqualTo(30);
assertThat(transactionManager.isRollbackOnCommitFailure()).isTrue();
});
} }
@Configuration @Configuration

@ -54,43 +54,46 @@ public class BatchAutoConfigurationWithoutJpaTests {
@Test @Test
public void jdbcWithDefaultSettings() throws Exception { public void jdbcWithDefaultSettings() throws Exception {
this.contextRunner.withUserConfiguration(DefaultConfiguration.class, this.contextRunner
EmbeddedDataSourceConfiguration.class).withPropertyValues( .withUserConfiguration(DefaultConfiguration.class,
"spring.datasource.generate-unique-name=true").run((context) -> { EmbeddedDataSourceConfiguration.class)
assertThat(context).hasSingleBean(JobLauncher.class); .withPropertyValues("spring.datasource.generate-unique-name=true")
assertThat(context).hasSingleBean(JobExplorer.class); .run((context) -> {
assertThat(context).hasSingleBean(JobRepository.class); assertThat(context).hasSingleBean(JobLauncher.class);
assertThat(context).hasSingleBean(PlatformTransactionManager.class); assertThat(context).hasSingleBean(JobExplorer.class);
assertThat(context.getBean(PlatformTransactionManager.class).toString()) assertThat(context).hasSingleBean(JobRepository.class);
.contains("DataSourceTransactionManager"); assertThat(context).hasSingleBean(PlatformTransactionManager.class);
assertThat( assertThat(
context.getBean(BatchProperties.class).getInitializer().isEnabled()) context.getBean(PlatformTransactionManager.class).toString())
.isTrue(); .contains("DataSourceTransactionManager");
assertThat(new JdbcTemplate(context.getBean(DataSource.class)) assertThat(context.getBean(BatchProperties.class).getInitializer()
.queryForList("select * from BATCH_JOB_EXECUTION")).isEmpty(); .isEnabled()).isTrue();
assertThat( assertThat(new JdbcTemplate(context.getBean(DataSource.class))
context.getBean(JobExplorer.class).findRunningJobExecutions("test")) .queryForList("select * from BATCH_JOB_EXECUTION")).isEmpty();
.isEmpty(); assertThat(context.getBean(JobExplorer.class)
assertThat(context.getBean(JobRepository.class).getLastJobExecution("test", .findRunningJobExecutions("test")).isEmpty();
new JobParameters())).isNull(); assertThat(context.getBean(JobRepository.class)
}); .getLastJobExecution("test", new JobParameters())).isNull();
});
} }
@Test @Test
public void jdbcWithCustomPrefix() throws Exception { public void jdbcWithCustomPrefix() throws Exception {
this.contextRunner.withUserConfiguration(DefaultConfiguration.class, this.contextRunner
EmbeddedDataSourceConfiguration.class).withPropertyValues( .withUserConfiguration(DefaultConfiguration.class,
"spring.datasource.generate-unique-name=true", EmbeddedDataSourceConfiguration.class)
"spring.batch.schema:classpath:batch/custom-schema-hsql.sql", .withPropertyValues("spring.datasource.generate-unique-name=true",
"spring.batch.tablePrefix:PREFIX_").run((context) -> { "spring.batch.schema:classpath:batch/custom-schema-hsql.sql",
assertThat(new JdbcTemplate(context.getBean(DataSource.class)) "spring.batch.tablePrefix:PREFIX_")
.queryForList("select * from PREFIX_JOB_EXECUTION")).isEmpty(); .run((context) -> {
assertThat( assertThat(new JdbcTemplate(context.getBean(DataSource.class))
context.getBean(JobExplorer.class).findRunningJobExecutions("test")) .queryForList("select * from PREFIX_JOB_EXECUTION"))
.isEmpty(); .isEmpty();
assertThat(context.getBean(JobRepository.class).getLastJobExecution("test", assertThat(context.getBean(JobExplorer.class)
new JobParameters())).isNull(); .findRunningJobExecutions("test")).isEmpty();
}); assertThat(context.getBean(JobRepository.class)
.getLastJobExecution("test", new JobParameters())).isNull();
});
} }
@EnableBatchProcessing @EnableBatchProcessing

@ -80,8 +80,7 @@ public class JobLauncherCommandLineRunnerTests {
this.step = this.steps.get("step").tasklet(tasklet).build(); this.step = this.steps.get("step").tasklet(tasklet).build();
this.job = this.jobs.get("job").start(this.step).build(); this.job = this.jobs.get("job").start(this.step).build();
this.jobExplorer = this.context.getBean(JobExplorer.class); this.jobExplorer = this.context.getBean(JobExplorer.class);
this.runner = new JobLauncherCommandLineRunner(jobLauncher, this.runner = new JobLauncherCommandLineRunner(jobLauncher, this.jobExplorer);
this.jobExplorer);
this.context.getBean(BatchConfiguration.class).clear(); this.context.getBean(BatchConfiguration.class).clear();
} }

@ -50,31 +50,33 @@ public class CassandraAutoConfigurationTests {
@Test @Test
public void createClusterWithOverrides() { public void createClusterWithOverrides() {
this.contextRunner.withPropertyValues( this.contextRunner
"spring.data.cassandra.cluster-name=testcluster").run((context) -> { .withPropertyValues("spring.data.cassandra.cluster-name=testcluster")
assertThat(context).hasSingleBean(Cluster.class); .run((context) -> {
assertThat(context.getBean(Cluster.class).getClusterName()) assertThat(context).hasSingleBean(Cluster.class);
.isEqualTo("testcluster"); assertThat(context.getBean(Cluster.class).getClusterName())
}); .isEqualTo("testcluster");
});
} }
@Test @Test
public void createCustomizeCluster() { public void createCustomizeCluster() {
this.contextRunner.withUserConfiguration( this.contextRunner.withUserConfiguration(MockCustomizerConfig.class)
MockCustomizerConfig.class).run((context) -> { .run((context) -> {
assertThat(context).hasSingleBean(Cluster.class); assertThat(context).hasSingleBean(Cluster.class);
assertThat(context).hasSingleBean(ClusterBuilderCustomizer.class); assertThat(context).hasSingleBean(ClusterBuilderCustomizer.class);
}); });
} }
@Test @Test
public void customizerOverridesAutoConfig() { public void customizerOverridesAutoConfig() {
this.contextRunner.withUserConfiguration(SimpleCustomizerConfig.class) this.contextRunner.withUserConfiguration(SimpleCustomizerConfig.class)
.withPropertyValues("spring.data.cassandra.cluster-name=testcluster").run((context) -> { .withPropertyValues("spring.data.cassandra.cluster-name=testcluster")
assertThat(context).hasSingleBean(Cluster.class); .run((context) -> {
assertThat(context.getBean(Cluster.class).getClusterName()) assertThat(context).hasSingleBean(Cluster.class);
.isEqualTo("overridden-name"); assertThat(context.getBean(Cluster.class).getClusterName())
}); .isEqualTo("overridden-name");
});
} }
@Test @Test
@ -96,22 +98,23 @@ public class CassandraAutoConfigurationTests {
@Test @Test
public void customizePoolOptions() { public void customizePoolOptions() {
this.contextRunner.withPropertyValues( this.contextRunner
"spring.data.cassandra.pool.idle-timeout=42", .withPropertyValues("spring.data.cassandra.pool.idle-timeout=42",
"spring.data.cassandra.pool.pool-timeout=52", "spring.data.cassandra.pool.pool-timeout=52",
"spring.data.cassandra.pool.heartbeat-interval=62", "spring.data.cassandra.pool.heartbeat-interval=62",
"spring.data.cassandra.pool.max-queue-size=72").run((context) -> { "spring.data.cassandra.pool.max-queue-size=72")
assertThat(context).hasSingleBean(Cluster.class); .run((context) -> {
PoolingOptions poolingOptions = context.getBean(Cluster.class) assertThat(context).hasSingleBean(Cluster.class);
.getConfiguration().getPoolingOptions(); PoolingOptions poolingOptions = context.getBean(Cluster.class)
assertThat(poolingOptions.getIdleTimeoutSeconds()).isEqualTo(42); .getConfiguration().getPoolingOptions();
assertThat(poolingOptions.getPoolTimeoutMillis()).isEqualTo(52); assertThat(poolingOptions.getIdleTimeoutSeconds()).isEqualTo(42);
assertThat(poolingOptions.getHeartbeatIntervalSeconds()).isEqualTo(62); assertThat(poolingOptions.getPoolTimeoutMillis()).isEqualTo(52);
assertThat(poolingOptions.getMaxQueueSize()).isEqualTo(72); assertThat(poolingOptions.getHeartbeatIntervalSeconds())
}); .isEqualTo(62);
assertThat(poolingOptions.getMaxQueueSize()).isEqualTo(72);
});
} }
@Configuration @Configuration
static class MockCustomizerConfig { static class MockCustomizerConfig {

@ -30,7 +30,6 @@ import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.RootBeanDefinition; import org.springframework.beans.factory.support.RootBeanDefinition;
import org.springframework.boot.test.context.assertj.AssertableApplicationContext; import org.springframework.boot.test.context.assertj.AssertableApplicationContext;
import org.springframework.boot.test.context.runner.ApplicationContextRunner; import org.springframework.boot.test.context.runner.ApplicationContextRunner;
import org.springframework.boot.test.context.runner.ContextConsumer;
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import; import org.springframework.context.annotation.Import;
@ -55,40 +54,42 @@ public class ConditionalOnBeanTests {
@Test @Test
public void testNameOnBeanCondition() { public void testNameOnBeanCondition() {
this.contextRunner.withUserConfiguration(FooConfiguration.class, this.contextRunner.withUserConfiguration(FooConfiguration.class,
OnBeanNameConfiguration.class).run(hasBarBean()); OnBeanNameConfiguration.class).run(this::hasBarBean);
} }
@Test @Test
public void testNameAndTypeOnBeanCondition() { public void testNameAndTypeOnBeanCondition() {
this.contextRunner.withUserConfiguration(FooConfiguration.class, this.contextRunner
OnBeanNameAndTypeConfiguration.class).run((context) -> .withUserConfiguration(FooConfiguration.class,
assertThat(context).doesNotHaveBean("bar")); OnBeanNameAndTypeConfiguration.class)
.run((context) -> assertThat(context).doesNotHaveBean("bar"));
} }
@Test @Test
public void testNameOnBeanConditionReverseOrder() { public void testNameOnBeanConditionReverseOrder() {
// Ideally this should be true // Ideally this should be true
this.contextRunner.withUserConfiguration(OnBeanNameConfiguration.class, this.contextRunner
FooConfiguration.class).run((context) -> .withUserConfiguration(OnBeanNameConfiguration.class,
assertThat(context).doesNotHaveBean("bar")); FooConfiguration.class)
.run((context) -> assertThat(context).doesNotHaveBean("bar"));
} }
@Test @Test
public void testClassOnBeanCondition() { public void testClassOnBeanCondition() {
this.contextRunner.withUserConfiguration(FooConfiguration.class, this.contextRunner.withUserConfiguration(FooConfiguration.class,
OnBeanClassConfiguration.class).run(hasBarBean()); OnBeanClassConfiguration.class).run(this::hasBarBean);
} }
@Test @Test
public void testClassOnBeanClassNameCondition() { public void testClassOnBeanClassNameCondition() {
this.contextRunner.withUserConfiguration(FooConfiguration.class, this.contextRunner.withUserConfiguration(FooConfiguration.class,
OnBeanClassNameConfiguration.class).run(hasBarBean()); OnBeanClassNameConfiguration.class).run(this::hasBarBean);
} }
@Test @Test
public void testOnBeanConditionWithXml() { public void testOnBeanConditionWithXml() {
this.contextRunner.withUserConfiguration(XmlConfiguration.class, this.contextRunner.withUserConfiguration(XmlConfiguration.class,
OnBeanNameConfiguration.class).run(hasBarBean()); OnBeanNameConfiguration.class).run(this::hasBarBean);
} }
@Test @Test
@ -101,22 +102,23 @@ public class ConditionalOnBeanTests {
@Test @Test
public void testAnnotationOnBeanCondition() { public void testAnnotationOnBeanCondition() {
this.contextRunner.withUserConfiguration(FooConfiguration.class, this.contextRunner.withUserConfiguration(FooConfiguration.class,
OnAnnotationConfiguration.class).run(hasBarBean()); OnAnnotationConfiguration.class).run(this::hasBarBean);
} }
@Test @Test
public void testOnMissingBeanType() throws Exception { public void testOnMissingBeanType() throws Exception {
this.contextRunner.withUserConfiguration(FooConfiguration.class, this.contextRunner
OnBeanMissingClassConfiguration.class).run((context) -> .withUserConfiguration(FooConfiguration.class,
assertThat(context).doesNotHaveBean("bar")); OnBeanMissingClassConfiguration.class)
.run((context) -> assertThat(context).doesNotHaveBean("bar"));
} }
@Test @Test
public void withPropertyPlaceholderClassName() throws Exception { public void withPropertyPlaceholderClassName() throws Exception {
this.contextRunner.withUserConfiguration( this.contextRunner
PropertySourcesPlaceholderConfigurer.class, .withUserConfiguration(PropertySourcesPlaceholderConfigurer.class,
WithPropertyPlaceholderClassName.class, WithPropertyPlaceholderClassName.class,
OnBeanClassConfiguration.class) OnBeanClassConfiguration.class)
.withPropertyValues("mybeanclass=java.lang.String") .withPropertyValues("mybeanclass=java.lang.String")
.run(context -> assertThat(context).hasNotFailed()); .run(context -> assertThat(context).hasNotFailed());
} }
@ -125,19 +127,16 @@ public class ConditionalOnBeanTests {
public void beanProducedByFactoryBeanIsConsideredWhenMatchingOnAnnotation() { public void beanProducedByFactoryBeanIsConsideredWhenMatchingOnAnnotation() {
this.contextRunner.withUserConfiguration(FactoryBeanConfiguration.class, this.contextRunner.withUserConfiguration(FactoryBeanConfiguration.class,
OnAnnotationWithFactoryBeanConfiguration.class).run((context) -> { OnAnnotationWithFactoryBeanConfiguration.class).run((context) -> {
assertThat(context).hasBean("bar"); assertThat(context).hasBean("bar");
assertThat(context).hasSingleBean(ExampleBean.class); assertThat(context).hasSingleBean(ExampleBean.class);
}); });
} }
private ContextConsumer<AssertableApplicationContext> hasBarBean() { private void hasBarBean(AssertableApplicationContext context) {
return (context) -> { assertThat(context).hasBean("bar");
assertThat(context).hasBean("bar"); assertThat(context.getBean("bar")).isEqualTo("bar");
assertThat(context.getBean("bar")).isEqualTo("bar");
};
} }
@Configuration @Configuration
@ConditionalOnBean(name = "foo") @ConditionalOnBean(name = "foo")
protected static class OnBeanNameConfiguration { protected static class OnBeanNameConfiguration {

@ -1,5 +1,5 @@
/* /*
* Copyright 2012-2016 the original author or authors. * Copyright 2012-2017 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -20,7 +20,6 @@ import org.junit.Test;
import org.springframework.boot.test.context.assertj.AssertableApplicationContext; import org.springframework.boot.test.context.assertj.AssertableApplicationContext;
import org.springframework.boot.test.context.runner.ApplicationContextRunner; import org.springframework.boot.test.context.runner.ApplicationContextRunner;
import org.springframework.boot.test.context.runner.ContextConsumer;
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import; import org.springframework.context.annotation.Import;
@ -40,38 +39,38 @@ public class ConditionalOnClassTests {
@Test @Test
public void testVanillaOnClassCondition() { public void testVanillaOnClassCondition() {
this.contextRunner.withUserConfiguration(BasicConfiguration.class, this.contextRunner
FooConfiguration.class).run(hasBarBean()); .withUserConfiguration(BasicConfiguration.class, FooConfiguration.class)
.run(this::hasBarBean);
} }
@Test @Test
public void testMissingOnClassCondition() { public void testMissingOnClassCondition() {
this.contextRunner.withUserConfiguration(MissingConfiguration.class, this.contextRunner
FooConfiguration.class).run((context) -> { .withUserConfiguration(MissingConfiguration.class, FooConfiguration.class)
assertThat(context).doesNotHaveBean("bar"); .run((context) -> {
assertThat(context).hasBean("foo"); assertThat(context).doesNotHaveBean("bar");
assertThat(context.getBean("foo")).isEqualTo("foo"); assertThat(context).hasBean("foo");
}); assertThat(context.getBean("foo")).isEqualTo("foo");
});
} }
@Test @Test
public void testOnClassConditionWithXml() { public void testOnClassConditionWithXml() {
this.contextRunner.withUserConfiguration(BasicConfiguration.class, this.contextRunner
XmlConfiguration.class).run(hasBarBean()); .withUserConfiguration(BasicConfiguration.class, XmlConfiguration.class)
.run(this::hasBarBean);
} }
@Test @Test
public void testOnClassConditionWithCombinedXml() { public void testOnClassConditionWithCombinedXml() {
this.contextRunner.withUserConfiguration(CombinedXmlConfiguration.class) this.contextRunner.withUserConfiguration(CombinedXmlConfiguration.class)
.run(hasBarBean()); .run(this::hasBarBean);
} }
private ContextConsumer<AssertableApplicationContext> hasBarBean() { private void hasBarBean(AssertableApplicationContext context) {
return (context) -> { assertThat(context).hasBean("bar");
assertThat(context).hasBean("bar"); assertThat(context.getBean("bar")).isEqualTo("bar");
assertThat(context.getBean("bar")).isEqualTo("bar");
};
} }
@Configuration @Configuration

@ -19,9 +19,7 @@ package org.springframework.boot.autoconfigure.condition;
import org.junit.Test; import org.junit.Test;
import org.springframework.boot.cloud.CloudPlatform; import org.springframework.boot.cloud.CloudPlatform;
import org.springframework.boot.test.context.assertj.AssertableApplicationContext;
import org.springframework.boot.test.context.runner.ApplicationContextRunner; import org.springframework.boot.test.context.runner.ApplicationContextRunner;
import org.springframework.boot.test.context.runner.ContextConsumer;
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
@ -37,32 +35,21 @@ public class ConditionalOnCloudPlatformTests {
@Test @Test
public void outcomeWhenCloudfoundryPlatformNotPresentShouldNotMatch() { public void outcomeWhenCloudfoundryPlatformNotPresentShouldNotMatch() {
this.contextRunner.withUserConfiguration(CloudFoundryPlatformConfig.class) this.contextRunner.withUserConfiguration(CloudFoundryPlatformConfig.class)
.run(match(false)); .run((context) -> assertThat(context).doesNotHaveBean("foo"));
} }
@Test @Test
public void outcomeWhenCloudfoundryPlatformPresentShouldMatch() { public void outcomeWhenCloudfoundryPlatformPresentShouldMatch() {
this.contextRunner.withUserConfiguration(CloudFoundryPlatformConfig.class) this.contextRunner.withUserConfiguration(CloudFoundryPlatformConfig.class)
.withPropertyValues("VCAP_APPLICATION:---") .withPropertyValues("VCAP_APPLICATION:---")
.run(match(true)); .run((context) -> assertThat(context).hasBean("foo"));
} }
@Test @Test
public void outcomeWhenCloudfoundryPlatformPresentAndMethodTargetShouldMatch() { public void outcomeWhenCloudfoundryPlatformPresentAndMethodTargetShouldMatch() {
this.contextRunner.withUserConfiguration(CloudFoundryPlatformOnMethodConfig.class) this.contextRunner.withUserConfiguration(CloudFoundryPlatformOnMethodConfig.class)
.withPropertyValues("VCAP_APPLICATION:---") .withPropertyValues("VCAP_APPLICATION:---")
.run(match(true)); .run((context) -> assertThat(context).hasBean("foo"));
}
private ContextConsumer<AssertableApplicationContext> match(boolean expected) {
return (context) -> {
if (expected) {
assertThat(context).hasBean("foo");
}
else {
assertThat(context).doesNotHaveBean("foo");
}
};
} }
@Configuration @Configuration

@ -18,9 +18,7 @@ package org.springframework.boot.autoconfigure.condition;
import org.junit.Test; import org.junit.Test;
import org.springframework.boot.test.context.assertj.AssertableApplicationContext;
import org.springframework.boot.test.context.runner.ApplicationContextRunner; import org.springframework.boot.test.context.runner.ApplicationContextRunner;
import org.springframework.boot.test.context.runner.ContextConsumer;
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
@ -39,31 +37,19 @@ public class ConditionalOnExpressionTests {
@Test @Test
public void expressionIsTrue() { public void expressionIsTrue() {
this.contextRunner.withUserConfiguration(BasicConfiguration.class) this.contextRunner.withUserConfiguration(BasicConfiguration.class)
.run(match(true)); .run((context) -> assertThat(context.getBean("foo")).isEqualTo("foo"));
} }
@Test @Test
public void expressionIsFalse() { public void expressionIsFalse() {
this.contextRunner.withUserConfiguration(MissingConfiguration.class) this.contextRunner.withUserConfiguration(MissingConfiguration.class)
.run(match(false)); .run((context) -> assertThat(context).doesNotHaveBean("foo"));
} }
@Test @Test
public void expressionIsNull() { public void expressionIsNull() {
this.contextRunner.withUserConfiguration(NullConfiguration.class) this.contextRunner.withUserConfiguration(NullConfiguration.class)
.run(match(false)); .run((context) -> assertThat(context).doesNotHaveBean("foo"));
}
private ContextConsumer<AssertableApplicationContext> match(boolean expected) {
return (context) -> {
if (expected) {
assertThat(context).hasBean("foo");
assertThat(context.getBean("foo")).isEqualTo("foo");
}
else {
assertThat(context).doesNotHaveBean("foo");
}
};
} }
@Configuration @Configuration

@ -1,5 +1,5 @@
/* /*
* Copyright 2012-2016 the original author or authors. * Copyright 2012-2017 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -29,9 +29,7 @@ import org.junit.Test;
import org.springframework.boot.autoconfigure.condition.ConditionalOnJava.JavaVersion; import org.springframework.boot.autoconfigure.condition.ConditionalOnJava.JavaVersion;
import org.springframework.boot.autoconfigure.condition.ConditionalOnJava.Range; import org.springframework.boot.autoconfigure.condition.ConditionalOnJava.Range;
import org.springframework.boot.test.context.assertj.AssertableApplicationContext;
import org.springframework.boot.test.context.runner.ApplicationContextRunner; import org.springframework.boot.test.context.runner.ApplicationContextRunner;
import org.springframework.boot.test.context.runner.ContextConsumer;
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
import org.springframework.util.ReflectionUtils; import org.springframework.util.ReflectionUtils;
@ -52,17 +50,20 @@ public class ConditionalOnJavaTests {
@Test @Test
public void doesNotMatchIfBetterVersionIsRequired() { public void doesNotMatchIfBetterVersionIsRequired() {
this.contextRunner.withUserConfiguration(Java9Required.class).run(match(false)); this.contextRunner.withUserConfiguration(Java9Required.class)
.run((context) -> assertThat(context).doesNotHaveBean(String.class));
} }
@Test @Test
public void doesNotMatchIfLowerIsRequired() { public void doesNotMatchIfLowerIsRequired() {
this.contextRunner.withUserConfiguration(Java7Required.class).run(match(false)); this.contextRunner.withUserConfiguration(Java7Required.class)
.run((context) -> assertThat(context).doesNotHaveBean(String.class));
} }
@Test @Test
public void matchesIfVersionIsInRange() { public void matchesIfVersionIsInRange() {
this.contextRunner.withUserConfiguration(Java8Required.class).run(match(true)); this.contextRunner.withUserConfiguration(Java8Required.class)
.run((context) -> assertThat(context).hasSingleBean(String.class));
} }
@Test @Test
@ -105,10 +106,8 @@ public class ConditionalOnJavaTests {
private String getJavaVersion(Class<?>... hiddenClasses) throws Exception { private String getJavaVersion(Class<?>... hiddenClasses) throws Exception {
URL[] urls = ((URLClassLoader) getClass().getClassLoader()).getURLs(); URL[] urls = ((URLClassLoader) getClass().getClassLoader()).getURLs();
URLClassLoader classLoader = new ClassHidingClassLoader(urls, hiddenClasses); URLClassLoader classLoader = new ClassHidingClassLoader(urls, hiddenClasses);
Class<?> javaVersionClass = classLoader Class<?> javaVersionClass = classLoader
.loadClass(ConditionalOnJava.JavaVersion.class.getName()); .loadClass(ConditionalOnJava.JavaVersion.class.getName());
Method getJavaVersionMethod = ReflectionUtils.findMethod(javaVersionClass, Method getJavaVersionMethod = ReflectionUtils.findMethod(javaVersionClass,
"getJavaVersion"); "getJavaVersion");
Object javaVersion = ReflectionUtils.invokeMethod(getJavaVersionMethod, null); Object javaVersion = ReflectionUtils.invokeMethod(getJavaVersionMethod, null);
@ -123,17 +122,6 @@ public class ConditionalOnJavaTests {
assertThat(outcome.isMatch()).as(outcome.getMessage()).isEqualTo(expected); assertThat(outcome.isMatch()).as(outcome.getMessage()).isEqualTo(expected);
} }
private ContextConsumer<AssertableApplicationContext> match(boolean expected) {
return (context) -> {
if (expected) {
assertThat(context).hasSingleBean(String.class);
}
else {
assertThat(context).doesNotHaveBean(String.class);
}
};
}
private final class ClassHidingClassLoader extends URLClassLoader { private final class ClassHidingClassLoader extends URLClassLoader {
private final List<Class<?>> hiddenClasses; private final List<Class<?>> hiddenClasses;

@ -27,9 +27,7 @@ import org.junit.Test;
import org.springframework.boot.autoconfigure.jndi.JndiPropertiesHidingClassLoader; import org.springframework.boot.autoconfigure.jndi.JndiPropertiesHidingClassLoader;
import org.springframework.boot.autoconfigure.jndi.TestableInitialContextFactory; import org.springframework.boot.autoconfigure.jndi.TestableInitialContextFactory;
import org.springframework.boot.test.context.assertj.AssertableApplicationContext;
import org.springframework.boot.test.context.runner.ApplicationContextRunner; import org.springframework.boot.test.context.runner.ApplicationContextRunner;
import org.springframework.boot.test.context.runner.ContextConsumer;
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
import org.springframework.core.type.AnnotatedTypeMetadata; import org.springframework.core.type.AnnotatedTypeMetadata;
@ -77,22 +75,26 @@ public class ConditionalOnJndiTests {
@Test @Test
public void jndiNotAvailable() { public void jndiNotAvailable() {
this.contextRunner.withUserConfiguration(JndiAvailableConfiguration.class, this.contextRunner
JndiConditionConfiguration.class).run(match(false)); .withUserConfiguration(JndiAvailableConfiguration.class,
JndiConditionConfiguration.class)
.run((context) -> assertThat(context).doesNotHaveBean(String.class));
} }
@Test @Test
public void jndiAvailable() { public void jndiAvailable() {
setupJndi(); setupJndi();
this.contextRunner.withUserConfiguration(JndiAvailableConfiguration.class, this.contextRunner
JndiConditionConfiguration.class).run(match(true)); .withUserConfiguration(JndiAvailableConfiguration.class,
JndiConditionConfiguration.class)
.run((context) -> assertThat(context).hasSingleBean(String.class));
} }
@Test @Test
public void jndiLocationNotBound() { public void jndiLocationNotBound() {
setupJndi(); setupJndi();
this.contextRunner.withUserConfiguration(JndiConditionConfiguration.class) this.contextRunner.withUserConfiguration(JndiConditionConfiguration.class)
.run(match(false)); .run((context) -> assertThat(context).doesNotHaveBean(String.class));
} }
@Test @Test
@ -100,7 +102,7 @@ public class ConditionalOnJndiTests {
setupJndi(); setupJndi();
TestableInitialContextFactory.bind("java:/FooManager", new Object()); TestableInitialContextFactory.bind("java:/FooManager", new Object());
this.contextRunner.withUserConfiguration(JndiConditionConfiguration.class) this.contextRunner.withUserConfiguration(JndiConditionConfiguration.class)
.run(match(true)); .run((context) -> assertThat(context).hasSingleBean(String.class));
} }
@Test @Test
@ -124,17 +126,6 @@ public class ConditionalOnJndiTests {
TestableInitialContextFactory.class.getName()); TestableInitialContextFactory.class.getName());
} }
private ContextConsumer<AssertableApplicationContext> match(boolean expected) {
return (context) -> {
if (expected) {
assertThat(context).hasSingleBean(String.class);
}
else {
assertThat(context).doesNotHaveBean(String.class);
}
};
}
private AnnotatedTypeMetadata mockMetaData(String... value) { private AnnotatedTypeMetadata mockMetaData(String... value) {
AnnotatedTypeMetadata metadata = mock(AnnotatedTypeMetadata.class); AnnotatedTypeMetadata metadata = mock(AnnotatedTypeMetadata.class);
Map<String, Object> attributes = new HashMap<>(); Map<String, Object> attributes = new HashMap<>();

@ -292,20 +292,13 @@ abstract class AbstractApplicationContextRunner<SELF extends AbstractApplication
consumer.accept(context); consumer.accept(context);
} }
catch (Throwable ex) { catch (Throwable ex) {
AnyThrow.throwUnchecked(ex); rethrow(ex);
} }
} }
private static class AnyThrow { @SuppressWarnings("unchecked")
private <E extends Throwable> void rethrow(Throwable e) throws E {
static void throwUnchecked(Throwable e) { throw (E) e;
AnyThrow.throwAny(e);
}
@SuppressWarnings("unchecked")
private static <E extends Throwable> void throwAny(Throwable e) throws E {
throw (E) e;
}
} }
} }

@ -1,5 +1,5 @@
/* /*
* Copyright 2012-2016 the original author or authors. * Copyright 2012-2017 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.

@ -130,11 +130,16 @@ public final class TestPropertyValues {
return call.call(); return call.call();
} }
catch (Exception ex) { catch (Exception ex) {
AnyThrow.throwUnchecked(ex); rethrow(ex);
return null; // never reached throw new IllegalStateException("Original cause not rethrown", ex);
} }
} }
@SuppressWarnings("unchecked")
private <E extends Throwable> void rethrow(Throwable e) throws E {
throw (E) e;
}
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
private void addToSources(MutablePropertySources sources, Type type, String name) { private void addToSources(MutablePropertySources sources, Type type, String name) {
if (sources.contains(name)) { if (sources.contains(name)) {
@ -310,16 +315,4 @@ public final class TestPropertyValues {
} }
private static class AnyThrow {
static void throwUnchecked(Throwable e) {
AnyThrow.throwAny(e);
}
@SuppressWarnings("unchecked")
private static <E extends Throwable> void throwAny(Throwable e) throws E {
throw (E) e;
}
}
} }

@ -153,7 +153,8 @@ public abstract class AbstractApplicationContextRunnerTests<T extends AbstractAp
new HidePackagesClassLoader(Gson.class.getPackage().getName())) new HidePackagesClassLoader(Gson.class.getPackage().getName()))
.run((context) -> { .run((context) -> {
try { try {
ClassUtils.forName(Gson.class.getName(), context.getClassLoader()); ClassUtils.forName(Gson.class.getName(),
context.getClassLoader());
fail("Should have thrown a ClassNotFoundException"); fail("Should have thrown a ClassNotFoundException");
} }
catch (ClassNotFoundException e) { catch (ClassNotFoundException e) {

Loading…
Cancel
Save