Upgrade to spring-javaformat 0.0.11

This commit is contained in:
Andy Wilkinson
2019-06-07 09:44:58 +01:00
parent d548c5ed31
commit 8f1be4cded
1940 changed files with 16814 additions and 28498 deletions

View File

@@ -33,14 +33,13 @@ import org.springframework.test.context.MergedContextConfiguration;
*
* @author Phillip Webb
*/
class OverrideAutoConfigurationContextCustomizerFactory
implements ContextCustomizerFactory {
class OverrideAutoConfigurationContextCustomizerFactory implements ContextCustomizerFactory {
@Override
public ContextCustomizer createContextCustomizer(Class<?> testClass,
List<ContextConfigurationAttributes> configurationAttributes) {
OverrideAutoConfiguration annotation = AnnotatedElementUtils
.findMergedAnnotation(testClass, OverrideAutoConfiguration.class);
OverrideAutoConfiguration annotation = AnnotatedElementUtils.findMergedAnnotation(testClass,
OverrideAutoConfiguration.class);
if (annotation != null && !annotation.enabled()) {
return new DisableAutoConfigurationContextCustomizer();
}
@@ -50,14 +49,11 @@ class OverrideAutoConfigurationContextCustomizerFactory
/**
* {@link ContextCustomizer} to disable full auto-configuration.
*/
private static class DisableAutoConfigurationContextCustomizer
implements ContextCustomizer {
private static class DisableAutoConfigurationContextCustomizer implements ContextCustomizer {
@Override
public void customizeContext(ConfigurableApplicationContext context,
MergedContextConfiguration mergedConfig) {
EnvironmentTestUtils.addEnvironment(context,
EnableAutoConfiguration.ENABLED_OVERRIDE_PROPERTY + "=false");
public void customizeContext(ConfigurableApplicationContext context, MergedContextConfiguration mergedConfig) {
EnvironmentTestUtils.addEnvironment(context, EnableAutoConfiguration.ENABLED_OVERRIDE_PROPERTY + "=false");
}
@Override

View File

@@ -35,8 +35,7 @@ import org.springframework.test.context.support.DependencyInjectionTestExecution
* @author Phillip Webb
* @since 1.4.1
*/
public class SpringBootDependencyInjectionTestExecutionListener
extends DependencyInjectionTestExecutionListener {
public class SpringBootDependencyInjectionTestExecutionListener extends DependencyInjectionTestExecutionListener {
@Override
public void prepareTestInstance(TestContext testContext) throws Exception {
@@ -71,10 +70,8 @@ public class SpringBootDependencyInjectionTestExecutionListener
Set<Class<? extends TestExecutionListener>> updated = new LinkedHashSet<Class<? extends TestExecutionListener>>(
listeners.size());
for (Class<? extends TestExecutionListener> listener : listeners) {
updated.add(
listener.equals(DependencyInjectionTestExecutionListener.class)
? SpringBootDependencyInjectionTestExecutionListener.class
: listener);
updated.add(listener.equals(DependencyInjectionTestExecutionListener.class)
? SpringBootDependencyInjectionTestExecutionListener.class : listener);
}
return updated;
}

View File

@@ -34,8 +34,7 @@ class DataMongoTypeExcludeFilter extends AnnotationCustomizableTypeExcludeFilter
private final DataMongoTest annotation;
DataMongoTypeExcludeFilter(Class<?> testClass) {
this.annotation = AnnotatedElementUtils.getMergedAnnotation(testClass,
DataMongoTest.class);
this.annotation = AnnotatedElementUtils.getMergedAnnotation(testClass, DataMongoTest.class);
}
@Override

View File

@@ -47,30 +47,28 @@ public abstract class AnnotationCustomizableTypeExcludeFilter extends TypeExclud
}
@Override
public boolean match(MetadataReader metadataReader,
MetadataReaderFactory metadataReaderFactory) throws IOException {
public boolean match(MetadataReader metadataReader, MetadataReaderFactory metadataReaderFactory)
throws IOException {
if (hasAnnotation()) {
return !(include(metadataReader, metadataReaderFactory)
&& !exclude(metadataReader, metadataReaderFactory));
return !(include(metadataReader, metadataReaderFactory) && !exclude(metadataReader, metadataReaderFactory));
}
return false;
}
protected boolean include(MetadataReader metadataReader,
MetadataReaderFactory metadataReaderFactory) throws IOException {
if (new FilterAnnotations(this.classLoader, getFilters(FilterType.INCLUDE))
.anyMatches(metadataReader, metadataReaderFactory)) {
protected boolean include(MetadataReader metadataReader, MetadataReaderFactory metadataReaderFactory)
throws IOException {
if (new FilterAnnotations(this.classLoader, getFilters(FilterType.INCLUDE)).anyMatches(metadataReader,
metadataReaderFactory)) {
return true;
}
if (isUseDefaultFilters()
&& defaultInclude(metadataReader, metadataReaderFactory)) {
if (isUseDefaultFilters() && defaultInclude(metadataReader, metadataReaderFactory)) {
return true;
}
return false;
}
protected boolean defaultInclude(MetadataReader metadataReader,
MetadataReaderFactory metadataReaderFactory) throws IOException {
protected boolean defaultInclude(MetadataReader metadataReader, MetadataReaderFactory metadataReaderFactory)
throws IOException {
for (Class<?> include : getDefaultIncludes()) {
if (isTypeOrAnnotated(metadataReader, metadataReaderFactory, include)) {
return true;
@@ -84,18 +82,16 @@ public abstract class AnnotationCustomizableTypeExcludeFilter extends TypeExclud
return false;
}
protected boolean exclude(MetadataReader metadataReader,
MetadataReaderFactory metadataReaderFactory) throws IOException {
return new FilterAnnotations(this.classLoader, getFilters(FilterType.EXCLUDE))
.anyMatches(metadataReader, metadataReaderFactory);
protected boolean exclude(MetadataReader metadataReader, MetadataReaderFactory metadataReaderFactory)
throws IOException {
return new FilterAnnotations(this.classLoader, getFilters(FilterType.EXCLUDE)).anyMatches(metadataReader,
metadataReaderFactory);
}
@SuppressWarnings("unchecked")
protected final boolean isTypeOrAnnotated(MetadataReader metadataReader,
MetadataReaderFactory metadataReaderFactory, Class<?> type)
throws IOException {
AnnotationTypeFilter annotationFilter = new AnnotationTypeFilter(
(Class<? extends Annotation>) type);
MetadataReaderFactory metadataReaderFactory, Class<?> type) throws IOException {
AnnotationTypeFilter annotationFilter = new AnnotationTypeFilter((Class<? extends Annotation>) type);
AssignableTypeFilter typeFilter = new AssignableTypeFilter(type);
return annotationFilter.match(metadataReader, metadataReaderFactory)
|| typeFilter.match(metadataReader, metadataReaderFactory);
@@ -129,14 +125,11 @@ public abstract class AnnotationCustomizableTypeExcludeFilter extends TypeExclud
boolean result = true;
result = result && hasAnnotation() == other.hasAnnotation();
for (FilterType filterType : FilterType.values()) {
result &= ObjectUtils.nullSafeEquals(getFilters(filterType),
other.getFilters(filterType));
result &= ObjectUtils.nullSafeEquals(getFilters(filterType), other.getFilters(filterType));
}
result = result && isUseDefaultFilters() == other.isUseDefaultFilters();
result = result && ObjectUtils.nullSafeEquals(getDefaultIncludes(),
other.getDefaultIncludes());
result = result && ObjectUtils.nullSafeEquals(getComponentIncludes(),
other.getComponentIncludes());
result = result && ObjectUtils.nullSafeEquals(getDefaultIncludes(), other.getDefaultIncludes());
result = result && ObjectUtils.nullSafeEquals(getComponentIncludes(), other.getComponentIncludes());
return result;
}
@@ -146,8 +139,7 @@ public abstract class AnnotationCustomizableTypeExcludeFilter extends TypeExclud
int result = 0;
result = prime * result + ObjectUtils.hashCode(hasAnnotation());
for (FilterType filterType : FilterType.values()) {
result = prime * result
+ ObjectUtils.nullSafeHashCode(getFilters(filterType));
result = prime * result + ObjectUtils.nullSafeHashCode(getFilters(filterType));
}
result = prime * result + ObjectUtils.hashCode(isUseDefaultFilters());
result = prime * result + ObjectUtils.nullSafeHashCode(getDefaultIncludes());

View File

@@ -81,8 +81,7 @@ public class FilterAnnotations implements Iterable<TypeFilter> {
"An error occurred while processing a CUSTOM type filter: ");
return BeanUtils.instantiateClass(filterClass, TypeFilter.class);
}
throw new IllegalArgumentException(
"Filter type not supported with Class value: " + filterType);
throw new IllegalArgumentException("Filter type not supported with Class value: " + filterType);
}
private TypeFilter createTypeFilter(FilterType filterType, String pattern) {
@@ -92,8 +91,7 @@ public class FilterAnnotations implements Iterable<TypeFilter> {
case REGEX:
return new RegexPatternTypeFilter(Pattern.compile(pattern));
}
throw new IllegalArgumentException(
"Filter type not supported with String pattern: " + filterType);
throw new IllegalArgumentException("Filter type not supported with String pattern: " + filterType);
}
@Override
@@ -101,8 +99,8 @@ public class FilterAnnotations implements Iterable<TypeFilter> {
return this.filters.iterator();
}
public boolean anyMatches(MetadataReader metadataReader,
MetadataReaderFactory metadataReaderFactory) throws IOException {
public boolean anyMatches(MetadataReader metadataReader, MetadataReaderFactory metadataReaderFactory)
throws IOException {
for (TypeFilter filter : this) {
if (filter.match(metadataReader, metadataReaderFactory)) {
return true;

View File

@@ -38,13 +38,11 @@ import org.springframework.util.ReflectionUtils;
*/
class TypeExcludeFiltersContextCustomizer implements ContextCustomizer {
private static final String EXCLUDE_FILTER_BEAN_NAME = TypeExcludeFilters.class
.getName();
private static final String EXCLUDE_FILTER_BEAN_NAME = TypeExcludeFilters.class.getName();
private final Set<TypeExcludeFilter> filters;
TypeExcludeFiltersContextCustomizer(Class<?> testClass,
Set<Class<? extends TypeExcludeFilter>> filterClasses) {
TypeExcludeFiltersContextCustomizer(Class<?> testClass, Set<Class<? extends TypeExcludeFilter>> filterClasses) {
this.filters = instantiateTypeExcludeFilters(testClass, filterClasses);
}
@@ -57,8 +55,7 @@ class TypeExcludeFiltersContextCustomizer implements ContextCustomizer {
return Collections.unmodifiableSet(filters);
}
private TypeExcludeFilter instantiateTypeExcludeFilter(Class<?> testClass,
Class<?> filterClass) {
private TypeExcludeFilter instantiateTypeExcludeFilter(Class<?> testClass, Class<?> filterClass) {
try {
Constructor<?> constructor = getTypeExcludeFilterConstructor(filterClass);
ReflectionUtils.makeAccessible(constructor);
@@ -68,15 +65,14 @@ class TypeExcludeFiltersContextCustomizer implements ContextCustomizer {
return (TypeExcludeFilter) constructor.newInstance();
}
catch (Exception ex) {
throw new IllegalStateException("Unable to create filter for " + filterClass,
ex);
throw new IllegalStateException("Unable to create filter for " + filterClass, ex);
}
}
@Override
public boolean equals(Object obj) {
return (obj != null && getClass().equals(obj.getClass()) && this.filters
.equals(((TypeExcludeFiltersContextCustomizer) obj).filters));
return (obj != null && getClass().equals(obj.getClass())
&& this.filters.equals(((TypeExcludeFiltersContextCustomizer) obj).filters));
}
@Override
@@ -88,8 +84,7 @@ class TypeExcludeFiltersContextCustomizer implements ContextCustomizer {
public void customizeContext(ConfigurableApplicationContext context,
MergedContextConfiguration mergedContextConfiguration) {
if (!this.filters.isEmpty()) {
context.getBeanFactory().registerSingleton(EXCLUDE_FILTER_BEAN_NAME,
createDelegatingTypeExcludeFilter());
context.getBeanFactory().registerSingleton(EXCLUDE_FILTER_BEAN_NAME, createDelegatingTypeExcludeFilter());
}
}
@@ -97,8 +92,8 @@ class TypeExcludeFiltersContextCustomizer implements ContextCustomizer {
return new TypeExcludeFilter() {
@Override
public boolean match(MetadataReader metadataReader,
MetadataReaderFactory metadataReaderFactory) throws IOException {
public boolean match(MetadataReader metadataReader, MetadataReaderFactory metadataReaderFactory)
throws IOException {
for (TypeExcludeFilter filter : TypeExcludeFiltersContextCustomizer.this.filters) {
if (filter.match(metadataReader, metadataReaderFactory)) {
return true;
@@ -110,8 +105,7 @@ class TypeExcludeFiltersContextCustomizer implements ContextCustomizer {
};
}
private Constructor<?> getTypeExcludeFilterConstructor(Class<?> type)
throws NoSuchMethodException {
private Constructor<?> getTypeExcludeFilterConstructor(Class<?> type) throws NoSuchMethodException {
try {
return type.getDeclaredConstructor(Class.class);
}

View File

@@ -39,8 +39,7 @@ class TypeExcludeFiltersContextCustomizerFactory implements ContextCustomizerFac
@Override
public ContextCustomizer createContextCustomizer(Class<?> testClass,
List<ContextConfigurationAttributes> configurationAttributes) {
TypeExcludeFilters annotation = AnnotatedElementUtils
.findMergedAnnotation(testClass, TypeExcludeFilters.class);
TypeExcludeFilters annotation = AnnotatedElementUtils.findMergedAnnotation(testClass, TypeExcludeFilters.class);
if (annotation != null) {
Set<Class<? extends TypeExcludeFilter>> filterClasses = new LinkedHashSet<Class<? extends TypeExcludeFilter>>(
Arrays.asList(annotation.value()));

View File

@@ -34,8 +34,7 @@ class JdbcTypeExcludeFilter extends AnnotationCustomizableTypeExcludeFilter {
private final JdbcTest annotation;
JdbcTypeExcludeFilter(Class<?> testClass) {
this.annotation = AnnotatedElementUtils.getMergedAnnotation(testClass,
JdbcTest.class);
this.annotation = AnnotatedElementUtils.getMergedAnnotation(testClass, JdbcTest.class);
}
@Override

View File

@@ -64,67 +64,56 @@ public class TestDatabaseAutoConfiguration {
}
@Bean
@ConditionalOnProperty(prefix = "spring.test.database", name = "replace",
havingValue = "AUTO_CONFIGURED")
@ConditionalOnProperty(prefix = "spring.test.database", name = "replace", havingValue = "AUTO_CONFIGURED")
@ConditionalOnMissingBean
public DataSource dataSource() {
return new EmbeddedDataSourceFactory(this.environment).getEmbeddedDatabase();
}
@Bean
@ConditionalOnProperty(prefix = "spring.test.database", name = "replace",
havingValue = "ANY", matchIfMissing = true)
@ConditionalOnProperty(prefix = "spring.test.database", name = "replace", havingValue = "ANY",
matchIfMissing = true)
public static EmbeddedDataSourceBeanFactoryPostProcessor embeddedDataSourceBeanFactoryPostProcessor() {
return new EmbeddedDataSourceBeanFactoryPostProcessor();
}
@Order(Ordered.LOWEST_PRECEDENCE)
private static class EmbeddedDataSourceBeanFactoryPostProcessor
implements BeanDefinitionRegistryPostProcessor {
private static class EmbeddedDataSourceBeanFactoryPostProcessor implements BeanDefinitionRegistryPostProcessor {
private static final Log logger = LogFactory
.getLog(EmbeddedDataSourceBeanFactoryPostProcessor.class);
private static final Log logger = LogFactory.getLog(EmbeddedDataSourceBeanFactoryPostProcessor.class);
@Override
public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry)
throws BeansException {
public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {
Assert.isInstanceOf(ConfigurableListableBeanFactory.class, registry,
"Test Database Auto-configuration can only be "
+ "used with a ConfigurableListableBeanFactory");
"Test Database Auto-configuration can only be " + "used with a ConfigurableListableBeanFactory");
process(registry, (ConfigurableListableBeanFactory) registry);
}
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory)
throws BeansException {
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
}
private void process(BeanDefinitionRegistry registry,
ConfigurableListableBeanFactory beanFactory) {
private void process(BeanDefinitionRegistry registry, ConfigurableListableBeanFactory beanFactory) {
BeanDefinitionHolder holder = getDataSourceBeanDefinition(beanFactory);
if (holder != null) {
String beanName = holder.getBeanName();
boolean primary = holder.getBeanDefinition().isPrimary();
logger.info("Replacing '" + beanName + "' DataSource bean with "
+ (primary ? "primary " : "") + "embedded version");
registry.registerBeanDefinition(beanName,
createEmbeddedBeanDefinition(primary));
logger.info("Replacing '" + beanName + "' DataSource bean with " + (primary ? "primary " : "")
+ "embedded version");
registry.registerBeanDefinition(beanName, createEmbeddedBeanDefinition(primary));
}
}
private BeanDefinition createEmbeddedBeanDefinition(boolean primary) {
BeanDefinition beanDefinition = new RootBeanDefinition(
EmbeddedDataSourceFactoryBean.class);
BeanDefinition beanDefinition = new RootBeanDefinition(EmbeddedDataSourceFactoryBean.class);
beanDefinition.setPrimary(primary);
return beanDefinition;
}
private BeanDefinitionHolder getDataSourceBeanDefinition(
ConfigurableListableBeanFactory beanFactory) {
private BeanDefinitionHolder getDataSourceBeanDefinition(ConfigurableListableBeanFactory beanFactory) {
String[] beanNames = beanFactory.getBeanNamesForType(DataSource.class);
if (ObjectUtils.isEmpty(beanNames)) {
logger.warn("No DataSource beans found, "
+ "embedded version will not be used");
logger.warn("No DataSource beans found, " + "embedded version will not be used");
return null;
}
if (beanNames.length == 1) {
@@ -138,8 +127,7 @@ public class TestDatabaseAutoConfiguration {
return new BeanDefinitionHolder(beanDefinition, beanName);
}
}
logger.warn("No primary DataSource found, "
+ "embedded version will not be used");
logger.warn("No primary DataSource found, " + "embedded version will not be used");
return null;
}
@@ -188,19 +176,16 @@ public class TestDatabaseAutoConfiguration {
}
public EmbeddedDatabase getEmbeddedDatabase() {
EmbeddedDatabaseConnection connection = this.environment.getProperty(
"spring.test.database.connection", EmbeddedDatabaseConnection.class,
EmbeddedDatabaseConnection.NONE);
EmbeddedDatabaseConnection connection = this.environment.getProperty("spring.test.database.connection",
EmbeddedDatabaseConnection.class, EmbeddedDatabaseConnection.NONE);
if (EmbeddedDatabaseConnection.NONE.equals(connection)) {
connection = EmbeddedDatabaseConnection.get(getClass().getClassLoader());
}
Assert.state(connection != EmbeddedDatabaseConnection.NONE,
"Failed to replace DataSource with an embedded database for tests. If "
+ "you want an embedded database please put a supported one "
+ "on the classpath or tune the replace attribute of "
+ "@AutoconfigureTestDatabase.");
return new EmbeddedDatabaseBuilder().generateUniqueName(true)
.setType(connection.getType()).build();
+ "on the classpath or tune the replace attribute of " + "@AutoconfigureTestDatabase.");
return new EmbeddedDatabaseBuilder().generateUniqueName(true).setType(connection.getType()).build();
}
}

View File

@@ -52,8 +52,7 @@ class JsonExcludeFilter extends AnnotationCustomizableTypeExcludeFilter {
private final JsonTest annotation;
JsonExcludeFilter(Class<?> testClass) {
this.annotation = AnnotatedElementUtils.getMergedAnnotation(testClass,
JsonTest.class);
this.annotation = AnnotatedElementUtils.getMergedAnnotation(testClass, JsonTest.class);
}
@Override

View File

@@ -66,8 +66,7 @@ public class JsonTestersAutoConfiguration {
@Bean
@Scope("prototype")
public FactoryBean<BasicJsonTester> basicJsonTesterFactoryBean() {
return new JsonTesterFactoryBean<BasicJsonTester, Void>(BasicJsonTester.class,
null);
return new JsonTesterFactoryBean<BasicJsonTester, Void>(BasicJsonTester.class, null);
}
@Configuration
@@ -77,10 +76,8 @@ public class JsonTestersAutoConfiguration {
@Bean
@Scope("prototype")
@ConditionalOnBean(ObjectMapper.class)
public FactoryBean<JacksonTester<?>> jacksonTesterFactoryBean(
ObjectMapper mapper) {
return new JsonTesterFactoryBean<JacksonTester<?>, ObjectMapper>(
JacksonTester.class, mapper);
public FactoryBean<JacksonTester<?>> jacksonTesterFactoryBean(ObjectMapper mapper) {
return new JsonTesterFactoryBean<JacksonTester<?>, ObjectMapper>(JacksonTester.class, mapper);
}
}
@@ -129,14 +126,12 @@ public class JsonTestersAutoConfiguration {
Constructor<?>[] constructors = this.objectType.getDeclaredConstructors();
for (Constructor<?> constructor : constructors) {
if (constructor.getParameterTypes().length == 1
&& constructor.getParameterTypes()[0]
.isInstance(this.marshaller)) {
&& constructor.getParameterTypes()[0].isInstance(this.marshaller)) {
ReflectionUtils.makeAccessible(constructor);
return (T) BeanUtils.instantiateClass(constructor, this.marshaller);
}
}
throw new IllegalStateException(
this.objectType + " does not have a usable constructor");
throw new IllegalStateException(this.objectType + " does not have a usable constructor");
}
@Override
@@ -149,18 +144,15 @@ public class JsonTestersAutoConfiguration {
/**
* {@link BeanPostProcessor} used to initialize JSON testers.
*/
private static class JsonMarshalTestersBeanPostProcessor
extends InstantiationAwareBeanPostProcessorAdapter {
private static class JsonMarshalTestersBeanPostProcessor extends InstantiationAwareBeanPostProcessorAdapter {
@Override
public Object postProcessAfterInitialization(final Object bean, String beanName)
throws BeansException {
public Object postProcessAfterInitialization(final Object bean, String beanName) throws BeansException {
ReflectionUtils.doWithFields(bean.getClass(), new FieldCallback() {
@Override
public void doWith(Field field)
throws IllegalArgumentException, IllegalAccessException {
public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException {
processField(bean, field);
}
@@ -175,8 +167,7 @@ public class JsonTestersAutoConfiguration {
ReflectionUtils.makeAccessible(field);
Object tester = ReflectionUtils.getField(field, bean);
if (tester != null) {
ReflectionTestUtils.invokeMethod(tester, "initialize",
bean.getClass(), type);
ReflectionTestUtils.invokeMethod(tester, "initialize", bean.getClass(), type);
}
}
}

View File

@@ -34,8 +34,7 @@ class DataJpaTypeExcludeFilter extends AnnotationCustomizableTypeExcludeFilter {
private final DataJpaTest annotation;
DataJpaTypeExcludeFilter(Class<?> testClass) {
this.annotation = AnnotatedElementUtils.getMergedAnnotation(testClass,
DataJpaTest.class);
this.annotation = AnnotatedElementUtils.getMergedAnnotation(testClass, DataJpaTest.class);
}
@Override

View File

@@ -234,8 +234,7 @@ public class TestEntityManager {
* @return the entity manager
*/
public final EntityManager getEntityManager() {
EntityManager manager = EntityManagerFactoryUtils
.getTransactionalEntityManager(this.entityManagerFactory);
EntityManager manager = EntityManagerFactoryUtils.getTransactionalEntityManager(this.entityManagerFactory);
Assert.state(manager != null, "No transactional EntityManager found");
return manager;
}

View File

@@ -39,8 +39,7 @@ public class TestEntityManagerAutoConfiguration {
@Bean
@ConditionalOnMissingBean
public TestEntityManager testEntityManager(
EntityManagerFactory entityManagerFactory) {
public TestEntityManager testEntityManager(EntityManagerFactory entityManagerFactory) {
return new TestEntityManager(entityManagerFactory);
}

View File

@@ -65,19 +65,15 @@ public class AnnotationsPropertySource extends EnumerablePropertySource<Class<?>
return Collections.unmodifiableMap(properties);
}
private void collectProperties(Class<?> root, Class<?> source,
Map<String, Object> properties, Set<Class<?>> seen) {
private void collectProperties(Class<?> root, Class<?> source, Map<String, Object> properties, Set<Class<?>> seen) {
if (source != null && seen.add(source)) {
for (Annotation annotation : getMergedAnnotations(root, source)) {
if (!AnnotationUtils.isInJavaLangAnnotationPackage(annotation)) {
PropertyMapping typeMapping = annotation.annotationType()
.getAnnotation(PropertyMapping.class);
for (Method attribute : annotation.annotationType()
.getDeclaredMethods()) {
PropertyMapping typeMapping = annotation.annotationType().getAnnotation(PropertyMapping.class);
for (Method attribute : annotation.annotationType().getDeclaredMethods()) {
collectProperties(annotation, attribute, typeMapping, properties);
}
collectProperties(root, annotation.annotationType(), properties,
seen);
collectProperties(root, annotation.annotationType(), properties, seen);
}
}
collectProperties(root, source.getSuperclass(), properties, seen);
@@ -90,8 +86,7 @@ public class AnnotationsPropertySource extends EnumerablePropertySource<Class<?>
if (annotations != null) {
for (Annotation annotation : annotations) {
if (!AnnotationUtils.isInJavaLangAnnotationPackage(annotation)) {
Annotation mergedAnnotation = findMergedAnnotation(root,
annotation.annotationType());
Annotation mergedAnnotation = findMergedAnnotation(root, annotation.annotationType());
if (mergedAnnotation != null) {
mergedAnnotations.add(mergedAnnotation);
}
@@ -101,21 +96,18 @@ public class AnnotationsPropertySource extends EnumerablePropertySource<Class<?>
return mergedAnnotations;
}
private Annotation findMergedAnnotation(Class<?> source,
Class<? extends Annotation> annotationType) {
private Annotation findMergedAnnotation(Class<?> source, Class<? extends Annotation> annotationType) {
if (source == null) {
return null;
}
Annotation mergedAnnotation = AnnotatedElementUtils.getMergedAnnotation(source,
annotationType);
Annotation mergedAnnotation = AnnotatedElementUtils.getMergedAnnotation(source, annotationType);
return (mergedAnnotation != null) ? mergedAnnotation
: findMergedAnnotation(source.getSuperclass(), annotationType);
}
private void collectProperties(Annotation annotation, Method attribute,
PropertyMapping typeMapping, Map<String, Object> properties) {
PropertyMapping attributeMapping = AnnotationUtils.getAnnotation(attribute,
PropertyMapping.class);
private void collectProperties(Annotation annotation, Method attribute, PropertyMapping typeMapping,
Map<String, Object> properties) {
PropertyMapping attributeMapping = AnnotationUtils.getAnnotation(attribute, PropertyMapping.class);
SkipPropertyMapping skip = getMappingType(typeMapping, attributeMapping);
if (skip == SkipPropertyMapping.YES) {
return;
@@ -124,8 +116,7 @@ public class AnnotationsPropertySource extends EnumerablePropertySource<Class<?>
ReflectionUtils.makeAccessible(attribute);
Object value = ReflectionUtils.invokeMethod(attribute, annotation);
if (skip == SkipPropertyMapping.ON_DEFAULT_VALUE) {
Object defaultValue = AnnotationUtils.getDefaultValue(annotation,
attribute.getName());
Object defaultValue = AnnotationUtils.getDefaultValue(annotation, attribute.getName());
if (ObjectUtils.nullSafeEquals(value, defaultValue)) {
return;
}
@@ -133,8 +124,7 @@ public class AnnotationsPropertySource extends EnumerablePropertySource<Class<?>
putProperties(name, value, properties);
}
private SkipPropertyMapping getMappingType(PropertyMapping typeMapping,
PropertyMapping attributeMapping) {
private SkipPropertyMapping getMappingType(PropertyMapping typeMapping, PropertyMapping attributeMapping) {
if (attributeMapping != null) {
return attributeMapping.skip();
}
@@ -144,8 +134,7 @@ public class AnnotationsPropertySource extends EnumerablePropertySource<Class<?>
return SkipPropertyMapping.YES;
}
private String getName(PropertyMapping typeMapping, PropertyMapping attributeMapping,
Method attribute) {
private String getName(PropertyMapping typeMapping, PropertyMapping attributeMapping, Method attribute) {
String prefix = (typeMapping != null) ? typeMapping.value() : "";
String name = (attributeMapping != null) ? attributeMapping.value() : "";
if (!StringUtils.hasText(name)) {
@@ -158,8 +147,7 @@ public class AnnotationsPropertySource extends EnumerablePropertySource<Class<?>
Matcher matcher = CAMEL_CASE_PATTERN.matcher(name);
StringBuffer result = new StringBuffer();
while (matcher.find()) {
matcher.appendReplacement(result,
matcher.group(1) + '-' + StringUtils.uncapitalize(matcher.group(2)));
matcher.appendReplacement(result, matcher.group(1) + '-' + StringUtils.uncapitalize(matcher.group(2)));
}
matcher.appendTail(result);
return result.toString().toLowerCase(Locale.ENGLISH);
@@ -172,8 +160,7 @@ public class AnnotationsPropertySource extends EnumerablePropertySource<Class<?>
return postfix;
}
private void putProperties(String name, Object value,
Map<String, Object> properties) {
private void putProperties(String name, Object value, Map<String, Object> properties) {
if (ObjectUtils.isArray(value)) {
Object[] array = ObjectUtils.toObjectArray(value);
for (int i = 0; i < array.length; i++) {

View File

@@ -50,15 +50,14 @@ class PropertyMappingContextCustomizer implements ContextCustomizer {
if (!this.propertySource.isEmpty()) {
context.getEnvironment().getPropertySources().addFirst(this.propertySource);
}
context.getBeanFactory().registerSingleton(
PropertyMappingCheckBeanPostProcessor.class.getName(),
context.getBeanFactory().registerSingleton(PropertyMappingCheckBeanPostProcessor.class.getName(),
new PropertyMappingCheckBeanPostProcessor());
}
@Override
public boolean equals(Object obj) {
return (obj != null && getClass().equals(obj.getClass()) && this.propertySource
.equals(((PropertyMappingContextCustomizer) obj).propertySource));
return (obj != null && getClass().equals(obj.getClass())
&& this.propertySource.equals(((PropertyMappingContextCustomizer) obj).propertySource));
}
@Override
@@ -73,8 +72,7 @@ class PropertyMappingContextCustomizer implements ContextCustomizer {
static class PropertyMappingCheckBeanPostProcessor implements BeanPostProcessor {
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName)
throws BeansException {
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
Class<?> beanClass = bean.getClass();
Set<Class<?>> components = new LinkedHashSet<Class<?>>();
Set<Class<?>> propertyMappings = new LinkedHashSet<Class<?>>();
@@ -93,19 +91,17 @@ class PropertyMappingContextCustomizer implements ContextCustomizer {
beanClass = beanClass.getSuperclass();
}
if (!components.isEmpty() && !propertyMappings.isEmpty()) {
throw new IllegalStateException("The @PropertyMapping "
+ getAnnotationsDescription(propertyMappings)
throw new IllegalStateException("The @PropertyMapping " + getAnnotationsDescription(propertyMappings)
+ " cannot be used in combination with the @Component "
+ getAnnotationsDescription(components));
}
return bean;
}
private boolean isAnnotated(Annotation element,
Class<? extends Annotation> annotationType) {
private boolean isAnnotated(Annotation element, Class<? extends Annotation> annotationType) {
try {
return element.annotationType().equals(annotationType) || AnnotationUtils
.findAnnotation(element.annotationType(), annotationType) != null;
return element.annotationType().equals(annotationType)
|| AnnotationUtils.findAnnotation(element.annotationType(), annotationType) != null;
}
catch (Throwable ex) {
return false;
@@ -123,8 +119,7 @@ class PropertyMappingContextCustomizer implements ContextCustomizer {
}
@Override
public Object postProcessAfterInitialization(Object bean, String beanName)
throws BeansException {
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
return bean;
}

View File

@@ -34,8 +34,7 @@ class PropertyMappingContextCustomizerFactory implements ContextCustomizerFactor
@Override
public ContextCustomizer createContextCustomizer(Class<?> testClass,
List<ContextConfigurationAttributes> configurationAttributes) {
AnnotationsPropertySource propertySource = new AnnotationsPropertySource(
testClass);
AnnotationsPropertySource propertySource = new AnnotationsPropertySource(testClass);
return new PropertyMappingContextCustomizer(propertySource);
}

View File

@@ -57,11 +57,9 @@ public class RestDocsAutoConfiguration {
@Bean
@ConfigurationProperties(prefix = "spring.test.restdocs")
public RestDocsMockMvcBuilderCustomizer restDocumentationConfigurer(
MockMvcRestDocumentationConfigurer configurer,
public RestDocsMockMvcBuilderCustomizer restDocumentationConfigurer(MockMvcRestDocumentationConfigurer configurer,
ObjectProvider<RestDocumentationResultHandler> resultHandler) {
return new RestDocsMockMvcBuilderCustomizer(configurer,
resultHandler.getIfAvailable());
return new RestDocsMockMvcBuilderCustomizer(configurer, resultHandler.getIfAvailable());
}
}

View File

@@ -28,8 +28,7 @@ import org.springframework.util.StringUtils;
*
* @author Andy Wilkinson
*/
class RestDocsMockMvcBuilderCustomizer
implements InitializingBean, MockMvcBuilderCustomizer {
class RestDocsMockMvcBuilderCustomizer implements InitializingBean, MockMvcBuilderCustomizer {
private final MockMvcRestDocumentationConfigurer delegate;

View File

@@ -56,27 +56,22 @@ public class RestDocsTestExecutionListener extends AbstractTestExecutionListener
private static class DocumentationHandler {
private void beforeTestMethod(TestContext testContext) throws Exception {
ManualRestDocumentation restDocumentation = findManualRestDocumentation(
testContext);
ManualRestDocumentation restDocumentation = findManualRestDocumentation(testContext);
if (restDocumentation != null) {
restDocumentation.beforeTest(testContext.getTestClass(),
testContext.getTestMethod().getName());
restDocumentation.beforeTest(testContext.getTestClass(), testContext.getTestMethod().getName());
}
}
private void afterTestMethod(TestContext testContext) {
ManualRestDocumentation restDocumentation = findManualRestDocumentation(
testContext);
ManualRestDocumentation restDocumentation = findManualRestDocumentation(testContext);
if (restDocumentation != null) {
restDocumentation.afterTest();
}
}
private ManualRestDocumentation findManualRestDocumentation(
TestContext testContext) {
private ManualRestDocumentation findManualRestDocumentation(TestContext testContext) {
try {
return testContext.getApplicationContext()
.getBean(ManualRestDocumentation.class);
return testContext.getApplicationContext().getBean(ManualRestDocumentation.class);
}
catch (NoSuchBeanDefinitionException ex) {
return null;

View File

@@ -34,16 +34,14 @@ import org.springframework.restdocs.ManualRestDocumentation;
class RestDocumentationContextProviderRegistrar implements ImportBeanDefinitionRegistrar {
@Override
public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata,
BeanDefinitionRegistry registry) {
public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
Map<String, Object> annotationAttributes = importingClassMetadata
.getAnnotationAttributes(AutoConfigureRestDocs.class.getName());
String outputDir = (String) annotationAttributes.get("outputDir");
AbstractBeanDefinition beanDefinition = BeanDefinitionBuilder
.genericBeanDefinition(ManualRestDocumentation.class)
.addConstructorArgValue(outputDir).getBeanDefinition();
registry.registerBeanDefinition(ManualRestDocumentation.class.getName(),
beanDefinition);
.genericBeanDefinition(ManualRestDocumentation.class).addConstructorArgValue(outputDir)
.getBeanDefinition();
registry.registerBeanDefinition(ManualRestDocumentation.class.getName(), beanDefinition);
}
}

View File

@@ -42,8 +42,7 @@ import org.springframework.web.client.RestTemplate;
* @see AutoConfigureMockRestServiceServer
*/
@Configuration
@ConditionalOnProperty(prefix = "spring.test.webclient.mockrestserviceserver",
name = "enabled")
@ConditionalOnProperty(prefix = "spring.test.webclient.mockrestserviceserver", name = "enabled")
public class MockRestServiceServerAutoConfiguration {
@Bean
@@ -52,8 +51,7 @@ public class MockRestServiceServerAutoConfiguration {
}
@Bean
public MockRestServiceServer mockRestServiceServer(
MockServerRestTemplateCustomizer customizer) {
public MockRestServiceServer mockRestServiceServer(MockServerRestTemplateCustomizer customizer) {
try {
return createDeferredMockRestServiceServer(customizer);
}
@@ -62,8 +60,8 @@ public class MockRestServiceServerAutoConfiguration {
}
}
private MockRestServiceServer createDeferredMockRestServiceServer(
MockServerRestTemplateCustomizer customizer) throws Exception {
private MockRestServiceServer createDeferredMockRestServiceServer(MockServerRestTemplateCustomizer customizer)
throws Exception {
Constructor<MockRestServiceServer> constructor = MockRestServiceServer.class
.getDeclaredConstructor(RequestExpectationManager.class);
constructor.setAccessible(true);
@@ -76,8 +74,7 @@ public class MockRestServiceServerAutoConfiguration {
* {@link MockServerRestTemplateCustomizer#customize(RestTemplate)
* MockServerRestTemplateCustomizer} has been called.
*/
private static class DeferredRequestExpectationManager
implements RequestExpectationManager {
private static class DeferredRequestExpectationManager implements RequestExpectationManager {
private MockServerRestTemplateCustomizer customizer;
@@ -86,14 +83,12 @@ public class MockRestServiceServerAutoConfiguration {
}
@Override
public ResponseActions expectRequest(ExpectedCount count,
RequestMatcher requestMatcher) {
public ResponseActions expectRequest(ExpectedCount count, RequestMatcher requestMatcher) {
return getDelegate().expectRequest(count, requestMatcher);
}
@Override
public ClientHttpResponse validateRequest(ClientHttpRequest request)
throws IOException {
public ClientHttpResponse validateRequest(ClientHttpRequest request) throws IOException {
return getDelegate().validateRequest(request);
}
@@ -104,24 +99,18 @@ public class MockRestServiceServerAutoConfiguration {
@Override
public void reset() {
Map<RestTemplate, RequestExpectationManager> expectationManagers = this.customizer
.getExpectationManagers();
Map<RestTemplate, RequestExpectationManager> expectationManagers = this.customizer.getExpectationManagers();
if (expectationManagers.size() == 1) {
getDelegate().reset();
}
}
private RequestExpectationManager getDelegate() {
Map<RestTemplate, RequestExpectationManager> expectationManagers = this.customizer
.getExpectationManagers();
Assert.state(expectationManagers.size() > 0,
"Unable to use auto-configured MockRestServiceServer since "
+ "MockServerRestTemplateCustomizer has not been bound to "
+ "a RestTemplate");
Assert.state(expectationManagers.size() == 1,
"Unable to use auto-configured MockRestServiceServer since "
+ "MockServerRestTemplateCustomizer has been bound to "
+ "more than one RestTemplate");
Map<RestTemplate, RequestExpectationManager> expectationManagers = this.customizer.getExpectationManagers();
Assert.state(expectationManagers.size() > 0, "Unable to use auto-configured MockRestServiceServer since "
+ "MockServerRestTemplateCustomizer has not been bound to " + "a RestTemplate");
Assert.state(expectationManagers.size() == 1, "Unable to use auto-configured MockRestServiceServer since "
+ "MockServerRestTemplateCustomizer has been bound to " + "more than one RestTemplate");
return expectationManagers.values().iterator().next();
}

View File

@@ -27,14 +27,12 @@ import org.springframework.test.web.client.MockRestServiceServer;
*
* @author Phillip Webb
*/
class MockRestServiceServerResetTestExecutionListener
extends AbstractTestExecutionListener {
class MockRestServiceServerResetTestExecutionListener extends AbstractTestExecutionListener {
@Override
public void afterTestMethod(TestContext testContext) throws Exception {
ApplicationContext applicationContext = testContext.getApplicationContext();
String[] names = applicationContext
.getBeanNamesForType(MockRestServiceServer.class, false, false);
String[] names = applicationContext.getBeanNamesForType(MockRestServiceServer.class, false, false);
for (String name : names) {
applicationContext.getBean(name, MockRestServiceServer.class).reset();
}

View File

@@ -48,8 +48,7 @@ class RestClientExcludeFilter extends AnnotationCustomizableTypeExcludeFilter {
RestClientExcludeFilter.class.getClassLoader()));
}
catch (ClassNotFoundException ex) {
throw new IllegalStateException(
"Failed to load " + DATABIND_MODULE_CLASS_NAME, ex);
throw new IllegalStateException("Failed to load " + DATABIND_MODULE_CLASS_NAME, ex);
}
includes.add(JsonComponent.class);
}
@@ -59,8 +58,7 @@ class RestClientExcludeFilter extends AnnotationCustomizableTypeExcludeFilter {
private final RestClientTest annotation;
RestClientExcludeFilter(Class<?> testClass) {
this.annotation = AnnotatedElementUtils.getMergedAnnotation(testClass,
RestClientTest.class);
this.annotation = AnnotatedElementUtils.getMergedAnnotation(testClass, RestClientTest.class);
}
@Override

View File

@@ -54,19 +54,16 @@ public class MockMvcAutoConfiguration {
private final WebMvcProperties webMvcProperties;
MockMvcAutoConfiguration(WebApplicationContext context,
WebMvcProperties webMvcProperties) {
MockMvcAutoConfiguration(WebApplicationContext context, WebMvcProperties webMvcProperties) {
this.context = context;
this.webMvcProperties = webMvcProperties;
}
@Bean
@ConditionalOnMissingBean(MockMvcBuilder.class)
public DefaultMockMvcBuilder mockMvcBuilder(
List<MockMvcBuilderCustomizer> customizers) {
public DefaultMockMvcBuilder mockMvcBuilder(List<MockMvcBuilderCustomizer> customizers) {
DefaultMockMvcBuilder builder = MockMvcBuilders.webAppContextSetup(this.context);
builder.addDispatcherServletCustomizer(
new MockMvcDispatcherServletCustomizer(this.webMvcProperties));
builder.addDispatcherServletCustomizer(new MockMvcDispatcherServletCustomizer(this.webMvcProperties));
for (MockMvcBuilderCustomizer customizer : customizers) {
customizer.customize(builder);
}
@@ -85,8 +82,7 @@ public class MockMvcAutoConfiguration {
return builder.build();
}
private static class MockMvcDispatcherServletCustomizer
implements DispatcherServletCustomizer {
private static class MockMvcDispatcherServletCustomizer implements DispatcherServletCustomizer {
private final WebMvcProperties webMvcProperties;
@@ -96,12 +92,10 @@ public class MockMvcAutoConfiguration {
@Override
public void customize(DispatcherServlet dispatcherServlet) {
dispatcherServlet.setDispatchOptionsRequest(
this.webMvcProperties.isDispatchOptionsRequest());
dispatcherServlet.setDispatchTraceRequest(
this.webMvcProperties.isDispatchTraceRequest());
dispatcherServlet.setThrowExceptionIfNoHandlerFound(
this.webMvcProperties.isThrowExceptionIfNoHandlerFound());
dispatcherServlet.setDispatchOptionsRequest(this.webMvcProperties.isDispatchOptionsRequest());
dispatcherServlet.setDispatchTraceRequest(this.webMvcProperties.isDispatchTraceRequest());
dispatcherServlet
.setThrowExceptionIfNoHandlerFound(this.webMvcProperties.isThrowExceptionIfNoHandlerFound());
}
}

View File

@@ -26,14 +26,12 @@ import org.springframework.test.context.support.AbstractTestExecutionListener;
*
* @author Phillip Webb
*/
class MockMvcPrintOnlyOnFailureTestExecutionListener
extends AbstractTestExecutionListener {
class MockMvcPrintOnlyOnFailureTestExecutionListener extends AbstractTestExecutionListener {
@Override
public void afterTestMethod(TestContext testContext) throws Exception {
if (testContext.getTestException() != null) {
DeferredLinesWriter writer = DeferredLinesWriter
.get(testContext.getApplicationContext());
DeferredLinesWriter writer = DeferredLinesWriter.get(testContext.getApplicationContext());
if (writer != null) {
writer.writeDeferredResult();
}

View File

@@ -29,8 +29,7 @@ import org.springframework.context.annotation.Import;
* @since 1.4.0
*/
@Configuration
@ConditionalOnProperty(prefix = "spring.test.mockmvc", name = "secure",
havingValue = "true", matchIfMissing = true)
@ConditionalOnProperty(prefix = "spring.test.mockmvc", name = "secure", havingValue = "true", matchIfMissing = true)
@Import({ SecurityAutoConfiguration.class, ServerPropertiesAutoConfiguration.class,
MockMvcSecurityConfiguration.class })
public class MockMvcSecurityAutoConfiguration {

View File

@@ -58,8 +58,7 @@ class MockMvcSecurityConfiguration {
builder.apply(new MockMvcConfigurerAdapter() {
@Override
public RequestPostProcessor beforeMockMvcCreated(
ConfigurableMockMvcBuilder<?> builder,
public RequestPostProcessor beforeMockMvcCreated(ConfigurableMockMvcBuilder<?> builder,
WebApplicationContext context) {
return SecurityMockMvcRequestPostProcessors.testSecurityContext();
}

View File

@@ -39,8 +39,7 @@ import org.springframework.test.web.servlet.htmlunit.MockMvcWebClientBuilder;
@Configuration
@ConditionalOnClass(WebClient.class)
@AutoConfigureAfter(MockMvcAutoConfiguration.class)
@ConditionalOnProperty(prefix = "spring.test.mockmvc.webclient", name = "enabled",
matchIfMissing = true)
@ConditionalOnProperty(prefix = "spring.test.mockmvc.webclient", name = "enabled", matchIfMissing = true)
public class MockMvcWebClientAutoConfiguration {
private final Environment environment;
@@ -53,8 +52,7 @@ public class MockMvcWebClientAutoConfiguration {
@ConditionalOnMissingBean({ WebClient.class, MockMvcWebClientBuilder.class })
@ConditionalOnBean(MockMvc.class)
public MockMvcWebClientBuilder mockMvcWebClientBuilder(MockMvc mockMvc) {
return MockMvcWebClientBuilder.mockMvcSetup(mockMvc)
.withDelegate(new LocalHostWebClient(this.environment));
return MockMvcWebClientBuilder.mockMvcSetup(mockMvc).withDelegate(new LocalHostWebClient(this.environment));
}
@Bean

View File

@@ -41,8 +41,7 @@ import org.springframework.test.web.servlet.htmlunit.webdriver.MockMvcHtmlUnitDr
@Configuration
@ConditionalOnClass(HtmlUnitDriver.class)
@AutoConfigureAfter(MockMvcAutoConfiguration.class)
@ConditionalOnProperty(prefix = "spring.test.mockmvc.webdriver", name = "enabled",
matchIfMissing = true)
@ConditionalOnProperty(prefix = "spring.test.mockmvc.webdriver", name = "enabled", matchIfMissing = true)
public class MockMvcWebDriverAutoConfiguration {
private final Environment environment;
@@ -56,8 +55,7 @@ public class MockMvcWebDriverAutoConfiguration {
@ConditionalOnBean(MockMvc.class)
public MockMvcHtmlUnitDriverBuilder mockMvcHtmlUnitDriverBuilder(MockMvc mockMvc) {
return MockMvcHtmlUnitDriverBuilder.mockMvcSetup(mockMvc)
.withDelegate(new LocalHostWebConnectionHtmlUnitDriver(this.environment,
BrowserVersion.CHROME));
.withDelegate(new LocalHostWebConnectionHtmlUnitDriver(this.environment, BrowserVersion.CHROME));
}
@Bean

View File

@@ -105,8 +105,7 @@ public class SpringBootMockMvcBuilderCustomizer implements MockMvcBuilderCustomi
}
private void addFilters(ConfigurableMockMvcBuilder<?> builder) {
ServletContextInitializerBeans Initializers = new ServletContextInitializerBeans(
this.context);
ServletContextInitializerBeans Initializers = new ServletContextInitializerBeans(this.context);
for (ServletContextInitializer initializer : Initializers) {
if (initializer instanceof FilterRegistrationBean) {
addFilter(builder, (FilterRegistrationBean) initializer);
@@ -117,22 +116,19 @@ public class SpringBootMockMvcBuilderCustomizer implements MockMvcBuilderCustomi
}
}
private void addFilter(ConfigurableMockMvcBuilder<?> builder,
FilterRegistrationBean registration) {
private void addFilter(ConfigurableMockMvcBuilder<?> builder, FilterRegistrationBean registration) {
if (registration.isEnabled()) {
addFilter(builder, registration.getFilter(), registration.getUrlPatterns());
}
}
private void addFilter(ConfigurableMockMvcBuilder<?> builder,
DelegatingFilterProxyRegistrationBean registration) {
private void addFilter(ConfigurableMockMvcBuilder<?> builder, DelegatingFilterProxyRegistrationBean registration) {
if (registration.isEnabled()) {
addFilter(builder, registration.getFilter(), registration.getUrlPatterns());
}
}
private void addFilter(ConfigurableMockMvcBuilder<?> builder, Filter filter,
Collection<String> urls) {
private void addFilter(ConfigurableMockMvcBuilder<?> builder, Filter filter, Collection<String> urls) {
if (urls.isEmpty()) {
builder.addFilters(filter);
}
@@ -247,8 +243,7 @@ public class SpringBootMockMvcBuilderCustomizer implements MockMvcBuilderCustomi
DeferredLinesWriter(WebApplicationContext context, LinesWriter delegate) {
Assert.state(context instanceof ConfigurableApplicationContext,
"A ConfigurableApplicationContext is required for printOnlyOnFailure");
((ConfigurableApplicationContext) context).getBeanFactory()
.registerSingleton(BEAN_NAME, this);
((ConfigurableApplicationContext) context).getBeanFactory().registerSingleton(BEAN_NAME, this);
this.delegate = delegate;
}
@@ -277,8 +272,7 @@ public class SpringBootMockMvcBuilderCustomizer implements MockMvcBuilderCustomi
*/
private static class LoggingLinesWriter implements LinesWriter {
private static final Log logger = LogFactory
.getLog("org.springframework.test.web.servlet.result");
private static final Log logger = LogFactory.getLog("org.springframework.test.web.servlet.result");
@Override
public void write(List<String> lines) {

View File

@@ -44,8 +44,7 @@ class WebDriverContextCustomizerFactory implements ContextCustomizerFactory {
private static class Customizer implements ContextCustomizer {
@Override
public void customizeContext(ConfigurableApplicationContext context,
MergedContextConfiguration mergedConfig) {
public void customizeContext(ConfigurableApplicationContext context, MergedContextConfiguration mergedConfig) {
WebDriverScope.registerWith(context);
}

View File

@@ -119,13 +119,11 @@ class WebDriverScope implements Scope {
context.addBeanFactoryPostProcessor(new BeanFactoryPostProcessor() {
@Override
public void postProcessBeanFactory(
ConfigurableListableBeanFactory beanFactory) throws BeansException {
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
for (String beanClass : BEAN_CLASSES) {
for (String beanName : beanFactory.getBeanNamesForType(
ClassUtils.resolveClassName(beanClass, null))) {
BeanDefinition definition = beanFactory
.getBeanDefinition(beanName);
for (String beanName : beanFactory
.getBeanNamesForType(ClassUtils.resolveClassName(beanClass, null))) {
BeanDefinition definition = beanFactory.getBeanDefinition(beanName);
if (!StringUtils.hasLength(definition.getScope())) {
definition.setScope(NAME);
}
@@ -143,8 +141,7 @@ class WebDriverScope implements Scope {
*/
public static WebDriverScope getFrom(ApplicationContext context) {
if (context instanceof ConfigurableApplicationContext) {
Scope scope = ((ConfigurableApplicationContext) context).getBeanFactory()
.getRegisteredScope(NAME);
Scope scope = ((ConfigurableApplicationContext) context).getBeanFactory().getRegisteredScope(NAME);
return (scope instanceof WebDriverScope) ? (WebDriverScope) scope : null;
}
return null;

View File

@@ -32,11 +32,9 @@ class WebDriverTestExecutionListener extends AbstractTestExecutionListener {
@Override
public void afterTestMethod(TestContext testContext) throws Exception {
WebDriverScope scope = WebDriverScope
.getFrom(testContext.getApplicationContext());
WebDriverScope scope = WebDriverScope.getFrom(testContext.getApplicationContext());
if (scope != null && scope.reset()) {
testContext.setAttribute(
DependencyInjectionTestExecutionListener.REINJECT_DEPENDENCIES_ATTRIBUTE,
testContext.setAttribute(DependencyInjectionTestExecutionListener.REINJECT_DEPENDENCIES_ATTRIBUTE,
Boolean.TRUE);
}
}

View File

@@ -29,10 +29,8 @@ import org.springframework.test.context.web.WebMergedContextConfiguration;
class WebMvcTestContextBootstrapper extends SpringBootTestContextBootstrapper {
@Override
protected MergedContextConfiguration processMergedContextConfiguration(
MergedContextConfiguration mergedConfig) {
return new WebMergedContextConfiguration(
super.processMergedContextConfiguration(mergedConfig), "");
protected MergedContextConfiguration processMergedContextConfiguration(MergedContextConfiguration mergedConfig) {
return new WebMergedContextConfiguration(super.processMergedContextConfiguration(mergedConfig), "");
}
}

View File

@@ -70,8 +70,7 @@ class WebMvcTypeExcludeFilter extends AnnotationCustomizableTypeExcludeFilter {
private final WebMvcTest annotation;
WebMvcTypeExcludeFilter(Class<?> testClass) {
this.annotation = AnnotatedElementUtils.getMergedAnnotation(testClass,
WebMvcTest.class);
this.annotation = AnnotatedElementUtils.getMergedAnnotation(testClass, WebMvcTest.class);
}
@Override

View File

@@ -28,8 +28,7 @@ import org.springframework.context.ApplicationContext;
*
* @author Andy Wilkinson
*/
public final class AutoConfigurationImportedCondition
extends Condition<ApplicationContext> {
public final class AutoConfigurationImportedCondition extends Condition<ApplicationContext> {
private final Class<?> autoConfigurationClass;
@@ -41,10 +40,8 @@ public final class AutoConfigurationImportedCondition
@Override
public boolean matches(ApplicationContext context) {
ConditionEvaluationReport report = ConditionEvaluationReport
.get((ConfigurableListableBeanFactory) context
.getAutowireCapableBeanFactory());
return report.getConditionAndOutcomesBySource().keySet()
.contains(this.autoConfigurationClass.getName());
.get((ConfigurableListableBeanFactory) context.getAutowireCapableBeanFactory());
return report.getConditionAndOutcomesBySource().keySet().contains(this.autoConfigurationClass.getName());
}
/**
@@ -53,8 +50,7 @@ public final class AutoConfigurationImportedCondition
* @param autoConfigurationClass the auto-configuration class
* @return the condition
*/
public static AutoConfigurationImportedCondition importedAutoConfiguration(
Class<?> autoConfigurationClass) {
public static AutoConfigurationImportedCondition importedAutoConfiguration(Class<?> autoConfigurationClass) {
return new AutoConfigurationImportedCondition(autoConfigurationClass);
}

View File

@@ -32,35 +32,27 @@ public class OverrideAutoConfigurationContextCustomizerFactoryTests {
private OverrideAutoConfigurationContextCustomizerFactory factory = new OverrideAutoConfigurationContextCustomizerFactory();
@Test
public void getContextCustomizerWhenHasNoAnnotationShouldReturnNull()
throws Exception {
ContextCustomizer customizer = this.factory
.createContextCustomizer(NoAnnotation.class, null);
public void getContextCustomizerWhenHasNoAnnotationShouldReturnNull() throws Exception {
ContextCustomizer customizer = this.factory.createContextCustomizer(NoAnnotation.class, null);
assertThat(customizer).isNull();
}
@Test
public void getContextCustomizerWhenHasAnnotationEnabledTrueShouldReturnNull()
throws Exception {
ContextCustomizer customizer = this.factory
.createContextCustomizer(WithAnnotationEnabledTrue.class, null);
public void getContextCustomizerWhenHasAnnotationEnabledTrueShouldReturnNull() throws Exception {
ContextCustomizer customizer = this.factory.createContextCustomizer(WithAnnotationEnabledTrue.class, null);
assertThat(customizer).isNull();
}
@Test
public void getContextCustomizerWhenHasAnnotationEnabledFalseShouldReturnCustomizer()
throws Exception {
ContextCustomizer customizer = this.factory
.createContextCustomizer(WithAnnotationEnabledFalse.class, null);
public void getContextCustomizerWhenHasAnnotationEnabledFalseShouldReturnCustomizer() throws Exception {
ContextCustomizer customizer = this.factory.createContextCustomizer(WithAnnotationEnabledFalse.class, null);
assertThat(customizer).isNotNull();
}
@Test
public void hashCodeAndEquals() throws Exception {
ContextCustomizer customizer1 = this.factory
.createContextCustomizer(WithAnnotationEnabledFalse.class, null);
ContextCustomizer customizer2 = this.factory
.createContextCustomizer(WithSameAnnotation.class, null);
ContextCustomizer customizer1 = this.factory.createContextCustomizer(WithAnnotationEnabledFalse.class, null);
ContextCustomizer customizer2 = this.factory.createContextCustomizer(WithSameAnnotation.class, null);
assertThat(customizer1.hashCode()).isEqualTo(customizer2.hashCode());
assertThat(customizer1).isEqualTo(customizer1).isEqualTo(customizer2);
}

View File

@@ -48,8 +48,7 @@ public class OverrideAutoConfigurationEnabledTrueIntegrationTests {
public void autoConfiguredContext() throws Exception {
ApplicationContext context = this.context;
assertThat(context.getBean(ExampleSpringBootApplication.class)).isNotNull();
assertThat(context.getBean(ConfigurationPropertiesBindingPostProcessor.class))
.isNotNull();
assertThat(context.getBean(ConfigurationPropertiesBindingPostProcessor.class)).isNotNull();
}
}

View File

@@ -52,11 +52,9 @@ public class SpringBootDependencyInjectionTestExecutionListenerTests {
private SpringBootDependencyInjectionTestExecutionListener reportListener = new SpringBootDependencyInjectionTestExecutionListener();
@Test
public void orderShouldBeSameAsDependencyInjectionTestExecutionListener()
throws Exception {
public void orderShouldBeSameAsDependencyInjectionTestExecutionListener() throws Exception {
Ordered injectionListener = new DependencyInjectionTestExecutionListener();
assertThat(this.reportListener.getOrder())
.isEqualTo(injectionListener.getOrder());
assertThat(this.reportListener.getOrder()).isEqualTo(injectionListener.getOrder());
}
@Test

View File

@@ -48,8 +48,7 @@ public class ImportsContextCustomizerFactoryWithAutoConfigurationTests {
static ApplicationContext contextFromTest;
@Test
public void testClassesThatHaveSameAnnotationsShareAContext()
throws InitializationError {
public void testClassesThatHaveSameAnnotationsShareAContext() throws InitializationError {
RunNotifier notifier = new RunNotifier();
new SpringJUnit4ClassRunner(DataJpaTest1.class).run(notifier);
ApplicationContext test1Context = contextFromTest;
@@ -59,8 +58,7 @@ public class ImportsContextCustomizerFactoryWithAutoConfigurationTests {
}
@Test
public void testClassesThatOnlyHaveDifferingUnrelatedAnnotationsShareAContext()
throws InitializationError {
public void testClassesThatOnlyHaveDifferingUnrelatedAnnotationsShareAContext() throws InitializationError {
RunNotifier notifier = new RunNotifier();
new SpringJUnit4ClassRunner(DataJpaTest1.class).run(notifier);
ApplicationContext test1Context = contextFromTest;

View File

@@ -83,11 +83,9 @@ public class FilterAnnotationsTests {
return new FilterAnnotations(getClass().getClassLoader(), filters.value());
}
private boolean match(FilterAnnotations filterAnnotations, Class<?> type)
throws IOException {
private boolean match(FilterAnnotations filterAnnotations, Class<?> type) throws IOException {
MetadataReaderFactory metadataReaderFactory = new SimpleMetadataReaderFactory();
MetadataReader metadataReader = metadataReaderFactory
.getMetadataReader(type.getName());
MetadataReader metadataReader = metadataReaderFactory.getMetadataReader(type.getName());
return filterAnnotations.anyMatches(metadataReader, metadataReaderFactory);
}
@@ -96,8 +94,7 @@ public class FilterAnnotationsTests {
}
@Filters(@Filter(type = FilterType.ASSIGNABLE_TYPE,
classes = ExampleWithoutAnnotation.class))
@Filters(@Filter(type = FilterType.ASSIGNABLE_TYPE, classes = ExampleWithoutAnnotation.class))
static class FilterByType {
}
@@ -107,8 +104,7 @@ public class FilterAnnotationsTests {
}
@Filters(@Filter(type = FilterType.ASPECTJ,
pattern = "(*..*ExampleWithoutAnnotation)"))
@Filters(@Filter(type = FilterType.ASPECTJ, pattern = "(*..*ExampleWithoutAnnotation)"))
static class FilterByAspectJ {
}
@@ -130,10 +126,9 @@ public class FilterAnnotationsTests {
static class ExampleCustomFilter implements TypeFilter {
@Override
public boolean match(MetadataReader metadataReader,
MetadataReaderFactory metadataReaderFactory) throws IOException {
return metadataReader.getClassMetadata().getClassName()
.equals(ExampleWithoutAnnotation.class.getName());
public boolean match(MetadataReader metadataReader, MetadataReaderFactory metadataReaderFactory)
throws IOException {
return metadataReader.getClassMetadata().getClassName().equals(ExampleWithoutAnnotation.class.getName());
}
}

View File

@@ -41,56 +41,43 @@ public class TypeExcludeFiltersContextCustomizerFactoryTests {
private TypeExcludeFiltersContextCustomizerFactory factory = new TypeExcludeFiltersContextCustomizerFactory();
private MergedContextConfiguration mergedContextConfiguration = mock(
MergedContextConfiguration.class);
private MergedContextConfiguration mergedContextConfiguration = mock(MergedContextConfiguration.class);
private ConfigurableApplicationContext context = new AnnotationConfigApplicationContext();
@Test
public void getContextCustomizerWhenHasNoAnnotationShouldReturnNull()
throws Exception {
ContextCustomizer customizer = this.factory
.createContextCustomizer(NoAnnotation.class, null);
public void getContextCustomizerWhenHasNoAnnotationShouldReturnNull() throws Exception {
ContextCustomizer customizer = this.factory.createContextCustomizer(NoAnnotation.class, null);
assertThat(customizer).isNull();
}
@Test
public void getContextCustomizerWhenHasAnnotationShouldReturnCustomizer()
throws Exception {
ContextCustomizer customizer = this.factory
.createContextCustomizer(WithExcludeFilters.class, null);
public void getContextCustomizerWhenHasAnnotationShouldReturnCustomizer() throws Exception {
ContextCustomizer customizer = this.factory.createContextCustomizer(WithExcludeFilters.class, null);
assertThat(customizer).isNotNull();
}
@Test
public void hashCodeAndEquals() throws Exception {
ContextCustomizer customizer1 = this.factory
.createContextCustomizer(WithExcludeFilters.class, null);
ContextCustomizer customizer2 = this.factory
.createContextCustomizer(WithSameExcludeFilters.class, null);
ContextCustomizer customizer3 = this.factory
.createContextCustomizer(WithDifferentExcludeFilters.class, null);
ContextCustomizer customizer1 = this.factory.createContextCustomizer(WithExcludeFilters.class, null);
ContextCustomizer customizer2 = this.factory.createContextCustomizer(WithSameExcludeFilters.class, null);
ContextCustomizer customizer3 = this.factory.createContextCustomizer(WithDifferentExcludeFilters.class, null);
assertThat(customizer1.hashCode()).isEqualTo(customizer2.hashCode());
assertThat(customizer1).isEqualTo(customizer1).isEqualTo(customizer2)
.isNotEqualTo(customizer3);
assertThat(customizer1).isEqualTo(customizer1).isEqualTo(customizer2).isNotEqualTo(customizer3);
}
@Test
public void getContextCustomizerShouldAddExcludeFilters() throws Exception {
ContextCustomizer customizer = this.factory
.createContextCustomizer(WithExcludeFilters.class, null);
ContextCustomizer customizer = this.factory.createContextCustomizer(WithExcludeFilters.class, null);
customizer.customizeContext(this.context, this.mergedContextConfiguration);
this.context.refresh();
TypeExcludeFilter filter = this.context.getBean(TypeExcludeFilter.class);
MetadataReaderFactory metadataReaderFactory = new SimpleMetadataReaderFactory();
MetadataReader metadataReader = metadataReaderFactory
.getMetadataReader(NoAnnotation.class.getName());
MetadataReader metadataReader = metadataReaderFactory.getMetadataReader(NoAnnotation.class.getName());
assertThat(filter.match(metadataReader, metadataReaderFactory)).isFalse();
metadataReader = metadataReaderFactory
.getMetadataReader(SimpleExclude.class.getName());
metadataReader = metadataReaderFactory.getMetadataReader(SimpleExclude.class.getName());
assertThat(filter.match(metadataReader, metadataReaderFactory)).isTrue();
metadataReader = metadataReaderFactory
.getMetadataReader(TestClassAwareExclude.class.getName());
metadataReader = metadataReaderFactory.getMetadataReader(TestClassAwareExclude.class.getName());
assertThat(filter.match(metadataReader, metadataReaderFactory)).isTrue();
}
@@ -116,10 +103,9 @@ public class TypeExcludeFiltersContextCustomizerFactoryTests {
static class SimpleExclude extends TypeExcludeFilter {
@Override
public boolean match(MetadataReader metadataReader,
MetadataReaderFactory metadataReaderFactory) throws IOException {
return metadataReader.getClassMetadata().getClassName()
.equals(getClass().getName());
public boolean match(MetadataReader metadataReader, MetadataReaderFactory metadataReaderFactory)
throws IOException {
return metadataReader.getClassMetadata().getClassName().equals(getClass().getName());
}
@Override

View File

@@ -49,8 +49,7 @@ public class AutoConfigureTestDatabaseWithMultipleDatasourcesIntegrationTests {
@Test
public void replacesDefinedDataSourceWithExplicit() throws Exception {
// Look that the datasource is replaced with an H2 DB.
String product = this.dataSource.getConnection().getMetaData()
.getDatabaseProductName();
String product = this.dataSource.getConnection().getMetaData().getDatabaseProductName();
assertThat(product).startsWith("H2");
}
@@ -61,15 +60,15 @@ public class AutoConfigureTestDatabaseWithMultipleDatasourcesIntegrationTests {
@Bean
@Primary
public DataSource dataSource() {
EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder()
.generateUniqueName(true).setType(EmbeddedDatabaseType.HSQL);
EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder().generateUniqueName(true)
.setType(EmbeddedDatabaseType.HSQL);
return builder.build();
}
@Bean
public DataSource secondaryDataSource() {
EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder()
.generateUniqueName(true).setType(EmbeddedDatabaseType.HSQL);
EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder().generateUniqueName(true)
.setType(EmbeddedDatabaseType.HSQL);
return builder.build();
}

View File

@@ -33,8 +33,8 @@ public class ExampleJdbcApplication {
@Bean
public DataSource dataSource() {
EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder()
.generateUniqueName(true).setType(EmbeddedDatabaseType.HSQL);
EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder().generateUniqueName(true)
.setType(EmbeddedDatabaseType.HSQL);
return builder.build();
}

View File

@@ -44,13 +44,11 @@ public class ExampleRepository {
@Transactional
public void save(ExampleEntity entity) {
this.jdbcTemplate.update("insert into example (id, name) values (?, ?)",
entity.getId(), entity.getName());
this.jdbcTemplate.update("insert into example (id, name) values (?, ?)", entity.getId(), entity.getName());
}
public ExampleEntity findById(int id) {
return this.jdbcTemplate.queryForObject(
"select id, name from example where id =?", new Object[] { id },
return this.jdbcTemplate.queryForObject("select id, name from example where id =?", new Object[] { id },
ROW_MAPPER);
}

View File

@@ -73,8 +73,7 @@ public class JdbcTestIntegrationTests {
@Test
public void replacesDefinedDataSourceWithEmbeddedDefault() throws Exception {
String product = this.dataSource.getConnection().getMetaData()
.getDatabaseProductName();
String product = this.dataSource.getConnection().getMetaData().getDatabaseProductName();
assertThat(product).isEqualTo("H2");
}
@@ -86,14 +85,12 @@ public class JdbcTestIntegrationTests {
@Test
public void flywayAutoConfigurationWasImported() {
assertThat(this.applicationContext)
.has(importedAutoConfiguration(FlywayAutoConfiguration.class));
assertThat(this.applicationContext).has(importedAutoConfiguration(FlywayAutoConfiguration.class));
}
@Test
public void liquibaseAutoConfigurationWasImported() {
assertThat(this.applicationContext)
.has(importedAutoConfiguration(LiquibaseAutoConfiguration.class));
assertThat(this.applicationContext).has(importedAutoConfiguration(LiquibaseAutoConfiguration.class));
}
}

View File

@@ -46,8 +46,7 @@ public class JdbcTestWithAutoConfigureTestDatabaseReplaceAutoConfiguredIntegrati
@Test
public void replacesAutoConfiguredDataSource() throws Exception {
String product = this.dataSource.getConnection().getMetaData()
.getDatabaseProductName();
String product = this.dataSource.getConnection().getMetaData().getDatabaseProductName();
assertThat(product).startsWith("HSQL");
}

View File

@@ -42,8 +42,7 @@ public class JdbcTestWithAutoConfigureTestDatabaseReplaceAutoConfiguredWithoutOv
@Test
public void usesDefaultEmbeddedDatabase() throws Exception {
String product = this.dataSource.getConnection().getMetaData()
.getDatabaseProductName();
String product = this.dataSource.getConnection().getMetaData().getDatabaseProductName();
// @AutoConfigureTestDatabase would use H2 but HSQL is manually defined
assertThat(product).startsWith("HSQL");
}

View File

@@ -49,8 +49,7 @@ public class JdbcTestWithAutoConfigureTestDatabaseReplaceExplicitIntegrationTest
@Test
public void replacesDefinedDataSourceWithExplicit() throws Exception {
// H2 is explicitly defined but HSQL is the override.
String product = this.dataSource.getConnection().getMetaData()
.getDatabaseProductName();
String product = this.dataSource.getConnection().getMetaData().getDatabaseProductName();
assertThat(product).startsWith("HSQL");
}
@@ -60,8 +59,8 @@ public class JdbcTestWithAutoConfigureTestDatabaseReplaceExplicitIntegrationTest
@Bean
public DataSource dataSource() {
EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder()
.generateUniqueName(true).setType(EmbeddedDatabaseType.H2);
EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder().generateUniqueName(true)
.setType(EmbeddedDatabaseType.H2);
return builder.build();
}

View File

@@ -43,8 +43,7 @@ public class JdbcTestWithAutoConfigureTestDatabaseReplaceNoneIntegrationTests {
@Test
public void usesDefaultEmbeddedDatabase() throws Exception {
// HSQL is explicitly defined and should not be replaced
String product = this.dataSource.getConnection().getMetaData()
.getDatabaseProductName();
String product = this.dataSource.getConnection().getMetaData().getDatabaseProductName();
assertThat(product).startsWith("HSQL");
}

View File

@@ -51,8 +51,7 @@ public class JdbcTestWithAutoConfigureTestDatabaseReplacePropertyAnyIntegrationT
@Test
public void replacesDefinedDataSourceWithExplicit() throws Exception {
// H2 is explicitly defined but HSQL is the override.
String product = this.dataSource.getConnection().getMetaData()
.getDatabaseProductName();
String product = this.dataSource.getConnection().getMetaData().getDatabaseProductName();
assertThat(product).startsWith("HSQL");
}
@@ -62,8 +61,8 @@ public class JdbcTestWithAutoConfigureTestDatabaseReplacePropertyAnyIntegrationT
@Bean
public DataSource dataSource() {
EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder()
.generateUniqueName(true).setType(EmbeddedDatabaseType.H2);
EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder().generateUniqueName(true)
.setType(EmbeddedDatabaseType.H2);
return builder.build();
}

View File

@@ -47,8 +47,7 @@ public class JdbcTestWithAutoConfigureTestDatabaseReplacePropertyAutoConfiguredI
@Test
public void replacesAutoConfiguredDataSource() throws Exception {
String product = this.dataSource.getConnection().getMetaData()
.getDatabaseProductName();
String product = this.dataSource.getConnection().getMetaData().getDatabaseProductName();
assertThat(product).startsWith("HSQL");
}

View File

@@ -44,8 +44,7 @@ public class JdbcTestWithAutoConfigureTestDatabaseReplacePropertyNoneIntegration
@Test
public void usesDefaultEmbeddedDatabase() throws Exception {
// HSQL is explicitly defined and should not be replaced
String product = this.dataSource.getConnection().getMetaData()
.getDatabaseProductName();
String product = this.dataSource.getConnection().getMetaData().getDatabaseProductName();
assertThat(product).startsWith("HSQL");
}

View File

@@ -60,8 +60,7 @@ public class TestDatabaseAutoConfigurationTests {
DataSource datasource = this.context.getBean(DataSource.class);
JdbcTemplate jdbcTemplate = new JdbcTemplate(datasource);
jdbcTemplate.execute("create table example (id int, name varchar);");
ConfigurableApplicationContext anotherContext = doLoad(
ExistingDataSourceConfiguration.class);
ConfigurableApplicationContext anotherContext = doLoad(ExistingDataSourceConfiguration.class);
try {
DataSource anotherDatasource = anotherContext.getBean(DataSource.class);
JdbcTemplate anotherJdbcTemplate = new JdbcTemplate(anotherDatasource);
@@ -76,8 +75,7 @@ public class TestDatabaseAutoConfigurationTests {
this.context = doLoad(config, environment);
}
private ConfigurableApplicationContext doLoad(Class<?> config,
String... environment) {
private ConfigurableApplicationContext doLoad(Class<?> config, String... environment) {
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
if (config != null) {
ctx.register(config);
@@ -93,8 +91,8 @@ public class TestDatabaseAutoConfigurationTests {
@Bean
public DataSource dataSource() {
EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder()
.generateUniqueName(true).setType(EmbeddedDatabaseType.HSQL);
EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder().generateUniqueName(true)
.setType(EmbeddedDatabaseType.HSQL);
return builder.build();
}

View File

@@ -41,8 +41,8 @@ public class ExampleJsonComponent {
public static class Serializer extends JsonObjectSerializer<ExampleCustomObject> {
@Override
protected void serializeObject(ExampleCustomObject value, JsonGenerator jgen,
SerializerProvider provider) throws IOException {
protected void serializeObject(ExampleCustomObject value, JsonGenerator jgen, SerializerProvider provider)
throws IOException {
jgen.writeStringField("value", value.toString());
}
@@ -51,11 +51,9 @@ public class ExampleJsonComponent {
public static class Deserializer extends JsonObjectDeserializer<ExampleCustomObject> {
@Override
protected ExampleCustomObject deserializeObject(JsonParser jsonParser,
DeserializationContext context, ObjectCodec codec, JsonNode tree)
throws IOException {
return new ExampleCustomObject(
nullSafeValue(tree.get("value"), String.class));
protected ExampleCustomObject deserializeObject(JsonParser jsonParser, DeserializationContext context,
ObjectCodec codec, JsonNode tree) throws IOException {
return new ExampleCustomObject(nullSafeValue(tree.get("value"), String.class));
}
}

View File

@@ -54,8 +54,7 @@ public class ExampleJsonObjectWithView {
return false;
}
ExampleJsonObjectWithView other = (ExampleJsonObjectWithView) obj;
return ObjectUtils.nullSafeEquals(this.value, other.value)
&& ObjectUtils.nullSafeEquals(this.id, other.id);
return ObjectUtils.nullSafeEquals(this.value, other.value) && ObjectUtils.nullSafeEquals(this.id, other.id);
}
@Override

View File

@@ -73,12 +73,10 @@ public class DataJpaTestIntegrationTests {
@Test
public void testEntityManagerPersistAndGetId() throws Exception {
Long id = this.entities.persistAndGetId(new ExampleEntity("spring", "123"),
Long.class);
Long id = this.entities.persistAndGetId(new ExampleEntity("spring", "123"), Long.class);
assertThat(id).isNotNull();
String reference = this.jdbcTemplate.queryForObject(
"SELECT REFERENCE FROM EXAMPLE_ENTITY WHERE ID = ?", new Object[] { id },
String.class);
String reference = this.jdbcTemplate.queryForObject("SELECT REFERENCE FROM EXAMPLE_ENTITY WHERE ID = ?",
new Object[] { id }, String.class);
assertThat(reference).isEqualTo("123");
}
@@ -93,8 +91,7 @@ public class DataJpaTestIntegrationTests {
@Test
public void replacesDefinedDataSourceWithEmbeddedDefault() throws Exception {
String product = this.dataSource.getConnection().getMetaData()
.getDatabaseProductName();
String product = this.dataSource.getConnection().getMetaData().getDatabaseProductName();
assertThat(product).isEqualTo("H2");
}
@@ -106,14 +103,12 @@ public class DataJpaTestIntegrationTests {
@Test
public void flywayAutoConfigurationWasImported() {
assertThat(this.applicationContext)
.has(importedAutoConfiguration(FlywayAutoConfiguration.class));
assertThat(this.applicationContext).has(importedAutoConfiguration(FlywayAutoConfiguration.class));
}
@Test
public void liquibaseAutoConfigurationWasImported() {
assertThat(this.applicationContext)
.has(importedAutoConfiguration(LiquibaseAutoConfiguration.class));
assertThat(this.applicationContext).has(importedAutoConfiguration(LiquibaseAutoConfiguration.class));
}
}

View File

@@ -37,8 +37,7 @@ import static org.assertj.core.api.Assertions.assertThat;
*/
@RunWith(SpringRunner.class)
@DataJpaTest
@AutoConfigureTestDatabase(replace = Replace.AUTO_CONFIGURED,
connection = EmbeddedDatabaseConnection.HSQL)
@AutoConfigureTestDatabase(replace = Replace.AUTO_CONFIGURED, connection = EmbeddedDatabaseConnection.HSQL)
@Deprecated
public class DataJpaTestWithAutoConfigureTestDatabaseReplaceAutoConfiguredIntegrationTests {
@@ -62,8 +61,7 @@ public class DataJpaTestWithAutoConfigureTestDatabaseReplaceAutoConfiguredIntegr
@Test
public void replacesAutoConfiguredDataSource() throws Exception {
String product = this.dataSource.getConnection().getMetaData()
.getDatabaseProductName();
String product = this.dataSource.getConnection().getMetaData().getDatabaseProductName();
assertThat(product).startsWith("HSQL");
}

View File

@@ -58,8 +58,7 @@ public class DataJpaTestWithAutoConfigureTestDatabaseReplaceAutoConfiguredWithou
@Test
public void usesDefaultEmbeddedDatabase() throws Exception {
String product = this.dataSource.getConnection().getMetaData()
.getDatabaseProductName();
String product = this.dataSource.getConnection().getMetaData().getDatabaseProductName();
// @AutoConfigureTestDatabase would use H2 but HSQL is manually defined
assertThat(product).startsWith("HSQL");
}

View File

@@ -64,8 +64,7 @@ public class DataJpaTestWithAutoConfigureTestDatabaseReplaceExplicitIntegrationT
@Test
public void replacesDefinedDataSourceWithExplicit() throws Exception {
// H2 is explicitly defined but HSQL is the override.
String product = this.dataSource.getConnection().getMetaData()
.getDatabaseProductName();
String product = this.dataSource.getConnection().getMetaData().getDatabaseProductName();
assertThat(product).startsWith("HSQL");
}
@@ -75,8 +74,8 @@ public class DataJpaTestWithAutoConfigureTestDatabaseReplaceExplicitIntegrationT
@Bean
public DataSource dataSource() {
EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder()
.generateUniqueName(true).setType(EmbeddedDatabaseType.H2);
EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder().generateUniqueName(true)
.setType(EmbeddedDatabaseType.H2);
return builder.build();
}

View File

@@ -59,8 +59,7 @@ public class DataJpaTestWithAutoConfigureTestDatabaseReplaceNoneIntegrationTests
@Test
public void usesDefaultEmbeddedDatabase() throws Exception {
// HSQL is explicitly defined and should not be replaced
String product = this.dataSource.getConnection().getMetaData()
.getDatabaseProductName();
String product = this.dataSource.getConnection().getMetaData().getDatabaseProductName();
assertThat(product).startsWith("HSQL");
}

View File

@@ -33,8 +33,8 @@ public class ExampleDataJpaApplication {
@Bean
public DataSource dataSource() {
EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder()
.generateUniqueName(true).setType(EmbeddedDatabaseType.HSQL);
EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder().generateUniqueName(true)
.setType(EmbeddedDatabaseType.HSQL);
return builder.build();
}

View File

@@ -61,13 +61,10 @@ public class TestDatabaseAutoConfigurationNoEmbeddedTests {
}
catch (BeanCreationException ex) {
String message = ex.getMessage();
assertThat(message).contains(
"Failed to replace DataSource with an embedded database for tests.");
assertThat(message).contains(
"If you want an embedded database please put a supported one on the "
+ "classpath");
assertThat(message).contains(
"or tune the replace attribute of @AutoconfigureTestDatabase.");
assertThat(message).contains("Failed to replace DataSource with an embedded database for tests.");
assertThat(message)
.contains("If you want an embedded database please put a supported one on the " + "classpath");
assertThat(message).contains("or tune the replace attribute of @AutoconfigureTestDatabase.");
}
}
@@ -75,8 +72,7 @@ public class TestDatabaseAutoConfigurationNoEmbeddedTests {
public void applyNoReplace() {
load(ExistingDataSourceConfiguration.class, "spring.test.database.replace=NONE");
assertThat(this.context.getBeansOfType(DataSource.class)).hasSize(1);
assertThat(this.context.getBean(DataSource.class))
.isSameAs(this.context.getBean("myCustomDataSource"));
assertThat(this.context.getBean(DataSource.class)).isSameAs(this.context.getBean("myCustomDataSource"));
}
public void load(Class<?> config, String... environment) {

View File

@@ -59,8 +59,7 @@ public class TestEntityManagerTests {
public void setup() {
MockitoAnnotations.initMocks(this);
this.testEntityManager = new TestEntityManager(this.entityManagerFactory);
given(this.entityManagerFactory.getPersistenceUnitUtil())
.willReturn(this.persistenceUnitUtil);
given(this.entityManagerFactory.getPersistenceUnitUtil()).willReturn(this.persistenceUnitUtil);
}
@Test
@@ -191,8 +190,8 @@ public class TestEntityManagerTests {
public void getIdForTypeWhenTypeIsWrongShouldThrowException() throws Exception {
TestEntity entity = new TestEntity();
given(this.persistenceUnitUtil.getIdentifier(entity)).willReturn(123);
this.thrown.expectMessage("ID mismatch: Object of class [java.lang.Integer] "
+ "must be an instance of class java.lang.Long");
this.thrown.expectMessage(
"ID mismatch: Object of class [java.lang.Integer] " + "must be an instance of class java.lang.Long");
this.testEntityManager.getId(entity, Long.class);
}
@@ -207,8 +206,7 @@ public class TestEntityManagerTests {
@Test
public void getEntityManagerShouldGetEntityManager() throws Exception {
bindEntityManager();
assertThat(this.testEntityManager.getEntityManager())
.isEqualTo(this.entityManager);
assertThat(this.testEntityManager.getEntityManager()).isEqualTo(this.entityManager);
}
@Test

View File

@@ -47,61 +47,49 @@ public class AnnotationsPropertySourceTests {
@Test
public void propertiesWhenHasNoAnnotationShouldBeEmpty() throws Exception {
AnnotationsPropertySource source = new AnnotationsPropertySource(
NoAnnotation.class);
AnnotationsPropertySource source = new AnnotationsPropertySource(NoAnnotation.class);
assertThat(source.getPropertyNames()).isEmpty();
assertThat(source.getProperty("value")).isNull();
}
@Test
public void propertiesWhenHasTypeLevelAnnotationShouldUseAttributeName()
throws Exception {
public void propertiesWhenHasTypeLevelAnnotationShouldUseAttributeName() throws Exception {
AnnotationsPropertySource source = new AnnotationsPropertySource(TypeLevel.class);
assertThat(source.getPropertyNames()).containsExactly("value");
assertThat(source.getProperty("value")).isEqualTo("abc");
}
@Test
public void propertiesWhenHasTypeLevelWithPrefixShouldUsePrefixedName()
throws Exception {
AnnotationsPropertySource source = new AnnotationsPropertySource(
TypeLevelWithPrefix.class);
public void propertiesWhenHasTypeLevelWithPrefixShouldUsePrefixedName() throws Exception {
AnnotationsPropertySource source = new AnnotationsPropertySource(TypeLevelWithPrefix.class);
assertThat(source.getPropertyNames()).containsExactly("test.value");
assertThat(source.getProperty("test.value")).isEqualTo("abc");
}
@Test
public void propertiesWhenHasAttributeLevelWithPrefixShouldUsePrefixedName()
throws Exception {
AnnotationsPropertySource source = new AnnotationsPropertySource(
AttributeLevelWithPrefix.class);
public void propertiesWhenHasAttributeLevelWithPrefixShouldUsePrefixedName() throws Exception {
AnnotationsPropertySource source = new AnnotationsPropertySource(AttributeLevelWithPrefix.class);
assertThat(source.getPropertyNames()).containsExactly("test");
assertThat(source.getProperty("test")).isEqualTo("abc");
}
@Test
public void propertiesWhenHasTypeAndAttributeLevelWithPrefixShouldUsePrefixedName()
throws Exception {
AnnotationsPropertySource source = new AnnotationsPropertySource(
TypeAndAttributeLevelWithPrefix.class);
public void propertiesWhenHasTypeAndAttributeLevelWithPrefixShouldUsePrefixedName() throws Exception {
AnnotationsPropertySource source = new AnnotationsPropertySource(TypeAndAttributeLevelWithPrefix.class);
assertThat(source.getPropertyNames()).containsExactly("test.example");
assertThat(source.getProperty("test.example")).isEqualTo("abc");
}
@Test
public void propertiesWhenNotMappedAtTypeLevelShouldIgnoreAttributes()
throws Exception {
AnnotationsPropertySource source = new AnnotationsPropertySource(
NotMappedAtTypeLevel.class);
public void propertiesWhenNotMappedAtTypeLevelShouldIgnoreAttributes() throws Exception {
AnnotationsPropertySource source = new AnnotationsPropertySource(NotMappedAtTypeLevel.class);
assertThat(source.getPropertyNames()).containsExactly("value");
assertThat(source.getProperty("ignore")).isNull();
}
@Test
public void propertiesWhenNotMappedAtAttributeLevelShouldIgnoreAttributes()
throws Exception {
AnnotationsPropertySource source = new AnnotationsPropertySource(
NotMappedAtAttributeLevel.class);
public void propertiesWhenNotMappedAtAttributeLevelShouldIgnoreAttributes() throws Exception {
AnnotationsPropertySource source = new AnnotationsPropertySource(NotMappedAtAttributeLevel.class);
assertThat(source.getPropertyNames()).containsExactly("value");
assertThat(source.getProperty("ignore")).isNull();
}
@@ -109,10 +97,9 @@ public class AnnotationsPropertySourceTests {
@Test
public void propertiesWhenContainsArraysShouldExpandNames() throws Exception {
AnnotationsPropertySource source = new AnnotationsPropertySource(Arrays.class);
assertThat(source.getPropertyNames()).contains("strings[0]", "strings[1]",
"classes[0]", "classes[1]", "ints[0]", "ints[1]", "longs[0]", "longs[1]",
"floats[0]", "floats[1]", "doubles[0]", "doubles[1]", "booleans[0]",
"booleans[1]");
assertThat(source.getPropertyNames()).contains("strings[0]", "strings[1]", "classes[0]", "classes[1]",
"ints[0]", "ints[1]", "longs[0]", "longs[1]", "floats[0]", "floats[1]", "doubles[0]", "doubles[1]",
"booleans[0]", "booleans[1]");
assertThat(source.getProperty("strings[0]")).isEqualTo("a");
assertThat(source.getProperty("strings[1]")).isEqualTo("b");
assertThat(source.getProperty("classes[0]")).isEqualTo(Integer.class);
@@ -131,26 +118,21 @@ public class AnnotationsPropertySourceTests {
@Test
public void propertiesWhenHasCamelCaseShouldConvertToKebabCase() throws Exception {
AnnotationsPropertySource source = new AnnotationsPropertySource(
CamelCaseToKebabCase.class);
AnnotationsPropertySource source = new AnnotationsPropertySource(CamelCaseToKebabCase.class);
assertThat(source.getPropertyNames()).contains("camel-case-to-kebab-case");
}
@Test
public void propertiesFromMetaAnnotationsAreMapped() throws Exception {
AnnotationsPropertySource source = new AnnotationsPropertySource(
PropertiesFromSingleMetaAnnotation.class);
AnnotationsPropertySource source = new AnnotationsPropertySource(PropertiesFromSingleMetaAnnotation.class);
assertThat(source.getPropertyNames()).containsExactly("value");
assertThat(source.getProperty("value")).isEqualTo("foo");
}
@Test
public void propertiesFromMultipleMetaAnnotationsAreMappedUsingTheirOwnPropertyMapping()
throws Exception {
AnnotationsPropertySource source = new AnnotationsPropertySource(
PropertiesFromMultipleMetaAnnotations.class);
assertThat(source.getPropertyNames()).containsExactly("value", "test.value",
"test.example");
public void propertiesFromMultipleMetaAnnotationsAreMappedUsingTheirOwnPropertyMapping() throws Exception {
AnnotationsPropertySource source = new AnnotationsPropertySource(PropertiesFromMultipleMetaAnnotations.class);
assertThat(source.getPropertyNames()).containsExactly("value", "test.value", "test.example");
assertThat(source.getProperty("value")).isEqualTo("alpha");
assertThat(source.getProperty("test.value")).isEqualTo("bravo");
assertThat(source.getProperty("test.example")).isEqualTo("charlie");
@@ -158,8 +140,7 @@ public class AnnotationsPropertySourceTests {
@Test
public void propertyMappedAttributesCanBeAliased() {
AnnotationsPropertySource source = new AnnotationsPropertySource(
PropertyMappedAttributeWithAnAlias.class);
AnnotationsPropertySource source = new AnnotationsPropertySource(PropertyMappedAttributeWithAnAlias.class);
assertThat(source.getPropertyNames()).containsExactly("aliasing.value");
assertThat(source.getProperty("aliasing.value")).isEqualTo("baz");
}
@@ -171,8 +152,7 @@ public class AnnotationsPropertySourceTests {
@Test
public void typeLevelAnnotationOnSuperClass() {
AnnotationsPropertySource source = new AnnotationsPropertySource(
PropertyMappedAnnotationOnSuperClass.class);
AnnotationsPropertySource source = new AnnotationsPropertySource(PropertyMappedAnnotationOnSuperClass.class);
assertThat(source.getPropertyNames()).containsExactly("value");
assertThat(source.getProperty("value")).isEqualTo("abc");
}
@@ -187,15 +167,13 @@ public class AnnotationsPropertySourceTests {
@Test
public void enumValueMapped() throws Exception {
AnnotationsPropertySource source = new AnnotationsPropertySource(
EnumValueMapped.class);
AnnotationsPropertySource source = new AnnotationsPropertySource(EnumValueMapped.class);
assertThat(source.getProperty("testenum.value")).isEqualTo(EnumItem.TWO);
}
@Test
public void enumValueNotMapped() throws Exception {
AnnotationsPropertySource source = new AnnotationsPropertySource(
EnumValueNotMapped.class);
AnnotationsPropertySource source = new AnnotationsPropertySource(EnumValueNotMapped.class);
assertThat(source.containsProperty("testenum.value")).isFalse();
}
@@ -288,9 +266,8 @@ public class AnnotationsPropertySourceTests {
}
@ArraysAnnotation(strings = { "a", "b" }, classes = { Integer.class, Long.class },
ints = { 1, 2 }, longs = { 1, 2 }, floats = { 1.0f, 2.0f },
doubles = { 1.0, 2.0 }, booleans = { false, true })
@ArraysAnnotation(strings = { "a", "b" }, classes = { Integer.class, Long.class }, ints = { 1, 2 },
longs = { 1, 2 }, floats = { 1.0f, 2.0f }, doubles = { 1.0, 2.0 }, booleans = { false, true })
static class Arrays {
}
@@ -391,8 +368,7 @@ public class AnnotationsPropertySourceTests {
}
static class AliasedPropertyMappedAnnotationOnSuperClass
extends PropertyMappedAttributeWithAnAlias {
static class AliasedPropertyMappedAnnotationOnSuperClass extends PropertyMappedAttributeWithAnAlias {
}

View File

@@ -50,13 +50,10 @@ public class PropertyMappingContextCustomizerFactoryTests {
@Test
public void getContextCustomizerWhenHasNoMappingShouldNotAddPropertySource() {
ContextCustomizer customizer = this.factory
.createContextCustomizer(NoMapping.class, null);
ConfigurableApplicationContext context = mock(
ConfigurableApplicationContext.class);
ContextCustomizer customizer = this.factory.createContextCustomizer(NoMapping.class, null);
ConfigurableApplicationContext context = mock(ConfigurableApplicationContext.class);
ConfigurableEnvironment environment = mock(ConfigurableEnvironment.class);
ConfigurableListableBeanFactory beanFactory = mock(
ConfigurableListableBeanFactory.class);
ConfigurableListableBeanFactory beanFactory = mock(ConfigurableListableBeanFactory.class);
given(context.getEnvironment()).willReturn(environment);
given(context.getBeanFactory()).willReturn(beanFactory);
customizer.customizeContext(context, null);
@@ -65,35 +62,28 @@ public class PropertyMappingContextCustomizerFactoryTests {
@Test
public void getContextCustomizerWhenHasTypeMappingShouldReturnCustomizer() {
ContextCustomizer customizer = this.factory
.createContextCustomizer(TypeMapping.class, null);
ContextCustomizer customizer = this.factory.createContextCustomizer(TypeMapping.class, null);
assertThat(customizer).isNotNull();
}
@Test
public void getContextCustomizerWhenHasAttributeMappingShouldReturnCustomizer() {
ContextCustomizer customizer = this.factory
.createContextCustomizer(AttributeMapping.class, null);
ContextCustomizer customizer = this.factory.createContextCustomizer(AttributeMapping.class, null);
assertThat(customizer).isNotNull();
}
@Test
public void hashCodeAndEqualsShouldBeBasedOnPropertyValues() throws Exception {
ContextCustomizer customizer1 = this.factory
.createContextCustomizer(TypeMapping.class, null);
ContextCustomizer customizer2 = this.factory
.createContextCustomizer(AttributeMapping.class, null);
ContextCustomizer customizer3 = this.factory
.createContextCustomizer(OtherMapping.class, null);
ContextCustomizer customizer1 = this.factory.createContextCustomizer(TypeMapping.class, null);
ContextCustomizer customizer2 = this.factory.createContextCustomizer(AttributeMapping.class, null);
ContextCustomizer customizer3 = this.factory.createContextCustomizer(OtherMapping.class, null);
assertThat(customizer1.hashCode()).isEqualTo(customizer2.hashCode());
assertThat(customizer1).isEqualTo(customizer1).isEqualTo(customizer2)
.isNotEqualTo(customizer3);
assertThat(customizer1).isEqualTo(customizer1).isEqualTo(customizer2).isNotEqualTo(customizer3);
}
@Test
public void prepareContextShouldAddPropertySource() throws Exception {
ContextCustomizer customizer = this.factory
.createContextCustomizer(AttributeMapping.class, null);
ContextCustomizer customizer = this.factory.createContextCustomizer(AttributeMapping.class, null);
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
customizer.customizeContext(context, null);
assertThat(context.getEnvironment().getProperty("mapped")).isEqualTo("Mapped");
@@ -101,8 +91,7 @@ public class PropertyMappingContextCustomizerFactoryTests {
@Test
public void propertyMappingShouldNotBeUsedWithComponent() throws Exception {
ContextCustomizer customizer = this.factory
.createContextCustomizer(AttributeMapping.class, null);
ContextCustomizer customizer = this.factory.createContextCustomizer(AttributeMapping.class, null);
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
context.register(ConfigMapping.class);
customizer.customizeContext(context, null);

View File

@@ -63,13 +63,11 @@ public class RestDocsAutoConfigurationAdvancedConfigurationIntegrationTests {
@Test
public void snippetGeneration() throws Exception {
this.mvc.perform(get("/")).andDo(this.documentationHandler.document(links(
linkWithRel("self").description("Canonical location of this resource"))));
File defaultSnippetsDir = new File(
"target/generated-snippets/snippet-generation");
this.mvc.perform(get("/")).andDo(this.documentationHandler
.document(links(linkWithRel("self").description("Canonical location of this resource"))));
File defaultSnippetsDir = new File("target/generated-snippets/snippet-generation");
assertThat(defaultSnippetsDir).exists();
assertThat(new File(defaultSnippetsDir, "curl-request.md"))
.has(contentContaining("'http://localhost:8080/'"));
assertThat(new File(defaultSnippetsDir, "curl-request.md")).has(contentContaining("'http://localhost:8080/'"));
assertThat(new File(defaultSnippetsDir, "links.md")).isFile();
}
@@ -78,8 +76,7 @@ public class RestDocsAutoConfigurationAdvancedConfigurationIntegrationTests {
}
@TestConfiguration
public static class CustomizationConfiguration
implements RestDocsMockMvcConfigurationCustomizer {
public static class CustomizationConfiguration implements RestDocsMockMvcConfigurationCustomizer {
@Bean
public RestDocumentationResultHandler restDocumentation() {

View File

@@ -40,8 +40,8 @@ import static org.springframework.test.web.servlet.request.MockMvcRequestBuilder
*/
@RunWith(SpringRunner.class)
@WebMvcTest
@AutoConfigureRestDocs(outputDir = "target/generated-snippets", uriScheme = "https",
uriHost = "api.example.com", uriPort = 443)
@AutoConfigureRestDocs(outputDir = "target/generated-snippets", uriScheme = "https", uriHost = "api.example.com",
uriPort = 443)
public class RestDocsAutoConfigurationIntegrationTests {
@Before
@@ -59,8 +59,7 @@ public class RestDocsAutoConfigurationIntegrationTests {
assertThat(defaultSnippetsDir).exists();
assertThat(new File(defaultSnippetsDir, "curl-request.adoc"))
.has(contentContaining("'https://api.example.com/'"));
assertThat(new File(defaultSnippetsDir, "http-request.adoc"))
.has(contentContaining("api.example.com"));
assertThat(new File(defaultSnippetsDir, "http-request.adoc")).has(contentContaining("api.example.com"));
assertThat(new File(defaultSnippetsDir, "http-response.adoc")).isFile();
}

View File

@@ -58,10 +58,8 @@ public class MockMvcSecurityAutoConfigurationIntegrationTests {
@Test
public void okResponseWithBasicAuthCredentialsForKnownUser() throws Exception {
this.mockMvc
.perform(get("/").header(HttpHeaders.AUTHORIZATION,
"Basic " + Base64Utils.encodeToString("user:secret".getBytes())))
.andExpect(status().isOk());
this.mockMvc.perform(get("/").header(HttpHeaders.AUTHORIZATION,
"Basic " + Base64Utils.encodeToString("user:secret".getBytes()))).andExpect(status().isOk());
}
}

View File

@@ -52,10 +52,8 @@ public class AutoConfigureWebClientWithRestTemplateIntegrationTests {
@Test
public void restTemplateTest() throws Exception {
this.server.expect(requestTo("/test"))
.andRespond(withSuccess("hello", MediaType.TEXT_HTML));
ResponseEntity<String> entity = this.restTemplate.getForEntity("/test",
String.class);
this.server.expect(requestTo("/test")).andRespond(withSuccess("hello", MediaType.TEXT_HTML));
ResponseEntity<String> entity = this.restTemplate.getForEntity("/test", String.class);
assertThat(entity.getBody()).isEqualTo("hello");
}

View File

@@ -46,15 +46,13 @@ public class RestClientRestIntegrationTests {
@Test
public void mockServerCall1() throws Exception {
this.server.expect(requestTo("/test"))
.andRespond(withSuccess("1", MediaType.TEXT_HTML));
this.server.expect(requestTo("/test")).andRespond(withSuccess("1", MediaType.TEXT_HTML));
assertThat(this.client.test()).isEqualTo("1");
}
@Test
public void mockServerCall2() throws Exception {
this.server.expect(requestTo("/test"))
.andRespond(withSuccess("2", MediaType.TEXT_HTML));
this.server.expect(requestTo("/test")).andRespond(withSuccess("2", MediaType.TEXT_HTML));
assertThat(this.client.test()).isEqualTo("2");
}

View File

@@ -57,8 +57,7 @@ public class RestClientTestNoComponentIntegrationTests {
@Test
public void manuallyCreateBean() throws Exception {
ExampleRestClient client = new ExampleRestClient(this.restTemplateBuilder);
this.server.expect(requestTo("/test"))
.andRespond(withSuccess("hello", MediaType.TEXT_HTML));
this.server.expect(requestTo("/test")).andRespond(withSuccess("hello", MediaType.TEXT_HTML));
assertThat(client.test()).isEqualTo("hello");
}

View File

@@ -59,22 +59,19 @@ public class RestClientTestTwoComponentsIntegrationTests {
public void serverShouldNotWork() throws Exception {
this.thrown.expect(IllegalStateException.class);
this.thrown.expectMessage("Unable to use auto-configured");
this.server.expect(requestTo("/test"))
.andRespond(withSuccess("hello", MediaType.TEXT_HTML));
this.server.expect(requestTo("/test")).andRespond(withSuccess("hello", MediaType.TEXT_HTML));
}
@Test
public void client1RestCallViaCustomizer() throws Exception {
this.customizer.getServer(this.client1.getRestTemplate())
.expect(requestTo("/test"))
this.customizer.getServer(this.client1.getRestTemplate()).expect(requestTo("/test"))
.andRespond(withSuccess("hello", MediaType.TEXT_HTML));
assertThat(this.client1.test()).isEqualTo("hello");
}
@Test
public void client2RestCallViaCustomizer() throws Exception {
this.customizer.getServer(this.client2.getRestTemplate())
.expect(requestTo("/test"))
this.customizer.getServer(this.client2.getRestTemplate()).expect(requestTo("/test"))
.andRespond(withSuccess("there", MediaType.TEXT_HTML));
assertThat(this.client2.test()).isEqualTo("there");
}

View File

@@ -45,8 +45,7 @@ public class RestClientTestWithComponentIntegrationTests {
@Test
public void mockServerCall() throws Exception {
this.server.expect(requestTo("/test"))
.andRespond(withSuccess("hello", MediaType.TEXT_HTML));
this.server.expect(requestTo("/test")).andRespond(withSuccess("hello", MediaType.TEXT_HTML));
assertThat(this.client.test()).isEqualTo("hello");
}

View File

@@ -38,10 +38,9 @@ public class RestClientTestWithoutJacksonIntegrationTests {
@Test
public void restClientTestCanBeUsedWhenJacksonIsNotOnTheClassPath() {
assertThat(ClassUtils.isPresent("com.fasterxml.jackson.databind.Module",
getClass().getClassLoader())).isFalse();
Result result = JUnitCore
.runClasses(RestClientTestWithComponentIntegrationTests.class);
assertThat(ClassUtils.isPresent("com.fasterxml.jackson.databind.Module", getClass().getClassLoader()))
.isFalse();
Result result = JUnitCore.runClasses(RestClientTestWithComponentIntegrationTests.class);
assertThat(result.getFailureCount()).isEqualTo(0);
assertThat(result.getRunCount()).isGreaterThan(0);
}

View File

@@ -39,10 +39,8 @@ public class ExampleControllerAdvice {
@ExceptionHandler(NoHandlerFoundException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
public ResponseEntity<String> noHandlerFoundHandler(
NoHandlerFoundException exception) {
return ResponseEntity.badRequest()
.body("Invalid request: " + exception.getRequestURL());
public ResponseEntity<String> noHandlerFoundHandler(NoHandlerFoundException exception) {
return ResponseEntity.badRequest().body("Invalid request: " + exception.getRequestURL());
}
}

View File

@@ -41,8 +41,8 @@ public class ExampleFilter implements Filter {
}
@Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
chain.doFilter(request, response);
((HttpServletResponse) response).addHeader("x-test", "abc");
}

View File

@@ -36,8 +36,7 @@ import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter
public class ExampleWebMvcConfigurer extends WebMvcConfigurerAdapter {
@Override
public void addArgumentResolvers(
List<HandlerMethodArgumentResolver> argumentResolvers) {
public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) {
argumentResolvers.add(new HandlerMethodArgumentResolver() {
@Override
@@ -46,9 +45,8 @@ public class ExampleWebMvcConfigurer extends WebMvcConfigurerAdapter {
}
@Override
public Object resolveArgument(MethodParameter parameter,
ModelAndViewContainer mavContainer, NativeWebRequest webRequest,
WebDataBinderFactory binderFactory) throws Exception {
public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer,
NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
return new ExampleArgument("hello");
}

View File

@@ -60,21 +60,18 @@ public class MockMvcSpringBootTestIntegrationTests {
@Test
public void shouldFindController1() throws Exception {
this.mvc.perform(get("/one")).andExpect(content().string("one"))
.andExpect(status().isOk());
this.mvc.perform(get("/one")).andExpect(content().string("one")).andExpect(status().isOk());
assertThat(this.output.toString()).contains("Request URI = /one");
}
@Test
public void shouldFindController2() throws Exception {
this.mvc.perform(get("/two")).andExpect(content().string("hellotwo"))
.andExpect(status().isOk());
this.mvc.perform(get("/two")).andExpect(content().string("hellotwo")).andExpect(status().isOk());
}
@Test
public void shouldFindControllerAdvice() throws Exception {
this.mvc.perform(get("/error")).andExpect(content().string("recovered"))
.andExpect(status().isOk());
this.mvc.perform(get("/error")).andExpect(content().string("recovered")).andExpect(status().isOk());
}
@Test

View File

@@ -55,26 +55,22 @@ public class WebMvcTestAllControllersIntegrationTests {
@Test
public void shouldFindController1() throws Exception {
this.mvc.perform(get("/one")).andExpect(content().string("one"))
.andExpect(status().isOk());
this.mvc.perform(get("/one")).andExpect(content().string("one")).andExpect(status().isOk());
}
@Test
public void shouldFindController2() throws Exception {
this.mvc.perform(get("/two")).andExpect(content().string("hellotwo"))
.andExpect(status().isOk());
this.mvc.perform(get("/two")).andExpect(content().string("hellotwo")).andExpect(status().isOk());
}
@Test
public void shouldFindControllerAdvice() throws Exception {
this.mvc.perform(get("/error")).andExpect(content().string("recovered"))
.andExpect(status().isOk());
this.mvc.perform(get("/error")).andExpect(content().string("recovered")).andExpect(status().isOk());
}
@Test
public void shouldRunValidationSuccess() throws Exception {
this.mvc.perform(get("/three/OK")).andExpect(status().isOk())
.andExpect(content().string("Hello OK"));
this.mvc.perform(get("/three/OK")).andExpect(status().isOk()).andExpect(content().string("Hello OK"));
}
@Test

View File

@@ -44,26 +44,22 @@ public class WebMvcTestAutoConfigurationIntegrationTests {
@Test
public void freemarkerAutoConfigurationWasImported() {
assertThat(this.applicationContext)
.has(importedAutoConfiguration(FreeMarkerAutoConfiguration.class));
assertThat(this.applicationContext).has(importedAutoConfiguration(FreeMarkerAutoConfiguration.class));
}
@Test
public void groovyTemplatesAutoConfigurationWasImported() {
assertThat(this.applicationContext)
.has(importedAutoConfiguration(GroovyTemplateAutoConfiguration.class));
assertThat(this.applicationContext).has(importedAutoConfiguration(GroovyTemplateAutoConfiguration.class));
}
@Test
public void mustacheAutoConfigurationWasImported() {
assertThat(this.applicationContext)
.has(importedAutoConfiguration(MustacheAutoConfiguration.class));
assertThat(this.applicationContext).has(importedAutoConfiguration(MustacheAutoConfiguration.class));
}
@Test
public void thymeleafAutoConfigurationWasImported() {
assertThat(this.applicationContext)
.has(importedAutoConfiguration(ThymeleafAutoConfiguration.class));
assertThat(this.applicationContext).has(importedAutoConfiguration(ThymeleafAutoConfiguration.class));
}
}

View File

@@ -41,14 +41,14 @@ public class WebMvcTestHateoasIntegrationTests {
@Test
public void plainResponse() throws Exception {
this.mockMvc.perform(get("/hateoas/plain")).andExpect(header()
.string(HttpHeaders.CONTENT_TYPE, "application/json;charset=UTF-8"));
this.mockMvc.perform(get("/hateoas/plain"))
.andExpect(header().string(HttpHeaders.CONTENT_TYPE, "application/json;charset=UTF-8"));
}
@Test
public void hateoasResponse() throws Exception {
this.mockMvc.perform(get("/hateoas/resource")).andExpect(header()
.string(HttpHeaders.CONTENT_TYPE, "application/hal+json;charset=UTF-8"));
this.mockMvc.perform(get("/hateoas/resource"))
.andExpect(header().string(HttpHeaders.CONTENT_TYPE, "application/hal+json;charset=UTF-8"));
}
}

View File

@@ -46,8 +46,7 @@ public class WebMvcTestOneControllerIntegrationTests {
@Test
public void shouldFindController2() throws Exception {
this.mvc.perform(get("/two")).andExpect(content().string("hellotwo"))
.andExpect(status().isOk());
this.mvc.perform(get("/two")).andExpect(content().string("hellotwo")).andExpect(status().isOk());
}
}

View File

@@ -48,8 +48,7 @@ public class WebMvcTestPrintAlwaysIntegrationTests {
@Test
public void shouldPrint() throws Exception {
this.mvc.perform(get("/one")).andExpect(content().string("one"))
.andExpect(status().isOk());
this.mvc.perform(get("/one")).andExpect(content().string("one")).andExpect(status().isOk());
assertThat(this.output.toString()).contains("Request URI = /one");
}

View File

@@ -41,14 +41,12 @@ public class WebMvcTestPrintDefaultIntegrationTests {
@Test
public void shouldNotPrint() throws Exception {
this.mvc.perform(get("/one")).andExpect(content().string("one"))
.andExpect(status().isOk());
this.mvc.perform(get("/one")).andExpect(content().string("one")).andExpect(status().isOk());
}
@Test
public void shouldPrint() throws Exception {
this.mvc.perform(get("/one")).andExpect(content().string("none"))
.andExpect(status().isOk());
this.mvc.perform(get("/one")).andExpect(content().string("none")).andExpect(status().isOk());
}
}

View File

@@ -49,8 +49,7 @@ public class WebMvcTestPrintDefaultOverrideIntegrationTests {
@Test
public void shouldFindController1() throws Exception {
this.mvc.perform(get("/one")).andExpect(content().string("one"))
.andExpect(status().isOk());
this.mvc.perform(get("/one")).andExpect(content().string("one")).andExpect(status().isOk());
assertThat(this.output.toString()).doesNotContain("Request URI = /one");
}

View File

@@ -48,8 +48,7 @@ public class WebMvcTestPrintOverrideIntegrationTests {
@Test
public void shouldNotPrint() throws Exception {
this.mvc.perform(get("/one")).andExpect(content().string("one"))
.andExpect(status().isOk());
this.mvc.perform(get("/one")).andExpect(content().string("one")).andExpect(status().isOk());
assertThat(this.output.toString()).doesNotContain("Request URI = /one");
}

View File

@@ -40,8 +40,7 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.
*/
@RunWith(SpringRunner.class)
@WebMvcTest
@AutoConfigureMockMvc(addFilters = false, webClientEnabled = false,
webDriverEnabled = false)
@AutoConfigureMockMvc(addFilters = false, webClientEnabled = false, webDriverEnabled = false)
public class WebMvcTestWithAutoConfigureMockMvcIntegrationTests {
@Rule

View File

@@ -45,8 +45,7 @@ public class WebMvcTypeExcludeFilterTests {
@Test
public void matchWhenHasNoControllers() throws Exception {
WebMvcTypeExcludeFilter filter = new WebMvcTypeExcludeFilter(
WithNoControllers.class);
WebMvcTypeExcludeFilter filter = new WebMvcTypeExcludeFilter(WithNoControllers.class);
assertThat(excludes(filter, Controller1.class)).isFalse();
assertThat(excludes(filter, Controller2.class)).isFalse();
assertThat(excludes(filter, ExampleControllerAdvice.class)).isFalse();
@@ -58,8 +57,7 @@ public class WebMvcTypeExcludeFilterTests {
@Test
public void matchWhenHasController() throws Exception {
WebMvcTypeExcludeFilter filter = new WebMvcTypeExcludeFilter(
WithController.class);
WebMvcTypeExcludeFilter filter = new WebMvcTypeExcludeFilter(WithController.class);
assertThat(excludes(filter, Controller1.class)).isFalse();
assertThat(excludes(filter, Controller2.class)).isTrue();
assertThat(excludes(filter, ExampleControllerAdvice.class)).isFalse();
@@ -71,8 +69,7 @@ public class WebMvcTypeExcludeFilterTests {
@Test
public void matchNotUsingDefaultFilters() throws Exception {
WebMvcTypeExcludeFilter filter = new WebMvcTypeExcludeFilter(
NotUsingDefaultFilters.class);
WebMvcTypeExcludeFilter filter = new WebMvcTypeExcludeFilter(NotUsingDefaultFilters.class);
assertThat(excludes(filter, Controller1.class)).isTrue();
assertThat(excludes(filter, Controller2.class)).isTrue();
assertThat(excludes(filter, ExampleControllerAdvice.class)).isTrue();
@@ -84,8 +81,7 @@ public class WebMvcTypeExcludeFilterTests {
@Test
public void matchWithIncludeFilter() throws Exception {
WebMvcTypeExcludeFilter filter = new WebMvcTypeExcludeFilter(
WithIncludeFilter.class);
WebMvcTypeExcludeFilter filter = new WebMvcTypeExcludeFilter(WithIncludeFilter.class);
assertThat(excludes(filter, Controller1.class)).isFalse();
assertThat(excludes(filter, Controller2.class)).isFalse();
assertThat(excludes(filter, ExampleControllerAdvice.class)).isFalse();
@@ -97,8 +93,7 @@ public class WebMvcTypeExcludeFilterTests {
@Test
public void matchWithExcludeFilter() throws Exception {
WebMvcTypeExcludeFilter filter = new WebMvcTypeExcludeFilter(
WithExcludeFilter.class);
WebMvcTypeExcludeFilter filter = new WebMvcTypeExcludeFilter(WithExcludeFilter.class);
assertThat(excludes(filter, Controller1.class)).isTrue();
assertThat(excludes(filter, Controller2.class)).isFalse();
assertThat(excludes(filter, ExampleControllerAdvice.class)).isFalse();
@@ -108,10 +103,8 @@ public class WebMvcTypeExcludeFilterTests {
assertThat(excludes(filter, ExampleRepository.class)).isTrue();
}
private boolean excludes(WebMvcTypeExcludeFilter filter, Class<?> type)
throws IOException {
MetadataReader metadataReader = this.metadataReaderFactory
.getMetadataReader(type.getName());
private boolean excludes(WebMvcTypeExcludeFilter filter, Class<?> type) throws IOException {
MetadataReader metadataReader = this.metadataReaderFactory.getMetadataReader(type.getName());
return filter.match(metadataReader, this.metadataReaderFactory);
}
@@ -135,8 +128,7 @@ public class WebMvcTypeExcludeFilterTests {
}
@WebMvcTest(excludeFilters = @Filter(type = FilterType.ASSIGNABLE_TYPE,
classes = Controller1.class))
@WebMvcTest(excludeFilters = @Filter(type = FilterType.ASSIGNABLE_TYPE, classes = Controller1.class))
static class WithExcludeFilter {
}