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

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

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

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

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

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

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

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

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

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

@ -18,9 +18,7 @@ package org.springframework.boot.autoconfigure.condition;
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.ContextConsumer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@ -39,31 +37,19 @@ public class ConditionalOnExpressionTests {
@Test
public void expressionIsTrue() {
this.contextRunner.withUserConfiguration(BasicConfiguration.class)
.run(match(true));
.run((context) -> assertThat(context.getBean("foo")).isEqualTo("foo"));
}
@Test
public void expressionIsFalse() {
this.contextRunner.withUserConfiguration(MissingConfiguration.class)
.run(match(false));
.run((context) -> assertThat(context).doesNotHaveBean("foo"));
}
@Test
public void expressionIsNull() {
this.contextRunner.withUserConfiguration(NullConfiguration.class)
.run(match(false));
}
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");
}
};
.run((context) -> assertThat(context).doesNotHaveBean("foo"));
}
@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");
* 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.Range;
import org.springframework.boot.test.context.assertj.AssertableApplicationContext;
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.Configuration;
import org.springframework.util.ReflectionUtils;
@ -52,17 +50,20 @@ public class ConditionalOnJavaTests {
@Test
public void doesNotMatchIfBetterVersionIsRequired() {
this.contextRunner.withUserConfiguration(Java9Required.class).run(match(false));
this.contextRunner.withUserConfiguration(Java9Required.class)
.run((context) -> assertThat(context).doesNotHaveBean(String.class));
}
@Test
public void doesNotMatchIfLowerIsRequired() {
this.contextRunner.withUserConfiguration(Java7Required.class).run(match(false));
this.contextRunner.withUserConfiguration(Java7Required.class)
.run((context) -> assertThat(context).doesNotHaveBean(String.class));
}
@Test
public void matchesIfVersionIsInRange() {
this.contextRunner.withUserConfiguration(Java8Required.class).run(match(true));
this.contextRunner.withUserConfiguration(Java8Required.class)
.run((context) -> assertThat(context).hasSingleBean(String.class));
}
@Test
@ -105,10 +106,8 @@ public class ConditionalOnJavaTests {
private String getJavaVersion(Class<?>... hiddenClasses) throws Exception {
URL[] urls = ((URLClassLoader) getClass().getClassLoader()).getURLs();
URLClassLoader classLoader = new ClassHidingClassLoader(urls, hiddenClasses);
Class<?> javaVersionClass = classLoader
.loadClass(ConditionalOnJava.JavaVersion.class.getName());
Method getJavaVersionMethod = ReflectionUtils.findMethod(javaVersionClass,
"getJavaVersion");
Object javaVersion = ReflectionUtils.invokeMethod(getJavaVersionMethod, null);
@ -123,17 +122,6 @@ public class ConditionalOnJavaTests {
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 List<Class<?>> hiddenClasses;

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

@ -292,20 +292,13 @@ abstract class AbstractApplicationContextRunner<SELF extends AbstractApplication
consumer.accept(context);
}
catch (Throwable ex) {
AnyThrow.throwUnchecked(ex);
rethrow(ex);
}
}
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;
}
@SuppressWarnings("unchecked")
private <E extends Throwable> void rethrow(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");
* you may not use this file except in compliance with the License.

@ -130,11 +130,16 @@ public final class TestPropertyValues {
return call.call();
}
catch (Exception ex) {
AnyThrow.throwUnchecked(ex);
return null; // never reached
rethrow(ex);
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")
private void addToSources(MutablePropertySources sources, Type type, String 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()))
.run((context) -> {
try {
ClassUtils.forName(Gson.class.getName(), context.getClassLoader());
ClassUtils.forName(Gson.class.getName(),
context.getClassLoader());
fail("Should have thrown a ClassNotFoundException");
}
catch (ClassNotFoundException e) {

Loading…
Cancel
Save