Merge pull request #15312 from dreis2211

* pr/15312:
  Replace DirectFieldAccessor usages by hasFieldOrPropertyWithValue
pull/15325/head
Stephane Nicoll 6 years ago
commit ce8556e4d3

@ -18,7 +18,6 @@ package org.springframework.boot.actuate.autoconfigure.system;
import org.junit.Test;
import org.springframework.beans.DirectFieldAccessor;
import org.springframework.boot.actuate.autoconfigure.health.HealthIndicatorAutoConfiguration;
import org.springframework.boot.actuate.health.ApplicationHealthIndicator;
import org.springframework.boot.actuate.system.DiskSpaceHealthIndicator;
@ -63,10 +62,9 @@ public class DiskSpaceHealthIndicatorAutoConfigurationTests {
.withPropertyValues("management.health.diskspace.threshold=20MB")
.run((context) -> {
assertThat(context).hasSingleBean(DiskSpaceHealthIndicator.class);
DirectFieldAccessor dfa = new DirectFieldAccessor(
context.getBean(DiskSpaceHealthIndicator.class));
assertThat(dfa.getPropertyValue("threshold"))
.isEqualTo(DataSize.ofMegabytes(20));
assertThat(context.getBean(DiskSpaceHealthIndicator.class))
.hasFieldOrPropertyWithValue("threshold",
DataSize.ofMegabytes(20));
});
}

@ -47,9 +47,7 @@ import org.springframework.amqp.rabbit.core.RabbitMessagingTemplate;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.listener.RabbitListenerContainerFactory;
import org.springframework.amqp.rabbit.retry.MessageRecoverer;
import org.springframework.amqp.rabbit.support.ValueExpression;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.beans.DirectFieldAccessor;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.boot.autoconfigure.AutoConfigurations;
import org.springframework.boot.test.context.assertj.AssertableApplicationContext;
@ -96,7 +94,6 @@ public class RabbitAutoConfigurationTests {
.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);
@ -105,9 +102,8 @@ public class RabbitAutoConfigurationTests {
.isEqualTo(rabbitTemplate);
assertThat(amqpAdmin).isNotNull();
assertThat(connectionFactory.getHost()).isEqualTo("localhost");
assertThat(dfa.getPropertyValue("publisherConfirms"))
.isEqualTo(false);
assertThat(dfa.getPropertyValue("publisherReturns")).isEqualTo(false);
assertThat(connectionFactory.isPublisherConfirms()).isFalse();
assertThat(connectionFactory.isPublisherReturns()).isFalse();
assertThat(context.containsBean("rabbitListenerContainerFactory"))
.as("Listener container factory should be created by default")
.isTrue();
@ -155,11 +151,11 @@ public class RabbitAutoConfigurationTests {
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");
com.rabbitmq.client.ConnectionFactory rcf = connectionFactory
.getRabbitConnectionFactory();
assertThat(rcf.getConnectionTimeout()).isEqualTo(123);
assertThat((Address[]) dfa.getPropertyValue("addresses")).hasSize(1);
assertThat((Address[]) ReflectionTestUtils.getField(connectionFactory,
"addresses")).hasSize(1);
});
}
@ -170,14 +166,15 @@ public class RabbitAutoConfigurationTests {
.run((context) -> {
CachingConnectionFactory connectionFactory = context
.getBean(CachingConnectionFactory.class);
DirectFieldAccessor dfa = new DirectFieldAccessor(connectionFactory);
Address[] addresses = (Address[]) dfa.getPropertyValue("addresses");
Address[] addresses = (Address[]) ReflectionTestUtils
.getField(connectionFactory, "addresses");
assertThat(addresses).hasSize(1);
com.rabbitmq.client.ConnectionFactory rcf = mock(
com.rabbitmq.client.ConnectionFactory.class);
given(rcf.newConnection(isNull(), eq(addresses), anyString()))
.willReturn(mock(Connection.class));
dfa.setPropertyValue("rabbitConnectionFactory", rcf);
ReflectionTestUtils.setField(connectionFactory,
"rabbitConnectionFactory", rcf);
connectionFactory.createConnection();
verify(rcf).newConnection(isNull(), eq(addresses), eq("test#0"));
connectionFactory.resetConnection();
@ -236,9 +233,8 @@ public class RabbitAutoConfigurationTests {
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(connectionFactory.isPublisherConfirms()).isTrue();
assertThat(connectionFactory.isPublisherReturns()).isTrue();
assertThat(getMandatory(rabbitTemplate)).isTrue();
});
}
@ -250,8 +246,8 @@ public class RabbitAutoConfigurationTests {
RabbitTemplate rabbitTemplate = context.getBean(RabbitTemplate.class);
assertThat(rabbitTemplate.getMessageConverter())
.isSameAs(context.getBean("myMessageConverter"));
DirectFieldAccessor dfa = new DirectFieldAccessor(rabbitTemplate);
assertThat(dfa.getPropertyValue("retryTemplate")).isNull();
assertThat(rabbitTemplate)
.hasFieldOrPropertyWithValue("retryTemplate", null);
});
}
@ -267,17 +263,17 @@ public class RabbitAutoConfigurationTests {
"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(rabbitTemplate)
.hasFieldOrPropertyWithValue("receiveTimeout", 123L);
assertThat(rabbitTemplate).hasFieldOrPropertyWithValue("replyTimeout",
456L);
RetryTemplate retryTemplate = (RetryTemplate) ReflectionTestUtils
.getField(rabbitTemplate, "retryTemplate");
assertThat(retryTemplate).isNotNull();
dfa = new DirectFieldAccessor(retryTemplate);
SimpleRetryPolicy retryPolicy = (SimpleRetryPolicy) dfa
.getPropertyValue("retryPolicy");
ExponentialBackOffPolicy backOffPolicy = (ExponentialBackOffPolicy) dfa
.getPropertyValue("backOffPolicy");
SimpleRetryPolicy retryPolicy = (SimpleRetryPolicy) ReflectionTestUtils
.getField(retryTemplate, "retryPolicy");
ExponentialBackOffPolicy backOffPolicy = (ExponentialBackOffPolicy) ReflectionTestUtils
.getField(retryTemplate, "backOffPolicy");
assertThat(retryPolicy.getMaxAttempts()).isEqualTo(4);
assertThat(backOffPolicy.getInitialInterval()).isEqualTo(2000);
assertThat(backOffPolicy.getMultiplier()).isEqualTo(1.5);
@ -293,16 +289,13 @@ public class RabbitAutoConfigurationTests {
"spring.rabbitmq.template.retry.initialInterval:2000")
.run((context) -> {
RabbitTemplate rabbitTemplate = context.getBean(RabbitTemplate.class);
DirectFieldAccessor dfa = new DirectFieldAccessor(rabbitTemplate);
RetryTemplate retryTemplate = (RetryTemplate) dfa
.getPropertyValue("retryTemplate");
RetryTemplate retryTemplate = (RetryTemplate) ReflectionTestUtils
.getField(rabbitTemplate, "retryTemplate");
assertThat(retryTemplate).isNotNull();
dfa = new DirectFieldAccessor(retryTemplate);
assertThat(dfa.getPropertyValue("backOffPolicy"))
.isSameAs(context.getBean(
RabbitRetryTemplateCustomizerConfiguration.class).backOffPolicy);
ExponentialBackOffPolicy backOffPolicy = (ExponentialBackOffPolicy) dfa
.getPropertyValue("backOffPolicy");
ExponentialBackOffPolicy backOffPolicy = (ExponentialBackOffPolicy) ReflectionTestUtils
.getField(retryTemplate, "backOffPolicy");
assertThat(backOffPolicy).isSameAs(context.getBean(
RabbitRetryTemplateCustomizerConfiguration.class).backOffPolicy);
assertThat(backOffPolicy.getInitialInterval()).isEqualTo(100);
});
}
@ -389,13 +382,12 @@ public class RabbitAutoConfigurationTests {
.run((context) -> {
CachingConnectionFactory connectionFactory = context
.getBean(CachingConnectionFactory.class);
DirectFieldAccessor dfa = new DirectFieldAccessor(connectionFactory);
assertThat(dfa.getPropertyValue("channelCacheSize")).isEqualTo(23);
assertThat(dfa.getPropertyValue("cacheMode"))
assertThat(connectionFactory.getChannelCacheSize()).isEqualTo(23);
assertThat(connectionFactory.getCacheMode())
.isEqualTo(CacheMode.CONNECTION);
assertThat(dfa.getPropertyValue("connectionCacheSize")).isEqualTo(2);
assertThat(dfa.getPropertyValue("channelCheckoutTimeout"))
.isEqualTo(1000L);
assertThat(connectionFactory.getConnectionCacheSize()).isEqualTo(2);
assertThat(connectionFactory)
.hasFieldOrPropertyWithValue("channelCheckoutTimeout", 1000L);
});
}
@ -453,10 +445,7 @@ public class RabbitAutoConfigurationTests {
SimpleRabbitListenerContainerFactory.class);
rabbitListenerContainerFactory.setTxSize(10);
verify(rabbitListenerContainerFactory).setTxSize(10);
DirectFieldAccessor dfa = new DirectFieldAccessor(
rabbitListenerContainerFactory);
Advice[] adviceChain = (Advice[]) dfa.getPropertyValue("adviceChain");
assertThat(adviceChain).isNull();
assertThat(rabbitListenerContainerFactory.getAdviceChain()).isNull();
});
}
@ -483,15 +472,15 @@ public class RabbitAutoConfigurationTests {
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);
assertThat(dfa.getPropertyValue("missingQueuesFatal"))
.isEqualTo(false);
checkCommonProps(context, dfa);
assertThat(rabbitListenerContainerFactory)
.hasFieldOrPropertyWithValue("concurrentConsumers", 5);
assertThat(rabbitListenerContainerFactory)
.hasFieldOrPropertyWithValue("maxConcurrentConsumers", 10);
assertThat(rabbitListenerContainerFactory)
.hasFieldOrPropertyWithValue("txSize", 20);
assertThat(rabbitListenerContainerFactory)
.hasFieldOrPropertyWithValue("missingQueuesFatal", false);
checkCommonProps(context, rabbitListenerContainerFactory);
});
}
@ -517,12 +506,11 @@ public class RabbitAutoConfigurationTests {
DirectRabbitListenerContainerFactory rabbitListenerContainerFactory = context
.getBean("rabbitListenerContainerFactory",
DirectRabbitListenerContainerFactory.class);
DirectFieldAccessor dfa = new DirectFieldAccessor(
rabbitListenerContainerFactory);
assertThat(dfa.getPropertyValue("consumersPerQueue")).isEqualTo(5);
assertThat(dfa.getPropertyValue("missingQueuesFatal"))
.isEqualTo(true);
checkCommonProps(context, dfa);
assertThat(rabbitListenerContainerFactory)
.hasFieldOrPropertyWithValue("consumersPerQueue", 5);
assertThat(rabbitListenerContainerFactory)
.hasFieldOrPropertyWithValue("missingQueuesFatal", true);
checkCommonProps(context, rabbitListenerContainerFactory);
});
}
@ -562,15 +550,13 @@ public class RabbitAutoConfigurationTests {
private void assertListenerRetryTemplate(
AbstractRabbitListenerContainerFactory<?> rabbitListenerContainerFactory,
RetryPolicy retryPolicy) {
DirectFieldAccessor dfa = new DirectFieldAccessor(rabbitListenerContainerFactory);
Advice[] adviceChain = (Advice[]) dfa.getPropertyValue("adviceChain");
Advice[] adviceChain = rabbitListenerContainerFactory.getAdviceChain();
assertThat(adviceChain).isNotNull();
assertThat(adviceChain.length).isEqualTo(1);
dfa = new DirectFieldAccessor(adviceChain[0]);
RetryTemplate retryTemplate = (RetryTemplate) dfa
.getPropertyValue("retryOperations");
dfa = new DirectFieldAccessor(retryTemplate);
assertThat(dfa.getPropertyValue("retryPolicy")).isSameAs(retryPolicy);
Advice advice = adviceChain[0];
RetryTemplate retryTemplate = (RetryTemplate) ReflectionTestUtils.getField(advice,
"retryOperations");
assertThat(retryTemplate).hasFieldOrPropertyWithValue("retryPolicy", retryPolicy);
}
@Test
@ -628,36 +614,36 @@ public class RabbitAutoConfigurationTests {
}
private void checkCommonProps(AssertableApplicationContext context,
DirectFieldAccessor dfa) {
assertThat(dfa.getPropertyValue("autoStartup")).isEqualTo(Boolean.FALSE);
assertThat(dfa.getPropertyValue("acknowledgeMode"))
.isEqualTo(AcknowledgeMode.MANUAL);
assertThat(dfa.getPropertyValue("prefetchCount")).isEqualTo(40);
assertThat(dfa.getPropertyValue("messageConverter"))
.isSameAs(context.getBean("myMessageConverter"));
assertThat(dfa.getPropertyValue("defaultRequeueRejected"))
.isEqualTo(Boolean.FALSE);
assertThat(dfa.getPropertyValue("idleEventInterval")).isEqualTo(5L);
Advice[] adviceChain = (Advice[]) dfa.getPropertyValue("adviceChain");
AbstractRabbitListenerContainerFactory containerFactory) {
assertThat(containerFactory).hasFieldOrPropertyWithValue("autoStartup",
Boolean.FALSE);
assertThat(containerFactory).hasFieldOrPropertyWithValue("acknowledgeMode",
AcknowledgeMode.MANUAL);
assertThat(containerFactory).hasFieldOrPropertyWithValue("prefetchCount", 40);
assertThat(containerFactory).hasFieldOrPropertyWithValue("messageConverter",
context.getBean("myMessageConverter"));
assertThat(containerFactory).hasFieldOrPropertyWithValue("defaultRequeueRejected",
Boolean.FALSE);
assertThat(containerFactory).hasFieldOrPropertyWithValue("idleEventInterval", 5L);
Advice[] adviceChain = containerFactory.getAdviceChain();
assertThat(adviceChain).isNotNull();
assertThat(adviceChain.length).isEqualTo(1);
dfa = new DirectFieldAccessor(adviceChain[0]);
Advice advice = adviceChain[0];
MessageRecoverer messageRecoverer = context.getBean("myMessageRecoverer",
MessageRecoverer.class);
MethodInvocationRecoverer<?> mir = (MethodInvocationRecoverer<?>) dfa
.getPropertyValue("recoverer");
MethodInvocationRecoverer<?> mir = (MethodInvocationRecoverer<?>) ReflectionTestUtils
.getField(advice, "recoverer");
Message message = mock(Message.class);
Exception ex = new Exception("test");
mir.recover(new Object[] { "foo", message }, ex);
verify(messageRecoverer).recover(message, ex);
RetryTemplate retryTemplate = (RetryTemplate) dfa
.getPropertyValue("retryOperations");
RetryTemplate retryTemplate = (RetryTemplate) ReflectionTestUtils.getField(advice,
"retryOperations");
assertThat(retryTemplate).isNotNull();
dfa = new DirectFieldAccessor(retryTemplate);
SimpleRetryPolicy retryPolicy = (SimpleRetryPolicy) dfa
.getPropertyValue("retryPolicy");
ExponentialBackOffPolicy backOffPolicy = (ExponentialBackOffPolicy) dfa
.getPropertyValue("backOffPolicy");
SimpleRetryPolicy retryPolicy = (SimpleRetryPolicy) ReflectionTestUtils
.getField(retryTemplate, "retryPolicy");
ExponentialBackOffPolicy backOffPolicy = (ExponentialBackOffPolicy) ReflectionTestUtils
.getField(retryTemplate, "backOffPolicy");
assertThat(retryPolicy.getMaxAttempts()).isEqualTo(4);
assertThat(backOffPolicy.getInitialInterval()).isEqualTo(2000);
assertThat(backOffPolicy.getMultiplier()).isEqualTo(1.5);
@ -825,15 +811,11 @@ public class RabbitAutoConfigurationTests {
AssertableApplicationContext context) {
CachingConnectionFactory connectionFactory = context
.getBean(CachingConnectionFactory.class);
return (com.rabbitmq.client.ConnectionFactory) new DirectFieldAccessor(
connectionFactory).getPropertyValue("rabbitConnectionFactory");
return connectionFactory.getRabbitConnectionFactory();
}
@SuppressWarnings("unchecked")
private boolean getMandatory(RabbitTemplate rabbitTemplate) {
ValueExpression<Boolean> expression = (ValueExpression<Boolean>) new DirectFieldAccessor(
rabbitTemplate).getPropertyValue("mandatoryExpression");
return expression.getValue();
return rabbitTemplate.isMandatoryFor(mock(Message.class));
}
@Configuration

@ -22,7 +22,6 @@ import org.springframework.amqp.rabbit.config.DirectRabbitListenerContainerFacto
import org.springframework.amqp.rabbit.config.SimpleRabbitListenerContainerFactory;
import org.springframework.amqp.rabbit.listener.DirectMessageListenerContainer;
import org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer;
import org.springframework.beans.DirectFieldAccessor;
import static org.assertj.core.api.Assertions.assertThat;
@ -237,24 +236,22 @@ public class RabbitPropertiesTests {
public void simpleContainerUseConsistentDefaultValues() {
SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory();
SimpleMessageListenerContainer container = factory.createListenerContainer();
DirectFieldAccessor dfa = new DirectFieldAccessor(container);
RabbitProperties.SimpleContainer simple = this.properties.getListener()
.getSimple();
assertThat(simple.isAutoStartup()).isEqualTo(container.isAutoStartup());
assertThat(simple.isMissingQueuesFatal())
.isEqualTo(dfa.getPropertyValue("missingQueuesFatal"));
assertThat(container).hasFieldOrPropertyWithValue("missingQueuesFatal",
simple.isMissingQueuesFatal());
}
@Test
public void directContainerUseConsistentDefaultValues() {
DirectRabbitListenerContainerFactory factory = new DirectRabbitListenerContainerFactory();
DirectMessageListenerContainer container = factory.createListenerContainer();
DirectFieldAccessor dfa = new DirectFieldAccessor(container);
RabbitProperties.DirectContainer direct = this.properties.getListener()
.getDirect();
assertThat(direct.isAutoStartup()).isEqualTo(container.isAutoStartup());
assertThat(direct.isMissingQueuesFatal())
.isEqualTo(dfa.getPropertyValue("missingQueuesFatal"));
assertThat(container).hasFieldOrPropertyWithValue("missingQueuesFatal",
direct.isMissingQueuesFatal());
}
}

@ -43,7 +43,6 @@ import org.infinispan.spring.provider.SpringEmbeddedCacheManager;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.DirectFieldAccessor;
import org.springframework.beans.factory.BeanCreationException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.boot.autoconfigure.AutoConfigurations;
@ -69,8 +68,10 @@ import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.test.util.ReflectionTestUtils;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.BDDMockito.given;
@ -284,8 +285,8 @@ public class CacheAutoConfigurationTests extends AbstractCacheAutoConfigurationT
RedisCacheManager cacheManager = getCacheManager(context,
RedisCacheManager.class);
assertThat(cacheManager.getCacheNames()).isEmpty();
org.springframework.data.redis.cache.RedisCacheConfiguration redisCacheConfiguration = (org.springframework.data.redis.cache.RedisCacheConfiguration) new DirectFieldAccessor(
cacheManager).getPropertyValue("defaultCacheConfig");
RedisCacheConfiguration redisCacheConfiguration = getDefaultRedisCacheConfiguration(
cacheManager);
assertThat(redisCacheConfiguration.getTtl())
.isEqualTo(java.time.Duration.ofSeconds(15));
assertThat(redisCacheConfiguration.getAllowCacheNullValues())
@ -307,8 +308,8 @@ public class CacheAutoConfigurationTests extends AbstractCacheAutoConfigurationT
RedisCacheManager cacheManager = getCacheManager(context,
RedisCacheManager.class);
assertThat(cacheManager.getCacheNames()).isEmpty();
org.springframework.data.redis.cache.RedisCacheConfiguration redisCacheConfiguration = (org.springframework.data.redis.cache.RedisCacheConfiguration) new DirectFieldAccessor(
cacheManager).getPropertyValue("defaultCacheConfig");
RedisCacheConfiguration redisCacheConfiguration = getDefaultRedisCacheConfiguration(
cacheManager);
assertThat(redisCacheConfiguration.getTtl())
.isEqualTo(java.time.Duration.ofSeconds(30));
assertThat(redisCacheConfiguration.getKeyPrefixFor(""))
@ -333,8 +334,8 @@ public class CacheAutoConfigurationTests extends AbstractCacheAutoConfigurationT
RedisCacheManager cacheManager = getCacheManager(context,
RedisCacheManager.class);
assertThat(cacheManager.getCacheNames()).containsOnly("foo", "bar");
org.springframework.data.redis.cache.RedisCacheConfiguration redisCacheConfiguration = (org.springframework.data.redis.cache.RedisCacheConfiguration) new DirectFieldAccessor(
cacheManager).getPropertyValue("defaultCacheConfig");
RedisCacheConfiguration redisCacheConfiguration = getDefaultRedisCacheConfiguration(
cacheManager);
assertThat(redisCacheConfiguration.getTtl())
.isEqualTo(java.time.Duration.ofMinutes(0));
assertThat(redisCacheConfiguration.getAllowCacheNullValues())
@ -786,6 +787,12 @@ public class CacheAutoConfigurationTests extends AbstractCacheAutoConfigurationT
.isEqualTo(1L);
}
private RedisCacheConfiguration getDefaultRedisCacheConfiguration(
RedisCacheManager cacheManager) {
return (RedisCacheConfiguration) ReflectionTestUtils.getField(cacheManager,
"defaultCacheConfig");
}
@Configuration
static class EmptyConfiguration {

@ -21,7 +21,6 @@ import java.util.Locale;
import org.junit.Ignore;
import org.junit.Test;
import org.springframework.beans.DirectFieldAccessor;
import org.springframework.boot.autoconfigure.AutoConfigurations;
import org.springframework.boot.test.context.assertj.AssertableApplicationContext;
import org.springframework.boot.test.context.runner.ApplicationContextRunner;
@ -99,8 +98,8 @@ public class MessageSourceAutoConfigurationTests {
private ContextConsumer<AssertableApplicationContext> assertCache(long expected) {
return (context) -> {
assertThat(context).hasSingleBean(MessageSource.class);
assertThat(new DirectFieldAccessor(context.getBean(MessageSource.class))
.getPropertyValue("cacheMillis")).isEqualTo(expected);
assertThat(context.getBean(MessageSource.class))
.hasFieldOrPropertyWithValue("cacheMillis", expected);
};
}
@ -138,9 +137,8 @@ public class MessageSourceAutoConfigurationTests {
@Test
public void testFallbackDefault() {
this.contextRunner.withPropertyValues("spring.messages.basename:test/messages")
.run((context) -> assertThat(
isFallbackToSystemLocale(context.getBean(MessageSource.class)))
.isTrue());
.run((context) -> assertThat(context.getBean(MessageSource.class))
.hasFieldOrPropertyWithValue("fallbackToSystemLocale", true));
}
@Test
@ -148,17 +146,15 @@ public class MessageSourceAutoConfigurationTests {
this.contextRunner
.withPropertyValues("spring.messages.basename:test/messages",
"spring.messages.fallback-to-system-locale:false")
.run((context) -> assertThat(
isFallbackToSystemLocale(context.getBean(MessageSource.class)))
.isFalse());
.run((context) -> assertThat(context.getBean(MessageSource.class))
.hasFieldOrPropertyWithValue("fallbackToSystemLocale", false));
}
@Test
public void testFormatMessageDefault() {
this.contextRunner.withPropertyValues("spring.messages.basename:test/messages")
.run((context) -> assertThat(
isAlwaysUseMessageFormat(context.getBean(MessageSource.class)))
.isFalse());
.run((context) -> assertThat(context.getBean(MessageSource.class))
.hasFieldOrPropertyWithValue("alwaysUseMessageFormat", false));
}
@Test
@ -166,27 +162,15 @@ public class MessageSourceAutoConfigurationTests {
this.contextRunner
.withPropertyValues("spring.messages.basename:test/messages",
"spring.messages.always-use-message-format:true")
.run((context) -> assertThat(
isAlwaysUseMessageFormat(context.getBean(MessageSource.class)))
.isTrue());
}
private boolean isFallbackToSystemLocale(MessageSource messageSource) {
return (boolean) new DirectFieldAccessor(messageSource)
.getPropertyValue("fallbackToSystemLocale");
}
private boolean isAlwaysUseMessageFormat(MessageSource messageSource) {
return (boolean) new DirectFieldAccessor(messageSource)
.getPropertyValue("alwaysUseMessageFormat");
.run((context) -> assertThat(context.getBean(MessageSource.class))
.hasFieldOrPropertyWithValue("alwaysUseMessageFormat", true));
}
@Test
public void testUseCodeAsDefaultMessageDefault() {
this.contextRunner.withPropertyValues("spring.messages.basename:test/messages")
.run((context) -> assertThat(
isUseCodeAsDefaultMessage(context.getBean(MessageSource.class)))
.isFalse());
.run((context) -> assertThat(context.getBean(MessageSource.class))
.hasFieldOrPropertyWithValue("useCodeAsDefaultMessage", false));
}
@Test
@ -194,14 +178,8 @@ public class MessageSourceAutoConfigurationTests {
this.contextRunner
.withPropertyValues("spring.messages.basename:test/messages",
"spring.messages.use-code-as-default-message:true")
.run((context) -> assertThat(
isUseCodeAsDefaultMessage(context.getBean(MessageSource.class)))
.isTrue());
}
private boolean isUseCodeAsDefaultMessage(MessageSource messageSource) {
return (boolean) new DirectFieldAccessor(messageSource)
.getPropertyValue("useCodeAsDefaultMessage");
.run((context) -> assertThat(context.getBean(MessageSource.class))
.hasFieldOrPropertyWithValue("useCodeAsDefaultMessage", true));
}
@Test

@ -21,7 +21,6 @@ import java.util.List;
import org.junit.Test;
import org.springframework.beans.DirectFieldAccessor;
import org.springframework.beans.FatalBeanException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.NoUniqueBeanDefinitionException;
@ -38,6 +37,7 @@ import org.springframework.context.annotation.AnnotationConfigApplicationContext
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.test.util.ReflectionTestUtils;
import org.springframework.util.ClassUtils;
import static org.assertj.core.api.Assertions.assertThat;
@ -227,8 +227,8 @@ public class NoSuchBeanDefinitionFailureAnalyzerTests {
private static void addExclusions(NoSuchBeanDefinitionFailureAnalyzer analyzer,
Class<?>... classes) {
ConditionEvaluationReport report = (ConditionEvaluationReport) new DirectFieldAccessor(
analyzer).getPropertyValue("report");
ConditionEvaluationReport report = (ConditionEvaluationReport) ReflectionTestUtils
.getField(analyzer, "report");
List<String> exclusions = new ArrayList<>(report.getExclusions());
for (Class<?> c : classes) {
exclusions.add(c.getName());

@ -24,13 +24,13 @@ import org.junit.Rule;
import org.junit.Test;
import retrofit2.Retrofit;
import org.springframework.beans.DirectFieldAccessor;
import org.springframework.boot.autoconfigure.AutoConfigurations;
import org.springframework.boot.test.context.assertj.AssertableApplicationContext;
import org.springframework.boot.test.context.runner.ApplicationContextRunner;
import org.springframework.boot.test.rule.OutputCapture;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.test.util.ReflectionTestUtils;
import static org.assertj.core.api.Assertions.assertThat;
@ -118,10 +118,8 @@ public class InfluxDbAutoConfigurationTests {
private int getReadTimeoutProperty(AssertableApplicationContext context) {
InfluxDB influxDB = context.getBean(InfluxDB.class);
Retrofit retrofit = (Retrofit) new DirectFieldAccessor(influxDB)
.getPropertyValue("retrofit");
OkHttpClient callFactory = (OkHttpClient) new DirectFieldAccessor(retrofit)
.getPropertyValue("callFactory");
Retrofit retrofit = (Retrofit) ReflectionTestUtils.getField(influxDB, "retrofit");
OkHttpClient callFactory = (OkHttpClient) retrofit.callFactory();
return callFactory.readTimeoutMillis();
}

@ -20,7 +20,6 @@ import javax.management.MBeanServer;
import org.junit.Test;
import org.springframework.beans.DirectFieldAccessor;
import org.springframework.boot.autoconfigure.AutoConfigurations;
import org.springframework.boot.autoconfigure.integration.IntegrationAutoConfiguration.IntegrationComponentScanConfiguration;
import org.springframework.boot.autoconfigure.jdbc.DataSourceTransactionManagerAutoConfiguration;
@ -213,8 +212,8 @@ public class IntegrationAutoConfigurationTests {
this.contextRunner.withUserConfiguration(MessageSourceConfiguration.class)
.run((context) -> {
assertThat(context).hasBean("myMessageSource");
assertThat(new DirectFieldAccessor(context.getBean("myMessageSource"))
.getPropertyValue("countsEnabled")).isEqualTo(true);
assertThat(((MessageProcessorMessageSource) context
.getBean("myMessageSource")).isCountsEnabled()).isTrue();
});
}

@ -1,5 +1,5 @@
/*
* Copyright 2012-2017 the original author or authors.
* Copyright 2012-2018 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.
@ -27,13 +27,13 @@ import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.springframework.beans.DirectFieldAccessor;
import org.springframework.boot.autoconfigure.jndi.JndiPropertiesHidingClassLoader;
import org.springframework.boot.autoconfigure.jndi.TestableInitialContextFactory;
import org.springframework.boot.test.util.TestPropertyValues;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.jmx.export.MBeanExporter;
import org.springframework.test.util.ReflectionTestUtils;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
@ -110,8 +110,8 @@ public class JndiDataSourceAutoConfigurationTests {
assertThat(this.context.getBean(DataSource.class)).isEqualTo(dataSource);
MBeanExporter exporter = this.context.getBean(MBeanExporter.class);
Set<String> excludedBeans = (Set<String>) new DirectFieldAccessor(exporter)
.getPropertyValue("excludedBeans");
Set<String> excludedBeans = (Set<String>) ReflectionTestUtils.getField(exporter,
"excludedBeans");
assertThat(excludedBeans).containsExactly("dataSource");
}
@ -130,8 +130,8 @@ public class JndiDataSourceAutoConfigurationTests {
assertThat(this.context.getBean(DataSource.class)).isEqualTo(dataSource);
for (MBeanExporter exporter : this.context.getBeansOfType(MBeanExporter.class)
.values()) {
Set<String> excludedBeans = (Set<String>) new DirectFieldAccessor(exporter)
.getPropertyValue("excludedBeans");
Set<String> excludedBeans = (Set<String>) ReflectionTestUtils
.getField(exporter, "excludedBeans");
assertThat(excludedBeans).containsExactly("dataSource");
}
}
@ -151,8 +151,8 @@ public class JndiDataSourceAutoConfigurationTests {
assertThat(this.context.getBean(DataSource.class)).isEqualTo(dataSource);
MBeanExporter exporter = this.context.getBean(MBeanExporter.class);
Set<String> excludedBeans = (Set<String>) new DirectFieldAccessor(exporter)
.getPropertyValue("excludedBeans");
Set<String> excludedBeans = (Set<String>) ReflectionTestUtils.getField(exporter,
"excludedBeans");
assertThat(excludedBeans).isEmpty();
}

@ -1,5 +1,5 @@
/*
* Copyright 2012-2017 the original author or authors.
* Copyright 2012-2018 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.
@ -26,7 +26,6 @@ import org.glassfish.jersey.server.ResourceConfig;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.DirectFieldAccessor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.context.PropertyPlaceholderAutoConfiguration;
import org.springframework.boot.autoconfigure.web.servlet.ServletWebServerFactoryAutoConfiguration;
@ -55,9 +54,8 @@ public class JerseyAutoConfigurationCustomLoadOnStartupTests {
@Test
public void contextLoads() {
assertThat(
new DirectFieldAccessor(this.context.getBean("jerseyServletRegistration"))
.getPropertyValue("loadOnStartup")).isEqualTo(5);
assertThat(this.context.getBean("jerseyServletRegistration"))
.hasFieldOrPropertyWithValue("loadOnStartup", 5);
}
@MinimalWebConfiguration

@ -24,7 +24,6 @@ import org.junit.Test;
import org.messaginghub.pooled.jms.JmsPoolConnectionFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.DirectFieldAccessor;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.boot.autoconfigure.AutoConfigurations;
import org.springframework.boot.autoconfigure.jms.activemq.ActiveMQAutoConfiguration;
@ -184,9 +183,9 @@ public class JmsAutoConfigurationTests {
DefaultMessageListenerContainer container = getContainer(context,
"jmsListenerContainerFactory");
assertThat(container.isSessionTransacted()).isFalse();
assertThat(new DirectFieldAccessor(container)
.getPropertyValue("transactionManager")).isSameAs(
context.getBean(JtaTransactionManager.class));
assertThat(container).hasFieldOrPropertyWithValue(
"transactionManager",
context.getBean(JtaTransactionManager.class));
});
}
@ -197,8 +196,8 @@ public class JmsAutoConfigurationTests {
DefaultMessageListenerContainer container = getContainer(context,
"jmsListenerContainerFactory");
assertThat(container.isSessionTransacted()).isTrue();
assertThat(new DirectFieldAccessor(container)
.getPropertyValue("transactionManager")).isNull();
assertThat(container)
.hasFieldOrPropertyWithValue("transactionManager", null);
});
}
@ -209,8 +208,8 @@ public class JmsAutoConfigurationTests {
DefaultMessageListenerContainer container = getContainer(context,
"jmsListenerContainerFactory");
assertThat(container.isSessionTransacted()).isTrue();
assertThat(new DirectFieldAccessor(container)
.getPropertyValue("transactionManager")).isNull();
assertThat(container)
.hasFieldOrPropertyWithValue("transactionManager", null);
});
}

@ -81,10 +81,8 @@ public class ActiveMQAutoConfigurationTests {
.getBean(CachingConnectionFactory.class);
assertThat(connectionFactory.getTargetConnectionFactory())
.isInstanceOf(ActiveMQConnectionFactory.class);
assertThat(connectionFactory)
.hasFieldOrPropertyWithValue("cacheConsumers", false);
assertThat(connectionFactory)
.hasFieldOrPropertyWithValue("cacheProducers", true);
assertThat(connectionFactory.isCacheConsumers()).isFalse();
assertThat(connectionFactory.isCacheProducers()).isTrue();
assertThat(connectionFactory.getSessionCacheSize()).isEqualTo(1);
});
}
@ -100,10 +98,8 @@ public class ActiveMQAutoConfigurationTests {
assertThat(context).hasSingleBean(CachingConnectionFactory.class);
CachingConnectionFactory connectionFactory = context
.getBean(CachingConnectionFactory.class);
assertThat(connectionFactory)
.hasFieldOrPropertyWithValue("cacheConsumers", true);
assertThat(connectionFactory)
.hasFieldOrPropertyWithValue("cacheProducers", false);
assertThat(connectionFactory.isCacheConsumers()).isTrue();
assertThat(connectionFactory.isCacheProducers()).isFalse();
assertThat(connectionFactory.getSessionCacheSize()).isEqualTo(10);
});
}

@ -81,10 +81,8 @@ public class ArtemisAutoConfigurationTests {
.getBean(CachingConnectionFactory.class);
assertThat(connectionFactory.getTargetConnectionFactory())
.isInstanceOf(ActiveMQConnectionFactory.class);
assertThat(connectionFactory)
.hasFieldOrPropertyWithValue("cacheConsumers", false);
assertThat(connectionFactory)
.hasFieldOrPropertyWithValue("cacheProducers", true);
assertThat(connectionFactory.isCacheConsumers()).isFalse();
assertThat(connectionFactory.isCacheProducers()).isTrue();
assertThat(connectionFactory.getSessionCacheSize()).isEqualTo(1);
});
}
@ -100,10 +98,8 @@ public class ArtemisAutoConfigurationTests {
assertThat(context).hasSingleBean(CachingConnectionFactory.class);
CachingConnectionFactory connectionFactory = context
.getBean(CachingConnectionFactory.class);
assertThat(connectionFactory)
.hasFieldOrPropertyWithValue("cacheConsumers", true);
assertThat(connectionFactory)
.hasFieldOrPropertyWithValue("cacheProducers", false);
assertThat(connectionFactory.isCacheConsumers()).isTrue();
assertThat(connectionFactory.isCacheProducers()).isFalse();
assertThat(connectionFactory.getSessionCacheSize()).isEqualTo(10);
});
}

@ -19,7 +19,6 @@ package org.springframework.boot.autoconfigure.jmx;
import org.junit.After;
import org.junit.Test;
import org.springframework.beans.DirectFieldAccessor;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.boot.autoconfigure.integration.IntegrationAutoConfiguration;
import org.springframework.context.ConfigurableApplicationContext;
@ -139,8 +138,7 @@ public class JmxAutoConfigurationTests {
this.context.refresh();
IntegrationMBeanExporter mbeanExporter = this.context
.getBean(IntegrationMBeanExporter.class);
DirectFieldAccessor dfa = new DirectFieldAccessor(mbeanExporter);
assertThat(dfa.getPropertyValue("domain")).isEqualTo("foo.my");
assertThat(mbeanExporter).hasFieldOrPropertyWithValue("domain", "foo.my");
}
@Configuration

@ -36,7 +36,6 @@ import org.apache.kafka.streams.StreamsBuilder;
import org.apache.kafka.streams.StreamsConfig;
import org.junit.Test;
import org.springframework.beans.DirectFieldAccessor;
import org.springframework.boot.autoconfigure.AutoConfigurations;
import org.springframework.boot.test.context.runner.ApplicationContextRunner;
import org.springframework.context.annotation.Bean;
@ -44,6 +43,7 @@ import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.kafka.annotation.EnableKafkaStreams;
import org.springframework.kafka.annotation.KafkaStreamsDefaultConfiguration;
import org.springframework.kafka.config.AbstractKafkaListenerContainerFactory;
import org.springframework.kafka.config.ConcurrentKafkaListenerContainerFactory;
import org.springframework.kafka.config.KafkaListenerContainerFactory;
import org.springframework.kafka.config.KafkaStreamsConfiguration;
@ -52,6 +52,7 @@ import org.springframework.kafka.core.DefaultKafkaProducerFactory;
import org.springframework.kafka.core.KafkaAdmin;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.kafka.listener.AfterRollbackProcessor;
import org.springframework.kafka.listener.ContainerProperties;
import org.springframework.kafka.listener.ContainerProperties.AckMode;
import org.springframework.kafka.listener.SeekToCurrentErrorHandler;
import org.springframework.kafka.security.jaas.KafkaJaasLoginModuleInitializer;
@ -61,6 +62,7 @@ import org.springframework.kafka.test.utils.KafkaTestUtils;
import org.springframework.kafka.transaction.ChainedKafkaTransactionManager;
import org.springframework.kafka.transaction.KafkaAwareTransactionManager;
import org.springframework.kafka.transaction.KafkaTransactionManager;
import org.springframework.test.util.ReflectionTestUtils;
import org.springframework.transaction.PlatformTransactionManager;
import static org.assertj.core.api.Assertions.assertThat;
@ -448,55 +450,43 @@ public class KafkaAutoConfigurationTests {
.getBean(DefaultKafkaConsumerFactory.class);
KafkaTemplate<?, ?> kafkaTemplate = context
.getBean(KafkaTemplate.class);
KafkaListenerContainerFactory<?> kafkaListenerContainerFactory = context
AbstractKafkaListenerContainerFactory kafkaListenerContainerFactory = (AbstractKafkaListenerContainerFactory) context
.getBean(KafkaListenerContainerFactory.class);
assertThat(kafkaTemplate.getMessageConverter())
.isInstanceOf(MessagingMessageConverter.class);
assertThat(new DirectFieldAccessor(kafkaTemplate)
.getPropertyValue("producerFactory"))
.isEqualTo(producerFactory);
assertThat(kafkaTemplate).hasFieldOrPropertyWithValue(
"producerFactory", producerFactory);
assertThat(kafkaTemplate.getDefaultTopic()).isEqualTo("testTopic");
DirectFieldAccessor dfa = new DirectFieldAccessor(
kafkaListenerContainerFactory);
assertThat(dfa.getPropertyValue("consumerFactory"))
assertThat(kafkaListenerContainerFactory.getConsumerFactory())
.isEqualTo(consumerFactory);
assertThat(dfa.getPropertyValue("containerProperties.ackMode"))
ContainerProperties containerProperties = kafkaListenerContainerFactory
.getContainerProperties();
assertThat(containerProperties.getAckMode())
.isEqualTo(AckMode.MANUAL);
assertThat(dfa.getPropertyValue("containerProperties.clientId"))
.isEqualTo("client");
assertThat(dfa.getPropertyValue("containerProperties.ackCount"))
.isEqualTo(123);
assertThat(dfa.getPropertyValue("containerProperties.ackTime"))
.isEqualTo(456L);
assertThat(dfa.getPropertyValue("concurrency")).isEqualTo(3);
assertThat(dfa.getPropertyValue("containerProperties.pollTimeout"))
.isEqualTo(2000L);
assertThat(
dfa.getPropertyValue("containerProperties.noPollThreshold"))
.isEqualTo(2.5f);
assertThat(
dfa.getPropertyValue("containerProperties.idleEventInterval"))
.isEqualTo(1000L);
assertThat(
dfa.getPropertyValue("containerProperties.monitorInterval"))
.isEqualTo(45);
assertThat(dfa
.getPropertyValue("containerProperties.logContainerConfig"))
.isEqualTo(Boolean.TRUE);
assertThat(dfa.getPropertyValue("batchListener")).isEqualTo(true);
assertThat(containerProperties.getClientId()).isEqualTo("client");
assertThat(containerProperties.getAckCount()).isEqualTo(123);
assertThat(containerProperties.getAckTime()).isEqualTo(456L);
assertThat(containerProperties.getPollTimeout()).isEqualTo(2000L);
assertThat(containerProperties.getNoPollThreshold()).isEqualTo(2.5f);
assertThat(containerProperties.getIdleEventInterval())
.isEqualTo(1000L);
assertThat(containerProperties.getMonitorInterval()).isEqualTo(45);
assertThat(containerProperties.isLogContainerConfig()).isTrue();
assertThat(ReflectionTestUtils.getField(kafkaListenerContainerFactory,
"concurrency")).isEqualTo(3);
assertThat(kafkaListenerContainerFactory.isBatchListener()).isTrue();
assertThat(
context.getBeansOfType(KafkaJaasLoginModuleInitializer.class))
.hasSize(1);
KafkaJaasLoginModuleInitializer jaas = context
.getBean(KafkaJaasLoginModuleInitializer.class);
dfa = new DirectFieldAccessor(jaas);
assertThat(dfa.getPropertyValue("loginModule")).isEqualTo("foo");
assertThat(dfa.getPropertyValue("controlFlag")).isEqualTo(
assertThat(jaas).hasFieldOrPropertyWithValue("loginModule", "foo");
assertThat(jaas).hasFieldOrPropertyWithValue("controlFlag",
AppConfigurationEntry.LoginModuleControlFlag.REQUISITE);
assertThat(context.getBeansOfType(KafkaTransactionManager.class))
.hasSize(1);
assertThat(((Map<String, String>) dfa.getPropertyValue("options")))
.containsExactly(entry("useKeyTab", "true"));
assertThat(((Map<String, String>) ReflectionTestUtils.getField(jaas,
"options"))).containsExactly(entry("useKeyTab", "true"));
});
}
@ -518,10 +508,8 @@ public class KafkaAutoConfigurationTests {
.run((context) -> {
ConcurrentKafkaListenerContainerFactory<?, ?> kafkaListenerContainerFactory = context
.getBean(ConcurrentKafkaListenerContainerFactory.class);
DirectFieldAccessor dfa = new DirectFieldAccessor(
kafkaListenerContainerFactory);
assertThat(dfa.getPropertyValue("messageConverter"))
.isSameAs(context.getBean("myMessageConverter"));
assertThat(kafkaListenerContainerFactory).hasFieldOrPropertyWithValue(
"messageConverter", context.getBean("myMessageConverter"));
});
}
@ -569,9 +557,9 @@ public class KafkaAutoConfigurationTests {
.run((context) -> {
ConcurrentKafkaListenerContainerFactory<?, ?> factory = context
.getBean(ConcurrentKafkaListenerContainerFactory.class);
DirectFieldAccessor dfa = new DirectFieldAccessor(factory);
assertThat(dfa.getPropertyValue("afterRollbackProcessor"))
.isSameAs(context.getBean("afterRollbackProcessor"));
assertThat(factory).hasFieldOrPropertyWithValue(
"afterRollbackProcessor",
context.getBean("afterRollbackProcessor"));
});
}
@ -580,10 +568,8 @@ public class KafkaAutoConfigurationTests {
this.contextRunner.run((context) -> {
ConcurrentKafkaListenerContainerFactory<?, ?> kafkaListenerContainerFactory = context
.getBean(ConcurrentKafkaListenerContainerFactory.class);
DirectFieldAccessor dfa = new DirectFieldAccessor(
kafkaListenerContainerFactory);
assertThat(dfa.getPropertyValue("replyTemplate"))
.isSameAs(context.getBean(KafkaTemplate.class));
assertThat(kafkaListenerContainerFactory).hasFieldOrPropertyWithValue(
"replyTemplate", context.getBean(KafkaTemplate.class));
});
}

@ -37,7 +37,6 @@ import org.quartz.impl.calendar.MonthlyCalendar;
import org.quartz.impl.calendar.WeeklyCalendar;
import org.quartz.simpl.RAMJobStore;
import org.springframework.beans.DirectFieldAccessor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigurations;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
@ -233,16 +232,18 @@ public class QuartzAutoConfigurationTests {
assertThat(context).hasSingleBean(SchedulerFactoryBean.class);
SchedulerFactoryBean schedulerFactory = context
.getBean(SchedulerFactoryBean.class);
DirectFieldAccessor dfa = new DirectFieldAccessor(schedulerFactory);
QuartzProperties properties = new QuartzProperties();
assertThat(properties.isAutoStartup())
.isEqualTo(schedulerFactory.isAutoStartup());
assertThat((int) properties.getStartupDelay().getSeconds())
.isEqualTo(dfa.getPropertyValue("startupDelay"));
assertThat(properties.isWaitForJobsToCompleteOnShutdown()).isEqualTo(
dfa.getPropertyValue("waitForJobsToCompleteOnShutdown"));
assertThat(properties.isOverwriteExistingJobs())
.isEqualTo(dfa.getPropertyValue("overwriteExistingJobs"));
assertThat(schedulerFactory).hasFieldOrPropertyWithValue(
"startupDelay",
(int) properties.getStartupDelay().getSeconds());
assertThat(schedulerFactory).hasFieldOrPropertyWithValue(
"waitForJobsToCompleteOnShutdown",
properties.isWaitForJobsToCompleteOnShutdown());
assertThat(schedulerFactory).hasFieldOrPropertyWithValue(
"overwriteExistingJobs",
properties.isOverwriteExistingJobs());
});
@ -257,13 +258,13 @@ public class QuartzAutoConfigurationTests {
assertThat(context).hasSingleBean(SchedulerFactoryBean.class);
SchedulerFactoryBean schedulerFactory = context
.getBean(SchedulerFactoryBean.class);
DirectFieldAccessor dfa = new DirectFieldAccessor(schedulerFactory);
assertThat(schedulerFactory.isAutoStartup()).isFalse();
assertThat(dfa.getPropertyValue("startupDelay")).isEqualTo(60);
assertThat(dfa.getPropertyValue("waitForJobsToCompleteOnShutdown"))
.isEqualTo(true);
assertThat(dfa.getPropertyValue("overwriteExistingJobs"))
.isEqualTo(true);
assertThat(schedulerFactory)
.hasFieldOrPropertyWithValue("startupDelay", 60);
assertThat(schedulerFactory).hasFieldOrPropertyWithValue(
"waitForJobsToCompleteOnShutdown", true);
assertThat(schedulerFactory)
.hasFieldOrPropertyWithValue("overwriteExistingJobs", true);
});
}
@ -301,8 +302,8 @@ public class QuartzAutoConfigurationTests {
assertThat(context).hasSingleBean(SchedulerFactoryBean.class);
SchedulerFactoryBean schedulerFactory = context
.getBean(SchedulerFactoryBean.class);
DirectFieldAccessor dfa = new DirectFieldAccessor(schedulerFactory);
assertThat(dfa.getPropertyValue("schedulerName")).isEqualTo(schedulerName);
assertThat(schedulerFactory).hasFieldOrPropertyWithValue("schedulerName",
schedulerName);
};
}

@ -1,5 +1,5 @@
/*
* Copyright 2012-2017 the original author or authors.
* Copyright 2012-2018 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.
@ -16,7 +16,6 @@
package org.springframework.boot.autoconfigure.session;
import org.springframework.beans.DirectFieldAccessor;
import org.springframework.boot.test.context.assertj.AssertableReactiveWebApplicationContext;
import org.springframework.boot.test.context.assertj.AssertableWebApplicationContext;
import org.springframework.session.ReactiveSessionRepository;
@ -42,11 +41,6 @@ public abstract class AbstractSessionAutoConfigurationTests {
return type.cast(repository);
}
protected Integer getSessionTimeout(SessionRepository<?> sessionRepository) {
return (Integer) new DirectFieldAccessor(sessionRepository)
.getPropertyValue("defaultMaxInactiveInterval");
}
protected <T extends ReactiveSessionRepository<?>> T validateSessionRepository(
AssertableReactiveWebApplicationContext context, Class<T> type) {
assertThat(context).hasSingleBean(WebSessionManager.class);
@ -57,9 +51,4 @@ public abstract class AbstractSessionAutoConfigurationTests {
return type.cast(repository);
}
protected Integer getSessionTimeout(ReactiveSessionRepository<?> sessionRepository) {
return (Integer) new DirectFieldAccessor(sessionRepository)
.getPropertyValue("defaultMaxInactiveInterval");
}
}

@ -1,5 +1,5 @@
/*
* Copyright 2012-2017 the original author or authors.
* Copyright 2012-2018 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.
@ -18,7 +18,6 @@ package org.springframework.boot.autoconfigure.session;
import org.junit.Test;
import org.springframework.beans.DirectFieldAccessor;
import org.springframework.boot.autoconfigure.AutoConfigurations;
import org.springframework.boot.autoconfigure.data.mongo.MongoDataAutoConfiguration;
import org.springframework.boot.autoconfigure.data.mongo.MongoReactiveDataAutoConfiguration;
@ -87,8 +86,7 @@ public class ReactiveSessionAutoConfigurationMongoTests
return (context) -> {
ReactiveMongoOperationsSessionRepository repository = validateSessionRepository(
context, ReactiveMongoOperationsSessionRepository.class);
assertThat(new DirectFieldAccessor(repository)
.getPropertyValue("collectionName")).isEqualTo(collectionName);
assertThat(repository.getCollectionName()).isEqualTo(collectionName);
};
}

@ -18,7 +18,6 @@ package org.springframework.boot.autoconfigure.session;
import org.junit.Test;
import org.springframework.beans.DirectFieldAccessor;
import org.springframework.boot.autoconfigure.AutoConfigurations;
import org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration;
import org.springframework.boot.autoconfigure.data.redis.RedisReactiveAutoConfiguration;
@ -81,10 +80,9 @@ public class ReactiveSessionAutoConfigurationRedisTests
return (context) -> {
ReactiveRedisOperationsSessionRepository repository = validateSessionRepository(
context, ReactiveRedisOperationsSessionRepository.class);
assertThat(new DirectFieldAccessor(repository).getPropertyValue("namespace"))
.isEqualTo(namespace);
assertThat(new DirectFieldAccessor(repository)
.getPropertyValue("redisFlushMode")).isEqualTo(flushMode);
assertThat(repository).hasFieldOrPropertyWithValue("namespace", namespace);
assertThat(repository).hasFieldOrPropertyWithValue("redisFlushMode",
flushMode);
};
}

@ -1,5 +1,5 @@
/*
* Copyright 2012-2017 the original author or authors.
* Copyright 2012-2018 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 com.hazelcast.core.HazelcastInstance;
import com.hazelcast.core.IMap;
import org.junit.Test;
import org.springframework.beans.DirectFieldAccessor;
import org.springframework.boot.autoconfigure.AutoConfigurations;
import org.springframework.boot.test.context.FilteredClassLoader;
import org.springframework.boot.test.context.assertj.AssertableWebApplicationContext;
@ -94,9 +93,8 @@ public class SessionAutoConfigurationHazelcastTests
.run((context) -> {
HazelcastSessionRepository repository = validateSessionRepository(
context, HazelcastSessionRepository.class);
assertThat(new DirectFieldAccessor(repository)
.getPropertyValue("hazelcastFlushMode"))
.isEqualTo(HazelcastFlushMode.IMMEDIATE);
assertThat(repository).hasFieldOrPropertyWithValue(
"hazelcastFlushMode", HazelcastFlushMode.IMMEDIATE);
});
}

@ -18,7 +18,6 @@ package org.springframework.boot.autoconfigure.session;
import org.junit.Test;
import org.springframework.beans.DirectFieldAccessor;
import org.springframework.boot.autoconfigure.AutoConfigurations;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.autoconfigure.jdbc.DataSourceTransactionManagerAutoConfiguration;
@ -72,16 +71,15 @@ public class SessionAutoConfigurationJdbcTests
private void validateDefaultConfig(AssertableWebApplicationContext context) {
JdbcOperationsSessionRepository repository = validateSessionRepository(context,
JdbcOperationsSessionRepository.class);
assertThat(new DirectFieldAccessor(repository).getPropertyValue("tableName"))
.isEqualTo("SPRING_SESSION");
assertThat(repository).hasFieldOrPropertyWithValue("tableName", "SPRING_SESSION");
assertThat(context.getBean(JdbcSessionProperties.class).getInitializeSchema())
.isEqualTo(DataSourceInitializationMode.EMBEDDED);
assertThat(context.getBean(JdbcOperations.class)
.queryForList("select * from SPRING_SESSION")).isEmpty();
SpringBootJdbcHttpSessionConfiguration configuration = context
.getBean(SpringBootJdbcHttpSessionConfiguration.class);
assertThat(new DirectFieldAccessor(configuration).getPropertyValue("cleanupCron"))
.isEqualTo("0 * * * * *");
assertThat(configuration).hasFieldOrPropertyWithValue("cleanupCron",
"0 * * * * *");
}
@Test
@ -100,8 +98,8 @@ public class SessionAutoConfigurationJdbcTests
"spring.session.jdbc.initialize-schema=never").run((context) -> {
JdbcOperationsSessionRepository repository = validateSessionRepository(
context, JdbcOperationsSessionRepository.class);
assertThat(new DirectFieldAccessor(repository)
.getPropertyValue("tableName")).isEqualTo("SPRING_SESSION");
assertThat(repository).hasFieldOrPropertyWithValue("tableName",
"SPRING_SESSION");
assertThat(context.getBean(JdbcSessionProperties.class)
.getInitializeSchema())
.isEqualTo(DataSourceInitializationMode.NEVER);
@ -119,8 +117,8 @@ public class SessionAutoConfigurationJdbcTests
.run((context) -> {
JdbcOperationsSessionRepository repository = validateSessionRepository(
context, JdbcOperationsSessionRepository.class);
assertThat(new DirectFieldAccessor(repository)
.getPropertyValue("tableName")).isEqualTo("FOO_BAR");
assertThat(repository).hasFieldOrPropertyWithValue("tableName",
"FOO_BAR");
assertThat(context.getBean(JdbcSessionProperties.class)
.getInitializeSchema())
.isEqualTo(DataSourceInitializationMode.EMBEDDED);
@ -140,8 +138,8 @@ public class SessionAutoConfigurationJdbcTests
.isEqualTo("0 0 12 * * *");
SpringBootJdbcHttpSessionConfiguration configuration = context
.getBean(SpringBootJdbcHttpSessionConfiguration.class);
assertThat(new DirectFieldAccessor(configuration)
.getPropertyValue("cleanupCron")).isEqualTo("0 0 12 * * *");
assertThat(configuration).hasFieldOrPropertyWithValue("cleanupCron",
"0 0 12 * * *");
});
}

@ -1,5 +1,5 @@
/*
* Copyright 2012-2017 the original author or authors.
* Copyright 2012-2018 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.
@ -18,7 +18,6 @@ package org.springframework.boot.autoconfigure.session;
import org.junit.Test;
import org.springframework.beans.DirectFieldAccessor;
import org.springframework.boot.autoconfigure.AutoConfigurations;
import org.springframework.boot.autoconfigure.data.mongo.MongoDataAutoConfiguration;
import org.springframework.boot.autoconfigure.mongo.MongoAutoConfiguration;
@ -82,8 +81,8 @@ public class SessionAutoConfigurationMongoTests
return (context) -> {
MongoOperationsSessionRepository repository = validateSessionRepository(
context, MongoOperationsSessionRepository.class);
assertThat(new DirectFieldAccessor(repository)
.getPropertyValue("collectionName")).isEqualTo(collectionName);
assertThat(repository).hasFieldOrPropertyWithValue("collectionName",
collectionName);
};
}

@ -19,7 +19,6 @@ package org.springframework.boot.autoconfigure.session;
import org.junit.ClassRule;
import org.junit.Test;
import org.springframework.beans.DirectFieldAccessor;
import org.springframework.boot.autoconfigure.AutoConfigurations;
import org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration;
import org.springframework.boot.autoconfigure.session.RedisSessionConfiguration.SpringBootRedisHttpSessionConfiguration;
@ -94,12 +93,12 @@ public class SessionAutoConfigurationRedisTests
context, RedisOperationsSessionRepository.class);
assertThat(repository.getSessionCreatedChannelPrefix())
.isEqualTo(sessionCreatedChannelPrefix);
assertThat(new DirectFieldAccessor(repository)
.getPropertyValue("redisFlushMode")).isEqualTo(flushMode);
assertThat(repository).hasFieldOrPropertyWithValue("redisFlushMode",
flushMode);
SpringBootRedisHttpSessionConfiguration configuration = context
.getBean(SpringBootRedisHttpSessionConfiguration.class);
assertThat(new DirectFieldAccessor(configuration)
.getPropertyValue("cleanupCron")).isEqualTo(cleanupCron);
assertThat(configuration).hasFieldOrPropertyWithValue("cleanupCron",
cleanupCron);
};
}

@ -23,7 +23,6 @@ import java.util.function.Consumer;
import org.junit.Rule;
import org.junit.Test;
import org.springframework.beans.DirectFieldAccessor;
import org.springframework.boot.autoconfigure.AutoConfigurations;
import org.springframework.boot.task.TaskExecutorBuilder;
import org.springframework.boot.task.TaskExecutorCustomizer;
@ -70,12 +69,12 @@ public class TaskExecutionAutoConfigurationTests {
"spring.task.execution.pool.keep-alive=5s",
"spring.task.execution.thread-name-prefix=mytest-")
.run(assertTaskExecutor((taskExecutor) -> {
DirectFieldAccessor dfa = new DirectFieldAccessor(taskExecutor);
assertThat(dfa.getPropertyValue("queueCapacity")).isEqualTo(10);
assertThat(taskExecutor).hasFieldOrPropertyWithValue("queueCapacity",
10);
assertThat(taskExecutor.getCorePoolSize()).isEqualTo(2);
assertThat(taskExecutor.getMaxPoolSize()).isEqualTo(4);
assertThat(dfa.getPropertyValue("allowCoreThreadTimeOut"))
.isEqualTo(true);
assertThat(taskExecutor)
.hasFieldOrPropertyWithValue("allowCoreThreadTimeOut", true);
assertThat(taskExecutor.getKeepAliveSeconds()).isEqualTo(5);
assertThat(taskExecutor.getThreadNamePrefix()).isEqualTo("mytest-");
}));

@ -27,7 +27,6 @@ import javax.validation.constraints.Size;
import org.junit.After;
import org.junit.Test;
import org.springframework.beans.DirectFieldAccessor;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.boot.autoconfigure.validation.ValidationAutoConfigurationTests.CustomValidatorConfiguration.TestBeanPostProcessor;
import org.springframework.boot.test.util.TestPropertyValues;
@ -35,6 +34,7 @@ import org.springframework.context.annotation.AnnotationConfigApplicationContext
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.test.util.ReflectionTestUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.validation.beanvalidation.CustomValidatorBean;
import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean;
@ -195,9 +195,8 @@ public class ValidationAutoConfigurationTests {
.isSameAs(userMethodValidationPostProcessor);
assertThat(this.context.getBeansOfType(MethodValidationPostProcessor.class))
.hasSize(1);
assertThat(this.context.getBean(Validator.class))
.isNotSameAs(new DirectFieldAccessor(userMethodValidationPostProcessor)
.getPropertyValue("validator"));
assertThat(this.context.getBean(Validator.class)).isNotSameAs(ReflectionTestUtils
.getField(userMethodValidationPostProcessor, "validator"));
}
@Test

@ -27,7 +27,6 @@ import javax.validation.ValidatorFactory;
import org.joda.time.DateTime;
import org.junit.Test;
import org.springframework.beans.DirectFieldAccessor;
import org.springframework.boot.autoconfigure.AutoConfigurations;
import org.springframework.boot.autoconfigure.validation.ValidationAutoConfiguration;
import org.springframework.boot.autoconfigure.validation.ValidatorAdapter;
@ -355,9 +354,8 @@ public class WebFluxAutoConfigurationTests {
Validator validator = context.getBean(Validator.class);
assertThat(validator).isInstanceOf(ValidatorAdapter.class);
Validator target = ((ValidatorAdapter) validator).getTarget();
assertThat(new DirectFieldAccessor(target)
.getPropertyValue("targetValidator"))
.isSameAs(context.getBean("customValidator"));
assertThat(target).hasFieldOrPropertyWithValue("targetValidator",
context.getBean("customValidator"));
});
}

@ -21,7 +21,6 @@ import javax.servlet.http.HttpServletRequest;
import org.junit.Test;
import org.springframework.beans.DirectFieldAccessor;
import org.springframework.boot.autoconfigure.AutoConfigurations;
import org.springframework.boot.test.context.runner.WebApplicationContextRunner;
import org.springframework.boot.web.servlet.MultipartConfigFactory;
@ -178,9 +177,8 @@ public class DispatcherServletAutoConfigurationTests {
.containsExactly(false);
assertThat(dispatcherServlet).extracting("enableLoggingRequestDetails")
.containsExactly(false);
assertThat(new DirectFieldAccessor(
context.getBean("dispatcherServletRegistration"))
.getPropertyValue("loadOnStartup")).isEqualTo(-1);
assertThat(context.getBean("dispatcherServletRegistration"))
.hasFieldOrPropertyWithValue("loadOnStartup", -1);
});
}
@ -201,9 +199,8 @@ public class DispatcherServletAutoConfigurationTests {
.containsExactly(false);
assertThat(dispatcherServlet).extracting("dispatchTraceRequest")
.containsExactly(true);
assertThat(new DirectFieldAccessor(
context.getBean("dispatcherServletRegistration"))
.getPropertyValue("loadOnStartup")).isEqualTo(5);
assertThat(context.getBean("dispatcherServletRegistration"))
.hasFieldOrPropertyWithValue("loadOnStartup", 5);
});
}

@ -21,7 +21,7 @@ import java.util.List;
import org.apache.commons.logging.Log;
import org.junit.Test;
import org.springframework.beans.DirectFieldAccessor;
import org.springframework.test.util.ReflectionTestUtils;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
@ -174,10 +174,8 @@ public class DeferredLogTests {
@SuppressWarnings("unchecked")
@Test
public void switchTo() {
DirectFieldAccessor deferredLogFieldAccessor = new DirectFieldAccessor(
this.deferredLog);
List<String> lines = (List<String>) deferredLogFieldAccessor
.getPropertyValue("lines");
List<String> lines = (List<String>) ReflectionTestUtils.getField(this.deferredLog,
"lines");
assertThat(lines).isEmpty();
this.deferredLog.error(this.message, this.throwable);

@ -22,7 +22,6 @@ import java.util.Set;
import org.junit.Test;
import org.springframework.beans.DirectFieldAccessor;
import org.springframework.core.task.TaskDecorator;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.test.util.ReflectionTestUtils;
@ -48,11 +47,10 @@ public class TaskExecutorBuilderTests {
ThreadPoolTaskExecutor executor = this.builder.queueCapacity(10).corePoolSize(4)
.maxPoolSize(8).allowCoreThreadTimeOut(true)
.keepAlive(Duration.ofMinutes(1)).build();
DirectFieldAccessor dfa = new DirectFieldAccessor(executor);
assertThat(dfa.getPropertyValue("queueCapacity")).isEqualTo(10);
assertThat(executor).hasFieldOrPropertyWithValue("queueCapacity", 10);
assertThat(executor.getCorePoolSize()).isEqualTo(4);
assertThat(executor.getMaxPoolSize()).isEqualTo(8);
assertThat(dfa.getPropertyValue("allowCoreThreadTimeOut")).isEqualTo(true);
assertThat(executor).hasFieldOrPropertyWithValue("allowCoreThreadTimeOut", true);
assertThat(executor.getKeepAliveSeconds()).isEqualTo(60);
}

@ -25,7 +25,6 @@ import org.junit.After;
import org.junit.Rule;
import org.junit.Test;
import org.springframework.beans.DirectFieldAccessor;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.context.event.ApplicationEnvironmentPreparedEvent;
@ -100,13 +99,11 @@ public class SpringBootServletInitializerTests {
}
@Test
@SuppressWarnings("rawtypes")
public void mainClassHasSensibleDefault() {
new WithConfigurationAnnotation()
.createRootApplicationContext(this.servletContext);
Class mainApplicationClass = (Class<?>) new DirectFieldAccessor(this.application)
.getPropertyValue("mainApplicationClass");
assertThat(mainApplicationClass).isEqualTo(WithConfigurationAnnotation.class);
assertThat(this.application).hasFieldOrPropertyWithValue("mainApplicationClass",
WithConfigurationAnnotation.class);
}
@Test

Loading…
Cancel
Save