Merge branch '2.0.x' into 2.1.x

Closes gh-17078
This commit is contained in:
Andy Wilkinson
2019-06-07 10:50:34 +01:00
2691 changed files with 27746 additions and 46049 deletions

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -38,8 +38,7 @@ import org.springframework.util.ClassUtils;
*/
public final class AnnotatedClassFinder {
private static final Map<String, Class<?>> cache = Collections
.synchronizedMap(new Cache(40));
private static final Map<String, Class<?>> cache = Collections.synchronizedMap(new Cache(40));
private final Class<? extends Annotation> annotationType;
@@ -90,11 +89,9 @@ public final class AnnotatedClassFinder {
while (!source.isEmpty()) {
Set<BeanDefinition> components = this.scanner.findCandidateComponents(source);
if (!components.isEmpty()) {
Assert.state(components.size() == 1,
() -> "Found multiple @" + this.annotationType.getSimpleName()
+ " annotated classes " + components);
return ClassUtils.resolveClassName(
components.iterator().next().getBeanClassName(), null);
Assert.state(components.size() == 1, () -> "Found multiple @" + this.annotationType.getSimpleName()
+ " annotated classes " + components);
return ClassUtils.resolveClassName(components.iterator().next().getBeanClassName(), null);
}
source = getParentPackage(source);
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2017 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -37,8 +37,7 @@ public class ConfigFileApplicationContextInitializer
public void initialize(ConfigurableApplicationContext applicationContext) {
new ConfigFileApplicationListener() {
public void apply() {
addPropertySources(applicationContext.getEnvironment(),
applicationContext);
addPropertySources(applicationContext.getEnvironment(), applicationContext);
addPostProcessors(applicationContext);
}
}.apply();

View File

@@ -48,8 +48,7 @@ public class FilteredClassLoader extends URLClassLoader {
* @param hiddenClasses the classes to hide
*/
public FilteredClassLoader(Class<?>... hiddenClasses) {
this(Collections.singleton(ClassFilter.of(hiddenClasses)),
Collections.emptyList());
this(Collections.singleton(ClassFilter.of(hiddenClasses)), Collections.emptyList());
}
/**
@@ -57,8 +56,7 @@ public class FilteredClassLoader extends URLClassLoader {
* @param hiddenPackages the packages to hide
*/
public FilteredClassLoader(String... hiddenPackages) {
this(Collections.singleton(PackageFilter.of(hiddenPackages)),
Collections.emptyList());
this(Collections.singleton(PackageFilter.of(hiddenPackages)), Collections.emptyList());
}
/**
@@ -68,8 +66,7 @@ public class FilteredClassLoader extends URLClassLoader {
* @since 2.1.0
*/
public FilteredClassLoader(ClassPathResource... hiddenResources) {
this(Collections.emptyList(),
Collections.singleton(ClassPathResourceFilter.of(hiddenResources)));
this(Collections.emptyList(), Collections.singleton(ClassPathResourceFilter.of(hiddenResources)));
}
/**
@@ -92,8 +89,7 @@ public class FilteredClassLoader extends URLClassLoader {
}
@Override
protected Class<?> loadClass(String name, boolean resolve)
throws ClassNotFoundException {
protected Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException {
for (Predicate<String> filter : this.classesFilters) {
if (filter.test(name)) {
throw new ClassNotFoundException();
@@ -202,8 +198,7 @@ public class FilteredClassLoader extends URLClassLoader {
@Override
public boolean test(String resourceName) {
for (ClassPathResource hiddenResource : this.hiddenResources) {
if (hiddenResource.getFilename() != null
&& resourceName.equals(hiddenResource.getPath())) {
if (hiddenResource.getFilename() != null && resourceName.equals(hiddenResource.getPath())) {
return true;
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -76,24 +76,20 @@ class ImportsContextCustomizer implements ContextCustomizer {
public void customizeContext(ConfigurableApplicationContext context,
MergedContextConfiguration mergedContextConfiguration) {
BeanDefinitionRegistry registry = getBeanDefinitionRegistry(context);
AnnotatedBeanDefinitionReader reader = new AnnotatedBeanDefinitionReader(
registry);
AnnotatedBeanDefinitionReader reader = new AnnotatedBeanDefinitionReader(registry);
registerCleanupPostProcessor(registry, reader);
registerImportsConfiguration(registry, reader);
}
private void registerCleanupPostProcessor(BeanDefinitionRegistry registry,
AnnotatedBeanDefinitionReader reader) {
BeanDefinition definition = registerBean(registry, reader,
ImportsCleanupPostProcessor.BEAN_NAME, ImportsCleanupPostProcessor.class);
definition.getConstructorArgumentValues().addIndexedArgumentValue(0,
this.testClass);
private void registerCleanupPostProcessor(BeanDefinitionRegistry registry, AnnotatedBeanDefinitionReader reader) {
BeanDefinition definition = registerBean(registry, reader, ImportsCleanupPostProcessor.BEAN_NAME,
ImportsCleanupPostProcessor.class);
definition.getConstructorArgumentValues().addIndexedArgumentValue(0, this.testClass);
}
private void registerImportsConfiguration(BeanDefinitionRegistry registry,
AnnotatedBeanDefinitionReader reader) {
BeanDefinition definition = registerBean(registry, reader,
ImportsConfiguration.BEAN_NAME, ImportsConfiguration.class);
private void registerImportsConfiguration(BeanDefinitionRegistry registry, AnnotatedBeanDefinitionReader reader) {
BeanDefinition definition = registerBean(registry, reader, ImportsConfiguration.BEAN_NAME,
ImportsConfiguration.class);
definition.setAttribute(TEST_CLASS_ATTRIBUTE, this.testClass);
}
@@ -102,15 +98,14 @@ class ImportsContextCustomizer implements ContextCustomizer {
return (BeanDefinitionRegistry) context;
}
if (context instanceof AbstractApplicationContext) {
return (BeanDefinitionRegistry) ((AbstractApplicationContext) context)
.getBeanFactory();
return (BeanDefinitionRegistry) ((AbstractApplicationContext) context).getBeanFactory();
}
throw new IllegalStateException("Could not locate BeanDefinitionRegistry");
}
@SuppressWarnings("unchecked")
private BeanDefinition registerBean(BeanDefinitionRegistry registry,
AnnotatedBeanDefinitionReader reader, String beanName, Class<?> type) {
private BeanDefinition registerBean(BeanDefinitionRegistry registry, AnnotatedBeanDefinitionReader reader,
String beanName, Class<?> type) {
reader.registerBean(type, beanName);
return registry.getBeanDefinition(beanName);
}
@@ -166,12 +161,9 @@ class ImportsContextCustomizer implements ContextCustomizer {
@Override
public String[] selectImports(AnnotationMetadata importingClassMetadata) {
BeanDefinition definition = this.beanFactory
.getBeanDefinition(ImportsConfiguration.BEAN_NAME);
Object testClass = (definition != null)
? definition.getAttribute(TEST_CLASS_ATTRIBUTE) : null;
return (testClass != null) ? new String[] { ((Class<?>) testClass).getName() }
: NO_IMPORTS;
BeanDefinition definition = this.beanFactory.getBeanDefinition(ImportsConfiguration.BEAN_NAME);
Object testClass = (definition != null) ? definition.getAttribute(TEST_CLASS_ATTRIBUTE) : null;
return (testClass != null) ? new String[] { ((Class<?>) testClass).getName() } : NO_IMPORTS;
}
}
@@ -181,8 +173,7 @@ class ImportsContextCustomizer implements ContextCustomizer {
* added to load imports.
*/
@Order(Ordered.LOWEST_PRECEDENCE)
static class ImportsCleanupPostProcessor
implements BeanDefinitionRegistryPostProcessor {
static class ImportsCleanupPostProcessor implements BeanDefinitionRegistryPostProcessor {
static final String BEAN_NAME = ImportsCleanupPostProcessor.class.getName();
@@ -193,13 +184,11 @@ class ImportsContextCustomizer implements ContextCustomizer {
}
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory)
throws BeansException {
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
}
@Override
public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry)
throws BeansException {
public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {
try {
String[] names = registry.getBeanDefinitionNames();
for (String name : names) {
@@ -244,12 +233,10 @@ class ImportsContextCustomizer implements ContextCustomizer {
Set<Class<?>> seen = new HashSet<>();
collectClassAnnotations(testClass, annotations, seen);
Set<Object> determinedImports = determineImports(annotations, testClass);
this.key = Collections.unmodifiableSet(
(determinedImports != null) ? determinedImports : annotations);
this.key = Collections.unmodifiableSet((determinedImports != null) ? determinedImports : annotations);
}
private void collectClassAnnotations(Class<?> classType,
Set<Annotation> annotations, Set<Class<?>> seen) {
private void collectClassAnnotations(Class<?> classType, Set<Annotation> annotations, Set<Class<?>> seen) {
if (seen.add(classType)) {
collectElementAnnotations(classType, annotations, seen);
for (Class<?> interfaceType : classType.getInterfaces()) {
@@ -261,13 +248,12 @@ class ImportsContextCustomizer implements ContextCustomizer {
}
}
private void collectElementAnnotations(AnnotatedElement element,
Set<Annotation> annotations, Set<Class<?>> seen) {
private void collectElementAnnotations(AnnotatedElement element, Set<Annotation> annotations,
Set<Class<?>> seen) {
for (Annotation annotation : element.getDeclaredAnnotations()) {
if (!isIgnoredAnnotation(annotation)) {
annotations.add(annotation);
collectClassAnnotations(annotation.annotationType(), annotations,
seen);
collectClassAnnotations(annotation.annotationType(), annotations, seen);
}
}
}
@@ -281,15 +267,12 @@ class ImportsContextCustomizer implements ContextCustomizer {
return false;
}
private Set<Object> determineImports(Set<Annotation> annotations,
Class<?> testClass) {
private Set<Object> determineImports(Set<Annotation> annotations, Class<?> testClass) {
Set<Object> determinedImports = new LinkedHashSet<>();
AnnotationMetadata testClassMetadata = new StandardAnnotationMetadata(
testClass);
AnnotationMetadata testClassMetadata = new StandardAnnotationMetadata(testClass);
for (Annotation annotation : annotations) {
for (Class<?> source : getImports(annotation)) {
Set<Object> determinedSourceImports = determineImports(source,
testClassMetadata);
Set<Object> determinedSourceImports = determineImports(source, testClassMetadata);
if (determinedSourceImports == null) {
return null;
}
@@ -306,12 +289,10 @@ class ImportsContextCustomizer implements ContextCustomizer {
return NO_IMPORTS;
}
private Set<Object> determineImports(Class<?> source,
AnnotationMetadata metadata) {
private Set<Object> determineImports(Class<?> source, AnnotationMetadata metadata) {
if (DeterminableImports.class.isAssignableFrom(source)) {
// We can determine the imports
return ((DeterminableImports) instantiate(source))
.determineImports(metadata);
return ((DeterminableImports) instantiate(source)).determineImports(metadata);
}
if (ImportSelector.class.isAssignableFrom(source)
|| ImportBeanDefinitionRegistrar.class.isAssignableFrom(source)) {
@@ -331,17 +312,14 @@ class ImportsContextCustomizer implements ContextCustomizer {
return (T) constructor.newInstance();
}
catch (Throwable ex) {
throw new IllegalStateException(
"Unable to instantiate DeterminableImportSelector "
+ source.getName(),
throw new IllegalStateException("Unable to instantiate DeterminableImportSelector " + source.getName(),
ex);
}
}
@Override
public boolean equals(Object obj) {
return (obj != null && getClass() == obj.getClass()
&& this.key.equals(((ContextCustomizerKey) obj).key));
return (obj != null && getClass() == obj.getClass() && this.key.equals(((ContextCustomizerKey) obj).key));
}
@Override

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2017 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -27,8 +27,7 @@ import org.springframework.test.context.MergedContextConfiguration;
*/
public class ReactiveWebMergedContextConfiguration extends MergedContextConfiguration {
public ReactiveWebMergedContextConfiguration(
MergedContextConfiguration mergedConfig) {
public ReactiveWebMergedContextConfiguration(MergedContextConfiguration mergedConfig) {
super(mergedConfig);
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -78,18 +78,13 @@ import org.springframework.web.context.support.GenericWebApplicationContext;
public class SpringBootContextLoader extends AbstractContextLoader {
@Override
public ApplicationContext loadContext(MergedContextConfiguration config)
throws Exception {
public ApplicationContext loadContext(MergedContextConfiguration config) throws Exception {
Class<?>[] configClasses = config.getClasses();
String[] configLocations = config.getLocations();
Assert.state(
!ObjectUtils.isEmpty(configClasses)
|| !ObjectUtils.isEmpty(configLocations),
() -> "No configuration classes "
+ "or locations found in @SpringApplicationConfiguration. "
+ "For default configuration detection to work you need "
+ "Spring 4.0.3 or better (found " + SpringVersion.getVersion()
+ ").");
Assert.state(!ObjectUtils.isEmpty(configClasses) || !ObjectUtils.isEmpty(configLocations),
() -> "No configuration classes " + "or locations found in @SpringApplicationConfiguration. "
+ "For default configuration detection to work you need " + "Spring 4.0.3 or better (found "
+ SpringVersion.getVersion() + ").");
SpringApplication application = getSpringApplication();
application.setMainApplicationClass(config.getTestClass());
application.addPrimarySources(Arrays.asList(configClasses));
@@ -98,16 +93,13 @@ public class SpringBootContextLoader extends AbstractContextLoader {
if (!ObjectUtils.isEmpty(config.getActiveProfiles())) {
setActiveProfiles(environment, config.getActiveProfiles());
}
ResourceLoader resourceLoader = (application.getResourceLoader() != null)
? application.getResourceLoader()
ResourceLoader resourceLoader = (application.getResourceLoader() != null) ? application.getResourceLoader()
: new DefaultResourceLoader(getClass().getClassLoader());
TestPropertySourceUtils.addPropertiesFilesToEnvironment(environment,
resourceLoader, config.getPropertySourceLocations());
TestPropertySourceUtils.addInlinedPropertiesToEnvironment(environment,
getInlinedProperties(config));
TestPropertySourceUtils.addPropertiesFilesToEnvironment(environment, resourceLoader,
config.getPropertySourceLocations());
TestPropertySourceUtils.addInlinedPropertiesToEnvironment(environment, getInlinedProperties(config));
application.setEnvironment(environment);
List<ApplicationContextInitializer<?>> initializers = getInitializers(config,
application);
List<ApplicationContextInitializer<?>> initializers = getInitializers(config, application);
if (config instanceof WebMergedContextConfiguration) {
application.setWebApplicationType(WebApplicationType.SERVLET);
if (!isEmbeddedWebEnvironment(config)) {
@@ -145,11 +137,8 @@ public class SpringBootContextLoader extends AbstractContextLoader {
return new StandardEnvironment();
}
private void setActiveProfiles(ConfigurableEnvironment environment,
String[] profiles) {
TestPropertyValues
.of("spring.profiles.active="
+ StringUtils.arrayToCommaDelimitedString(profiles))
private void setActiveProfiles(ConfigurableEnvironment environment, String[] profiles) {
TestPropertyValues.of("spring.profiles.active=" + StringUtils.arrayToCommaDelimitedString(profiles))
.applyTo(environment);
}
@@ -173,10 +162,9 @@ public class SpringBootContextLoader extends AbstractContextLoader {
return binder.bind("server.port", Bindable.of(String.class)).isBound();
}
private ConfigurationPropertySource convertToConfigurationPropertySource(
List<String> properties) {
return new MapConfigurationPropertySource(TestPropertySourceUtils
.convertInlinedPropertiesToMap(StringUtils.toStringArray(properties)));
private ConfigurationPropertySource convertToConfigurationPropertySource(List<String> properties) {
return new MapConfigurationPropertySource(
TestPropertySourceUtils.convertInlinedPropertiesToMap(StringUtils.toStringArray(properties)));
}
/**
@@ -191,8 +179,8 @@ public class SpringBootContextLoader extends AbstractContextLoader {
* @return the initializers to apply
* @since 2.0.0
*/
protected List<ApplicationContextInitializer<?>> getInitializers(
MergedContextConfiguration config, SpringApplication application) {
protected List<ApplicationContextInitializer<?>> getInitializers(MergedContextConfiguration config,
SpringApplication application) {
List<ApplicationContextInitializer<?>> initializers = new ArrayList<>();
for (ContextCustomizer contextCustomizer : config.getContextCustomizers()) {
initializers.add(new ContextCustomizerAdapter(contextCustomizer, config));
@@ -203,15 +191,14 @@ public class SpringBootContextLoader extends AbstractContextLoader {
initializers.add(BeanUtils.instantiateClass(initializerClass));
}
if (config.getParent() != null) {
initializers.add(new ParentContextApplicationContextInitializer(
config.getParentApplicationContext()));
initializers.add(new ParentContextApplicationContextInitializer(config.getParentApplicationContext()));
}
return initializers;
}
private boolean isEmbeddedWebEnvironment(MergedContextConfiguration config) {
SpringBootTest annotation = AnnotatedElementUtils
.findMergedAnnotation(config.getTestClass(), SpringBootTest.class);
SpringBootTest annotation = AnnotatedElementUtils.findMergedAnnotation(config.getTestClass(),
SpringBootTest.class);
if (annotation != null && annotation.webEnvironment().isEmbedded()) {
return true;
}
@@ -219,12 +206,10 @@ public class SpringBootContextLoader extends AbstractContextLoader {
}
@Override
public void processContextConfiguration(
ContextConfigurationAttributes configAttributes) {
public void processContextConfiguration(ContextConfigurationAttributes configAttributes) {
super.processContextConfiguration(configAttributes);
if (!configAttributes.hasResources()) {
Class<?>[] defaultConfigClasses = detectDefaultConfigurationClasses(
configAttributes.getDeclaringClass());
Class<?>[] defaultConfigClasses = detectDefaultConfigurationClasses(configAttributes.getDeclaringClass());
configAttributes.setClasses(defaultConfigClasses);
}
}
@@ -239,14 +224,13 @@ public class SpringBootContextLoader extends AbstractContextLoader {
* @see AnnotationConfigContextLoaderUtils
*/
protected Class<?>[] detectDefaultConfigurationClasses(Class<?> declaringClass) {
return AnnotationConfigContextLoaderUtils
.detectDefaultConfigurationClasses(declaringClass);
return AnnotationConfigContextLoaderUtils.detectDefaultConfigurationClasses(declaringClass);
}
@Override
public ApplicationContext loadContext(String... locations) throws Exception {
throw new UnsupportedOperationException("SpringApplicationContextLoader "
+ "does not support the loadContext(String...) method");
throw new UnsupportedOperationException(
"SpringApplicationContextLoader " + "does not support the loadContext(String...) method");
}
@Override
@@ -266,21 +250,18 @@ public class SpringBootContextLoader extends AbstractContextLoader {
private static final Class<GenericWebApplicationContext> WEB_CONTEXT_CLASS = GenericWebApplicationContext.class;
void configure(MergedContextConfiguration configuration,
SpringApplication application,
void configure(MergedContextConfiguration configuration, SpringApplication application,
List<ApplicationContextInitializer<?>> initializers) {
WebMergedContextConfiguration webConfiguration = (WebMergedContextConfiguration) configuration;
addMockServletContext(initializers, webConfiguration);
application.setApplicationContextClass(WEB_CONTEXT_CLASS);
}
private void addMockServletContext(
List<ApplicationContextInitializer<?>> initializers,
private void addMockServletContext(List<ApplicationContextInitializer<?>> initializers,
WebMergedContextConfiguration webConfiguration) {
SpringBootMockServletContext servletContext = new SpringBootMockServletContext(
webConfiguration.getResourceBasePath());
initializers.add(0, new ServletContextApplicationContextInitializer(
servletContext, true));
initializers.add(0, new ServletContextApplicationContextInitializer(servletContext, true));
}
}
@@ -309,8 +290,7 @@ public class SpringBootContextLoader extends AbstractContextLoader {
private final MergedContextConfiguration config;
ContextCustomizerAdapter(ContextCustomizer contextCustomizer,
MergedContextConfiguration config) {
ContextCustomizerAdapter(ContextCustomizer contextCustomizer, MergedContextConfiguration config) {
this.contextCustomizer = contextCustomizer;
this.config = config;
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -83,24 +83,21 @@ public class SpringBootTestContextBootstrapper extends DefaultTestContextBootstr
private static final String REACTIVE_WEB_ENVIRONMENT_CLASS = "org.springframework."
+ "web.reactive.DispatcherHandler";
private static final String MVC_WEB_ENVIRONMENT_CLASS = "org.springframework."
+ "web.servlet.DispatcherServlet";
private static final String MVC_WEB_ENVIRONMENT_CLASS = "org.springframework." + "web.servlet.DispatcherServlet";
private static final String JERSEY_WEB_ENVIRONMENT_CLASS = "org.glassfish.jersey.server.ResourceConfig";
private static final String ACTIVATE_SERVLET_LISTENER = "org.springframework.test."
+ "context.web.ServletTestExecutionListener.activateListener";
private static final Log logger = LogFactory
.getLog(SpringBootTestContextBootstrapper.class);
private static final Log logger = LogFactory.getLog(SpringBootTestContextBootstrapper.class);
@Override
public TestContext buildTestContext() {
TestContext context = super.buildTestContext();
verifyConfiguration(context.getTestClass());
WebEnvironment webEnvironment = getWebEnvironment(context.getTestClass());
if (webEnvironment == WebEnvironment.MOCK
&& deduceWebApplicationType() == WebApplicationType.SERVLET) {
if (webEnvironment == WebEnvironment.MOCK && deduceWebApplicationType() == WebApplicationType.SERVLET) {
context.setAttribute(ACTIVATE_SERVLET_LISTENER, true);
}
else if (webEnvironment != null && webEnvironment.isEmbedded()) {
@@ -113,8 +110,7 @@ public class SpringBootTestContextBootstrapper extends DefaultTestContextBootstr
protected Set<Class<? extends TestExecutionListener>> getDefaultTestExecutionListenerClasses() {
Set<Class<? extends TestExecutionListener>> listeners = super.getDefaultTestExecutionListenerClasses();
List<DefaultTestExecutionListenersPostProcessor> postProcessors = SpringFactoriesLoader
.loadFactories(DefaultTestExecutionListenersPostProcessor.class,
getClass().getClassLoader());
.loadFactories(DefaultTestExecutionListenersPostProcessor.class, getClass().getClassLoader());
for (DefaultTestExecutionListenersPostProcessor postProcessor : postProcessors) {
listeners = postProcessor.postProcessDefaultTestExecutionListeners(listeners);
}
@@ -133,8 +129,7 @@ public class SpringBootTestContextBootstrapper extends DefaultTestContextBootstr
return super.resolveContextLoader(testClass, configAttributesList);
}
private void addConfigAttributesClasses(
ContextConfigurationAttributes configAttributes, Class<?>[] classes) {
private void addConfigAttributesClasses(ContextConfigurationAttributes configAttributes, Class<?>[] classes) {
List<Class<?>> combined = new ArrayList<>();
combined.addAll(Arrays.asList(classes));
if (configAttributes.getClasses() != null) {
@@ -144,51 +139,39 @@ public class SpringBootTestContextBootstrapper extends DefaultTestContextBootstr
}
@Override
protected Class<? extends ContextLoader> getDefaultContextLoaderClass(
Class<?> testClass) {
protected Class<? extends ContextLoader> getDefaultContextLoaderClass(Class<?> testClass) {
return SpringBootContextLoader.class;
}
@Override
protected MergedContextConfiguration processMergedContextConfiguration(
MergedContextConfiguration mergedConfig) {
protected MergedContextConfiguration processMergedContextConfiguration(MergedContextConfiguration mergedConfig) {
Class<?>[] classes = getOrFindConfigurationClasses(mergedConfig);
List<String> propertySourceProperties = getAndProcessPropertySourceProperties(
mergedConfig);
mergedConfig = createModifiedConfig(mergedConfig, classes,
StringUtils.toStringArray(propertySourceProperties));
List<String> propertySourceProperties = getAndProcessPropertySourceProperties(mergedConfig);
mergedConfig = createModifiedConfig(mergedConfig, classes, StringUtils.toStringArray(propertySourceProperties));
WebEnvironment webEnvironment = getWebEnvironment(mergedConfig.getTestClass());
if (webEnvironment != null && isWebEnvironmentSupported(mergedConfig)) {
WebApplicationType webApplicationType = getWebApplicationType(mergedConfig);
if (webApplicationType == WebApplicationType.SERVLET
&& (webEnvironment.isEmbedded()
|| webEnvironment == WebEnvironment.MOCK)) {
&& (webEnvironment.isEmbedded() || webEnvironment == WebEnvironment.MOCK)) {
WebAppConfiguration webAppConfiguration = AnnotatedElementUtils
.findMergedAnnotation(mergedConfig.getTestClass(),
WebAppConfiguration.class);
String resourceBasePath = (webAppConfiguration != null)
? webAppConfiguration.value() : "src/main/webapp";
mergedConfig = new WebMergedContextConfiguration(mergedConfig,
resourceBasePath);
.findMergedAnnotation(mergedConfig.getTestClass(), WebAppConfiguration.class);
String resourceBasePath = (webAppConfiguration != null) ? webAppConfiguration.value()
: "src/main/webapp";
mergedConfig = new WebMergedContextConfiguration(mergedConfig, resourceBasePath);
}
else if (webApplicationType == WebApplicationType.REACTIVE
&& (webEnvironment.isEmbedded()
|| webEnvironment == WebEnvironment.MOCK)) {
&& (webEnvironment.isEmbedded() || webEnvironment == WebEnvironment.MOCK)) {
return new ReactiveWebMergedContextConfiguration(mergedConfig);
}
}
return mergedConfig;
}
private WebApplicationType getWebApplicationType(
MergedContextConfiguration configuration) {
private WebApplicationType getWebApplicationType(MergedContextConfiguration configuration) {
ConfigurationPropertySource source = new MapConfigurationPropertySource(
TestPropertySourceUtils.convertInlinedPropertiesToMap(
configuration.getPropertySourceProperties()));
TestPropertySourceUtils.convertInlinedPropertiesToMap(configuration.getPropertySourceProperties()));
Binder binder = new Binder(source);
return binder
.bind("spring.main.web-application-type",
Bindable.of(WebApplicationType.class))
return binder.bind("spring.main.web-application-type", Bindable.of(WebApplicationType.class))
.orElseGet(this::deduceWebApplicationType);
}
@@ -208,22 +191,19 @@ public class SpringBootTestContextBootstrapper extends DefaultTestContextBootstr
private boolean isWebEnvironmentSupported(MergedContextConfiguration mergedConfig) {
Class<?> testClass = mergedConfig.getTestClass();
ContextHierarchy hierarchy = AnnotationUtils.getAnnotation(testClass,
ContextHierarchy.class);
ContextHierarchy hierarchy = AnnotationUtils.getAnnotation(testClass, ContextHierarchy.class);
if (hierarchy == null || hierarchy.value().length == 0) {
return true;
}
ContextConfiguration[] configurations = hierarchy.value();
return isFromConfiguration(mergedConfig,
configurations[configurations.length - 1]);
return isFromConfiguration(mergedConfig, configurations[configurations.length - 1]);
}
private boolean isFromConfiguration(MergedContextConfiguration candidateConfig,
ContextConfiguration configuration) {
ContextConfigurationAttributes attributes = new ContextConfigurationAttributes(
candidateConfig.getTestClass(), configuration);
Set<Class<?>> configurationClasses = new HashSet<>(
Arrays.asList(attributes.getClasses()));
ContextConfigurationAttributes attributes = new ContextConfigurationAttributes(candidateConfig.getTestClass(),
configuration);
Set<Class<?>> configurationClasses = new HashSet<>(Arrays.asList(attributes.getClasses()));
for (Class<?> candidate : candidateConfig.getClasses()) {
if (configurationClasses.contains(candidate)) {
return true;
@@ -232,20 +212,16 @@ public class SpringBootTestContextBootstrapper extends DefaultTestContextBootstr
return false;
}
protected Class<?>[] getOrFindConfigurationClasses(
MergedContextConfiguration mergedConfig) {
protected Class<?>[] getOrFindConfigurationClasses(MergedContextConfiguration mergedConfig) {
Class<?>[] classes = mergedConfig.getClasses();
if (containsNonTestComponent(classes) || mergedConfig.hasLocations()) {
return classes;
}
Class<?> found = new AnnotatedClassFinder(SpringBootConfiguration.class)
.findFromClass(mergedConfig.getTestClass());
Assert.state(found != null,
"Unable to find a @SpringBootConfiguration, you need to use "
+ "@ContextConfiguration or @SpringBootTest(classes=...) "
+ "with your test");
logger.info("Found @SpringBootConfiguration " + found.getName() + " for test "
+ mergedConfig.getTestClass());
Assert.state(found != null, "Unable to find a @SpringBootConfiguration, you need to use "
+ "@ContextConfiguration or @SpringBootTest(classes=...) " + "with your test");
logger.info("Found @SpringBootConfiguration " + found.getName() + " for test " + mergedConfig.getTestClass());
return merge(found, classes);
}
@@ -265,8 +241,7 @@ public class SpringBootTestContextBootstrapper extends DefaultTestContextBootstr
return result;
}
private List<String> getAndProcessPropertySourceProperties(
MergedContextConfiguration mergedConfig) {
private List<String> getAndProcessPropertySourceProperties(MergedContextConfiguration mergedConfig) {
List<String> propertySourceProperties = new ArrayList<>(
Arrays.asList(mergedConfig.getPropertySourceProperties()));
String differentiator = getDifferentiatorPropertySourceProperty();
@@ -294,8 +269,7 @@ public class SpringBootTestContextBootstrapper extends DefaultTestContextBootstr
* @param mergedConfig the merged context configuration
* @param propertySourceProperties the property source properties to process
*/
protected void processPropertySourceProperties(
MergedContextConfiguration mergedConfig,
protected void processPropertySourceProperties(MergedContextConfiguration mergedConfig,
List<String> propertySourceProperties) {
Class<?> testClass = mergedConfig.getTestClass();
String[] properties = getProperties(testClass);
@@ -341,13 +315,11 @@ public class SpringBootTestContextBootstrapper extends DefaultTestContextBootstr
&& getAnnotation(WebAppConfiguration.class, testClass) != null) {
throw new IllegalStateException("@WebAppConfiguration should only be used "
+ "with @SpringBootTest when @SpringBootTest is configured with a "
+ "mock web environment. Please remove @WebAppConfiguration or "
+ "reconfigure @SpringBootTest.");
+ "mock web environment. Please remove @WebAppConfiguration or " + "reconfigure @SpringBootTest.");
}
}
private <T extends Annotation> T getAnnotation(Class<T> annotationType,
Class<?> testClass) {
private <T extends Annotation> T getAnnotation(Class<T> annotationType, Class<?> testClass) {
return AnnotatedElementUtils.getMergedAnnotation(testClass, annotationType);
}
@@ -357,10 +329,9 @@ public class SpringBootTestContextBootstrapper extends DefaultTestContextBootstr
* @param classes the replacement classes
* @return a new {@link MergedContextConfiguration}
*/
protected final MergedContextConfiguration createModifiedConfig(
MergedContextConfiguration mergedConfig, Class<?>[] classes) {
return createModifiedConfig(mergedConfig, classes,
mergedConfig.getPropertySourceProperties());
protected final MergedContextConfiguration createModifiedConfig(MergedContextConfiguration mergedConfig,
Class<?>[] classes) {
return createModifiedConfig(mergedConfig, classes, mergedConfig.getPropertySourceProperties());
}
/**
@@ -371,13 +342,10 @@ public class SpringBootTestContextBootstrapper extends DefaultTestContextBootstr
* @param propertySourceProperties the replacement properties
* @return a new {@link MergedContextConfiguration}
*/
protected final MergedContextConfiguration createModifiedConfig(
MergedContextConfiguration mergedConfig, Class<?>[] classes,
String[] propertySourceProperties) {
return new MergedContextConfiguration(mergedConfig.getTestClass(),
mergedConfig.getLocations(), classes,
mergedConfig.getContextInitializerClasses(),
mergedConfig.getActiveProfiles(),
protected final MergedContextConfiguration createModifiedConfig(MergedContextConfiguration mergedConfig,
Class<?>[] classes, String[] propertySourceProperties) {
return new MergedContextConfiguration(mergedConfig.getTestClass(), mergedConfig.getLocations(), classes,
mergedConfig.getContextInitializerClasses(), mergedConfig.getActiveProfiles(),
mergedConfig.getPropertySourceLocations(), propertySourceProperties,
mergedConfig.getContextCustomizers(), mergedConfig.getContextLoader(),
getCacheAwareContextLoaderDelegate(), mergedConfig.getParent());

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -80,13 +80,12 @@ public class ApplicationContextAssert<C extends ApplicationContext>
*/
public ApplicationContextAssert<C> hasBean(String name) {
if (this.startupFailure != null) {
throwAssertionError(contextFailedToStartWhenExpecting(
"to have bean named:%n <%s>", name));
throwAssertionError(contextFailedToStartWhenExpecting("to have bean named:%n <%s>", name));
}
if (findBean(name) == null) {
throwAssertionError(new BasicErrorMessageFactory(
"%nExpecting:%n <%s>%nto have bean named:%n <%s>%nbut found no such bean",
getApplicationContext(), name));
"%nExpecting:%n <%s>%nto have bean named:%n <%s>%nbut found no such bean", getApplicationContext(),
name));
}
return this;
}
@@ -124,8 +123,7 @@ public class ApplicationContextAssert<C extends ApplicationContext>
public ApplicationContextAssert<C> hasSingleBean(Class<?> type, Scope scope) {
Assert.notNull(scope, "Scope must not be null");
if (this.startupFailure != null) {
throwAssertionError(contextFailedToStartWhenExpecting(
"to have a single bean of type:%n <%s>", type));
throwAssertionError(contextFailedToStartWhenExpecting("to have a single bean of type:%n <%s>", type));
}
String[] names = scope.getBeanNamesForType(getApplicationContext(), type);
if (names.length == 0) {
@@ -172,8 +170,7 @@ public class ApplicationContextAssert<C extends ApplicationContext>
public ApplicationContextAssert<C> doesNotHaveBean(Class<?> type, Scope scope) {
Assert.notNull(scope, "Scope must not be null");
if (this.startupFailure != null) {
throwAssertionError(contextFailedToStartWhenExpecting(
"not to have any beans of type:%n <%s>", type));
throwAssertionError(contextFailedToStartWhenExpecting("not to have any beans of type:%n <%s>", type));
}
String[] names = scope.getBeanNamesForType(getApplicationContext(), type);
if (names.length > 0) {
@@ -197,8 +194,7 @@ public class ApplicationContextAssert<C extends ApplicationContext>
*/
public ApplicationContextAssert<C> doesNotHaveBean(String name) {
if (this.startupFailure != null) {
throwAssertionError(contextFailedToStartWhenExpecting(
"not to have any beans of name:%n <%s>", name));
throwAssertionError(contextFailedToStartWhenExpecting("not to have any beans of name:%n <%s>", name));
}
try {
Object bean = getApplicationContext().getBean(name);
@@ -224,8 +220,7 @@ public class ApplicationContextAssert<C extends ApplicationContext>
*/
public <T> AbstractObjectArrayAssert<?, String> getBeanNames(Class<T> type) {
if (this.startupFailure != null) {
throwAssertionError(contextFailedToStartWhenExpecting(
"to get beans names with type:%n <%s>", type));
throwAssertionError(contextFailedToStartWhenExpecting("to get beans names with type:%n <%s>", type));
}
return Assertions.assertThat(getApplicationContext().getBeanNamesForType(type))
.as("Bean names of type <%s> from <%s>", type, getApplicationContext());
@@ -271,19 +266,17 @@ public class ApplicationContextAssert<C extends ApplicationContext>
public <T> AbstractObjectAssert<?, T> getBean(Class<T> type, Scope scope) {
Assert.notNull(scope, "Scope must not be null");
if (this.startupFailure != null) {
throwAssertionError(contextFailedToStartWhenExpecting(
"to contain bean of type:%n <%s>", type));
throwAssertionError(contextFailedToStartWhenExpecting("to contain bean of type:%n <%s>", type));
}
String[] names = scope.getBeanNamesForType(getApplicationContext(), type);
String name = (names.length > 0) ? getPrimary(names, scope) : null;
if (names.length > 1 && name == null) {
throwAssertionError(new BasicErrorMessageFactory(
"%nExpecting:%n <%s>%nsingle bean of type:%n <%s>%nbut found:%n <%s>",
getApplicationContext(), type, names));
throwAssertionError(
new BasicErrorMessageFactory("%nExpecting:%n <%s>%nsingle bean of type:%n <%s>%nbut found:%n <%s>",
getApplicationContext(), type, names));
}
T bean = (name != null) ? getApplicationContext().getBean(name, type) : null;
return Assertions.assertThat(bean).as("Bean of type <%s> from <%s>", type,
getApplicationContext());
return Assertions.assertThat(bean).as("Bean of type <%s> from <%s>", type, getApplicationContext());
}
private String getPrimary(String[] names, Scope scope) {
@@ -306,10 +299,8 @@ public class ApplicationContextAssert<C extends ApplicationContext>
ApplicationContext context = getApplicationContext();
while (context != null) {
if (context instanceof ConfigurableApplicationContext) {
ConfigurableListableBeanFactory factory = ((ConfigurableApplicationContext) context)
.getBeanFactory();
if (factory.containsBean(name)
&& factory.getMergedBeanDefinition(name).isPrimary()) {
ConfigurableListableBeanFactory factory = ((ConfigurableApplicationContext) context).getBeanFactory();
if (factory.containsBean(name) && factory.getMergedBeanDefinition(name).isPrimary()) {
return true;
}
}
@@ -333,12 +324,10 @@ public class ApplicationContextAssert<C extends ApplicationContext>
*/
public AbstractObjectAssert<?, Object> getBean(String name) {
if (this.startupFailure != null) {
throwAssertionError(contextFailedToStartWhenExpecting(
"to contain a bean of name:%n <%s>", name));
throwAssertionError(contextFailedToStartWhenExpecting("to contain a bean of name:%n <%s>", name));
}
Object bean = findBean(name);
return Assertions.assertThat(bean).as("Bean of name <%s> from <%s>", name,
getApplicationContext());
return Assertions.assertThat(bean).as("Bean of name <%s> from <%s>", name, getApplicationContext());
}
/**
@@ -361,8 +350,8 @@ public class ApplicationContextAssert<C extends ApplicationContext>
@SuppressWarnings("unchecked")
public <T> AbstractObjectAssert<?, T> getBean(String name, Class<T> type) {
if (this.startupFailure != null) {
throwAssertionError(contextFailedToStartWhenExpecting(
"to contain a bean of name:%n <%s> (%s)", name, type));
throwAssertionError(
contextFailedToStartWhenExpecting("to contain a bean of name:%n <%s> (%s)", name, type));
}
Object bean = findBean(name);
if (bean != null && type != null && !type.isInstance(bean)) {
@@ -370,8 +359,7 @@ public class ApplicationContextAssert<C extends ApplicationContext>
"%nExpecting:%n <%s>%nto contain a bean of name:%n <%s> (%s)%nbut found:%n <%s> of type <%s>",
getApplicationContext(), name, type, bean, bean.getClass()));
}
return Assertions.assertThat((T) bean).as(
"Bean of name <%s> and type <%s> from <%s>", name, type,
return Assertions.assertThat((T) bean).as("Bean of name <%s> and type <%s> from <%s>", name, type,
getApplicationContext());
}
@@ -420,8 +408,7 @@ public class ApplicationContextAssert<C extends ApplicationContext>
public <T> MapAssert<String, T> getBeans(Class<T> type, Scope scope) {
Assert.notNull(scope, "Scope must not be null");
if (this.startupFailure != null) {
throwAssertionError(contextFailedToStartWhenExpecting(
"to get beans of type:%n <%s>", type));
throwAssertionError(contextFailedToStartWhenExpecting("to get beans of type:%n <%s>", type));
}
return Assertions.assertThat(scope.getBeansOfType(getApplicationContext(), type))
.as("Beans of type <%s> from <%s>", type, getApplicationContext());
@@ -453,8 +440,7 @@ public class ApplicationContextAssert<C extends ApplicationContext>
public ApplicationContextAssert<C> hasFailed() {
if (this.startupFailure == null) {
throwAssertionError(new BasicErrorMessageFactory(
"%nExpecting:%n <%s>%nto have failed%nbut context started successfully",
getApplicationContext()));
"%nExpecting:%n <%s>%nto have failed%nbut context started successfully", getApplicationContext()));
}
return this;
}
@@ -482,10 +468,8 @@ public class ApplicationContextAssert<C extends ApplicationContext>
return this.startupFailure;
}
private ContextFailedToStart<C> contextFailedToStartWhenExpecting(
String expectationFormat, Object... arguments) {
return new ContextFailedToStart<>(getApplicationContext(), this.startupFailure,
expectationFormat, arguments);
private ContextFailedToStart<C> contextFailedToStartWhenExpecting(String expectationFormat, Object... arguments) {
return new ContextFailedToStart<>(getApplicationContext(), this.startupFailure, expectationFormat, arguments);
}
/**
@@ -499,14 +483,12 @@ public class ApplicationContextAssert<C extends ApplicationContext>
NO_ANCESTORS {
@Override
String[] getBeanNamesForType(ApplicationContext applicationContext,
Class<?> type) {
String[] getBeanNamesForType(ApplicationContext applicationContext, Class<?> type) {
return applicationContext.getBeanNamesForType(type);
}
@Override
<T> Map<String, T> getBeansOfType(ApplicationContext applicationContext,
Class<T> type) {
<T> Map<String, T> getBeansOfType(ApplicationContext applicationContext, Class<T> type) {
return applicationContext.getBeansOfType(type);
}
@@ -518,46 +500,35 @@ public class ApplicationContextAssert<C extends ApplicationContext>
INCLUDE_ANCESTORS {
@Override
String[] getBeanNamesForType(ApplicationContext applicationContext,
Class<?> type) {
return BeanFactoryUtils
.beanNamesForTypeIncludingAncestors(applicationContext, type);
String[] getBeanNamesForType(ApplicationContext applicationContext, Class<?> type) {
return BeanFactoryUtils.beanNamesForTypeIncludingAncestors(applicationContext, type);
}
@Override
<T> Map<String, T> getBeansOfType(ApplicationContext applicationContext,
Class<T> type) {
return BeanFactoryUtils.beansOfTypeIncludingAncestors(applicationContext,
type);
<T> Map<String, T> getBeansOfType(ApplicationContext applicationContext, Class<T> type) {
return BeanFactoryUtils.beansOfTypeIncludingAncestors(applicationContext, type);
}
};
abstract String[] getBeanNamesForType(ApplicationContext applicationContext,
Class<?> type);
abstract String[] getBeanNamesForType(ApplicationContext applicationContext, Class<?> type);
abstract <T> Map<String, T> getBeansOfType(ApplicationContext applicationContext,
Class<T> type);
abstract <T> Map<String, T> getBeansOfType(ApplicationContext applicationContext, Class<T> type);
}
private static final class ContextFailedToStart<C extends ApplicationContext>
extends BasicErrorMessageFactory {
private static final class ContextFailedToStart<C extends ApplicationContext> extends BasicErrorMessageFactory {
private ContextFailedToStart(C context, Throwable ex, String expectationFormat,
Object... arguments) {
super("%nExpecting:%n <%s>%n" + expectationFormat
+ ":%nbut context failed to start:%n%s",
private ContextFailedToStart(C context, Throwable ex, String expectationFormat, Object... arguments) {
super("%nExpecting:%n <%s>%n" + expectationFormat + ":%nbut context failed to start:%n%s",
combineArguments(context.toString(), ex, arguments));
}
private static Object[] combineArguments(String context, Throwable ex,
Object[] arguments) {
private static Object[] combineArguments(String context, Throwable ex, Object[] arguments) {
Object[] combinedArguments = new Object[arguments.length + 2];
combinedArguments[0] = unquotedString(context);
System.arraycopy(arguments, 0, combinedArguments, 1, arguments.length);
combinedArguments[combinedArguments.length - 1] = unquotedString(
getIndentedStackTraceAsString(ex));
combinedArguments[combinedArguments.length - 1] = unquotedString(getIndentedStackTraceAsString(ex));
return combinedArguments;
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -48,8 +48,8 @@ import org.springframework.util.Assert;
* @see AssertableReactiveWebApplicationContext
* @see ApplicationContextAssert
*/
public interface ApplicationContextAssertProvider<C extends ApplicationContext> extends
ApplicationContext, AssertProvider<ApplicationContextAssert<C>>, Closeable {
public interface ApplicationContextAssertProvider<C extends ApplicationContext>
extends ApplicationContext, AssertProvider<ApplicationContextAssert<C>>, Closeable {
/**
* Return an assert for AspectJ.
@@ -100,17 +100,15 @@ public interface ApplicationContextAssertProvider<C extends ApplicationContext>
* @return a {@link ApplicationContextAssertProvider} instance
*/
@SuppressWarnings("unchecked")
static <T extends ApplicationContextAssertProvider<C>, C extends ApplicationContext> T get(
Class<T> type, Class<? extends C> contextType,
Supplier<? extends C> contextSupplier) {
static <T extends ApplicationContextAssertProvider<C>, C extends ApplicationContext> T get(Class<T> type,
Class<? extends C> contextType, Supplier<? extends C> contextSupplier) {
Assert.notNull(type, "Type must not be null");
Assert.isTrue(type.isInterface(), "Type must be an interface");
Assert.notNull(contextType, "ContextType must not be null");
Assert.isTrue(contextType.isInterface(), "ContextType must be an interface");
Class<?>[] interfaces = { type, contextType };
return (T) Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(),
interfaces, new AssertProviderApplicationContextInvocationHandler(
contextType, contextSupplier));
return (T) Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), interfaces,
new AssertProviderApplicationContextInvocationHandler(contextType, contextSupplier));
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2017 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -43,8 +43,7 @@ class AssertProviderApplicationContextInvocationHandler implements InvocationHan
private final RuntimeException startupFailure;
AssertProviderApplicationContextInvocationHandler(Class<?> applicationContextType,
Supplier<?> contextSupplier) {
AssertProviderApplicationContextInvocationHandler(Class<?> applicationContextType, Supplier<?> contextSupplier) {
this.applicationContextType = applicationContextType;
Object contextOrStartupFailure = getContextOrStartupFailure(contextSupplier);
if (contextOrStartupFailure instanceof RuntimeException) {
@@ -93,22 +92,19 @@ class AssertProviderApplicationContextInvocationHandler implements InvocationHan
@Override
public String toString() {
if (this.startupFailure != null) {
return "Unstarted application context "
+ this.applicationContextType.getName() + "[startupFailure="
return "Unstarted application context " + this.applicationContextType.getName() + "[startupFailure="
+ this.startupFailure.getClass().getName() + "]";
}
ToStringCreator builder = new ToStringCreator(this.applicationContext)
.append("id", this.applicationContext.getId())
.append("applicationName", this.applicationContext.getApplicationName())
.append("beanDefinitionCount",
this.applicationContext.getBeanDefinitionCount());
.append("beanDefinitionCount", this.applicationContext.getBeanDefinitionCount());
return "Started application " + builder;
}
private boolean isGetSourceContext(Method method) {
return "getSourceApplicationContext".equals(method.getName())
&& ((method.getParameterCount() == 0) || Arrays.equals(
new Class<?>[] { Class.class }, method.getParameterTypes()));
return "getSourceApplicationContext".equals(method.getName()) && ((method.getParameterCount() == 0)
|| Arrays.equals(new Class<?>[] { Class.class }, method.getParameterTypes()));
}
private Object getSourceContext(Object[] args) {
@@ -120,8 +116,7 @@ class AssertProviderApplicationContextInvocationHandler implements InvocationHan
}
private boolean isGetStartupFailure(Method method) {
return ("getStartupFailure".equals(method.getName())
&& method.getParameterCount() == 0);
return ("getStartupFailure".equals(method.getName()) && method.getParameterCount() == 0);
}
private Object getStartupFailure() {
@@ -133,8 +128,7 @@ class AssertProviderApplicationContextInvocationHandler implements InvocationHan
}
private Object getAssertThat(Object proxy) {
return new ApplicationContextAssert<>((ApplicationContext) proxy,
this.startupFailure);
return new ApplicationContextAssert<>((ApplicationContext) proxy, this.startupFailure);
}
private boolean isCloseMethod(Method method) {
@@ -148,8 +142,7 @@ class AssertProviderApplicationContextInvocationHandler implements InvocationHan
return null;
}
private Object invokeApplicationContextMethod(Method method, Object[] args)
throws Throwable {
private Object invokeApplicationContextMethod(Method method, Object[] args) throws Throwable {
try {
return method.invoke(getStartedApplicationContext(), args);
}
@@ -160,8 +153,7 @@ class AssertProviderApplicationContextInvocationHandler implements InvocationHan
private ApplicationContext getStartedApplicationContext() {
if (this.startupFailure != null) {
throw new IllegalStateException(toString() + " failed to start",
this.startupFailure);
throw new IllegalStateException(toString() + " failed to start", this.startupFailure);
}
return this.applicationContext;
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -35,8 +35,7 @@ import org.springframework.context.ConfigurableApplicationContext;
* @see ApplicationContext
*/
public interface AssertableApplicationContext
extends ApplicationContextAssertProvider<ConfigurableApplicationContext>,
ConfigurableApplicationContext {
extends ApplicationContextAssertProvider<ConfigurableApplicationContext>, ConfigurableApplicationContext {
/**
* Factory method to create a new {@link AssertableApplicationContext} instance.
@@ -45,8 +44,7 @@ public interface AssertableApplicationContext
* to start.
* @return an {@link AssertableApplicationContext} instance
*/
static AssertableApplicationContext get(
Supplier<? extends ConfigurableApplicationContext> contextSupplier) {
static AssertableApplicationContext get(Supplier<? extends ConfigurableApplicationContext> contextSupplier) {
return ApplicationContextAssertProvider.get(AssertableApplicationContext.class,
ConfigurableApplicationContext.class, contextSupplier);
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -33,8 +33,8 @@ import org.springframework.boot.web.reactive.context.ReactiveWebApplicationConte
* @see ReactiveWebApplicationContext
* @see ReactiveWebApplicationContext
*/
public interface AssertableReactiveWebApplicationContext extends
ApplicationContextAssertProvider<ConfigurableReactiveWebApplicationContext>,
public interface AssertableReactiveWebApplicationContext
extends ApplicationContextAssertProvider<ConfigurableReactiveWebApplicationContext>,
ConfigurableReactiveWebApplicationContext {
/**
@@ -47,8 +47,7 @@ public interface AssertableReactiveWebApplicationContext extends
*/
static AssertableReactiveWebApplicationContext get(
Supplier<? extends ConfigurableReactiveWebApplicationContext> contextSupplier) {
return ApplicationContextAssertProvider.get(
AssertableReactiveWebApplicationContext.class,
return ApplicationContextAssertProvider.get(AssertableReactiveWebApplicationContext.class,
ConfigurableReactiveWebApplicationContext.class, contextSupplier);
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -35,8 +35,7 @@ import org.springframework.web.context.WebApplicationContext;
* @see WebApplicationContext
*/
public interface AssertableWebApplicationContext
extends ApplicationContextAssertProvider<ConfigurableWebApplicationContext>,
ConfigurableWebApplicationContext {
extends ApplicationContextAssertProvider<ConfigurableWebApplicationContext>, ConfigurableWebApplicationContext {
/**
* Factory method to create a new {@link AssertableWebApplicationContext} instance.
@@ -45,8 +44,7 @@ public interface AssertableWebApplicationContext
* fails to start.
* @return a {@link AssertableWebApplicationContext} instance
*/
static AssertableWebApplicationContext get(
Supplier<? extends ConfigurableWebApplicationContext> contextSupplier) {
static AssertableWebApplicationContext get(Supplier<? extends ConfigurableWebApplicationContext> contextSupplier) {
return ApplicationContextAssertProvider.get(AssertableWebApplicationContext.class,
ConfigurableWebApplicationContext.class, contextSupplier);
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -32,8 +32,7 @@ class ExcludeFilterContextCustomizer implements ContextCustomizer {
@Override
public void customizeContext(ConfigurableApplicationContext context,
MergedContextConfiguration mergedContextConfiguration) {
context.getBeanFactory().registerSingleton(TestTypeExcludeFilter.class.getName(),
new TestTypeExcludeFilter());
context.getBeanFactory().registerSingleton(TestTypeExcludeFilter.class.getName(), new TestTypeExcludeFilter());
}
@Override

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -39,8 +39,8 @@ class TestTypeExcludeFilter extends TypeExcludeFilter {
"org.junit.platform.commons.annotation.Testable" };
@Override
public boolean match(MetadataReader metadataReader,
MetadataReaderFactory metadataReaderFactory) throws IOException {
public boolean match(MetadataReader metadataReader, MetadataReaderFactory metadataReaderFactory)
throws IOException {
if (isTestConfiguration(metadataReader)) {
return true;
}
@@ -50,8 +50,7 @@ class TestTypeExcludeFilter extends TypeExcludeFilter {
String enclosing = metadataReader.getClassMetadata().getEnclosingClassName();
if (enclosing != null) {
try {
if (match(metadataReaderFactory.getMetadataReader(enclosing),
metadataReaderFactory)) {
if (match(metadataReaderFactory.getMetadataReader(enclosing), metadataReaderFactory)) {
return true;
}
}
@@ -63,8 +62,7 @@ class TestTypeExcludeFilter extends TypeExcludeFilter {
}
private boolean isTestConfiguration(MetadataReader metadataReader) {
return (metadataReader.getAnnotationMetadata()
.isAnnotated(TestComponent.class.getName()));
return (metadataReader.getAnnotationMetadata().isAnnotated(TestComponent.class.getName()));
}
private boolean isTestClass(MetadataReader metadataReader) {

View File

@@ -117,8 +117,8 @@ public abstract class AbstractApplicationContextRunner<SELF extends AbstractAppl
* @param contextFactory the factory used to create the actual context
*/
protected AbstractApplicationContextRunner(Supplier<C> contextFactory) {
this(contextFactory, Collections.emptyList(), TestPropertyValues.empty(),
TestPropertyValues.empty(), null, null, Collections.emptyList());
this(contextFactory, Collections.emptyList(), TestPropertyValues.empty(), TestPropertyValues.empty(), null,
null, Collections.emptyList());
}
/**
@@ -132,9 +132,8 @@ public abstract class AbstractApplicationContextRunner<SELF extends AbstractAppl
* @param configurations the configuration
*/
protected AbstractApplicationContextRunner(Supplier<C> contextFactory,
List<ApplicationContextInitializer<? super C>> initializers,
TestPropertyValues environmentProperties, TestPropertyValues systemProperties,
ClassLoader classLoader, ApplicationContext parent,
List<ApplicationContextInitializer<? super C>> initializers, TestPropertyValues environmentProperties,
TestPropertyValues systemProperties, ClassLoader classLoader, ApplicationContext parent,
List<Configurations> configurations) {
Assert.notNull(contextFactory, "ContextFactory must not be null");
Assert.notNull(environmentProperties, "EnvironmentProperties must not be null");
@@ -156,12 +155,10 @@ public abstract class AbstractApplicationContextRunner<SELF extends AbstractAppl
* @param initializer the initializer to add
* @return a new instance with the updated initializers
*/
public SELF withInitializer(
ApplicationContextInitializer<? super ConfigurableApplicationContext> initializer) {
public SELF withInitializer(ApplicationContextInitializer<? super ConfigurableApplicationContext> initializer) {
Assert.notNull(initializer, "Initializer must not be null");
return newInstance(this.contextFactory, add(this.initializers, initializer),
this.environmentProperties, this.systemProperties, this.classLoader,
this.parent, this.configurations);
return newInstance(this.contextFactory, add(this.initializers, initializer), this.environmentProperties,
this.systemProperties, this.classLoader, this.parent, this.configurations);
}
/**
@@ -175,9 +172,8 @@ public abstract class AbstractApplicationContextRunner<SELF extends AbstractAppl
* @see #withSystemProperties(String...)
*/
public SELF withPropertyValues(String... pairs) {
return newInstance(this.contextFactory, this.initializers,
this.environmentProperties.and(pairs), this.systemProperties,
this.classLoader, this.parent, this.configurations);
return newInstance(this.contextFactory, this.initializers, this.environmentProperties.and(pairs),
this.systemProperties, this.classLoader, this.parent, this.configurations);
}
/**
@@ -191,9 +187,8 @@ public abstract class AbstractApplicationContextRunner<SELF extends AbstractAppl
* @see #withSystemProperties(String...)
*/
public SELF withSystemProperties(String... pairs) {
return newInstance(this.contextFactory, this.initializers,
this.environmentProperties, this.systemProperties.and(pairs),
this.classLoader, this.parent, this.configurations);
return newInstance(this.contextFactory, this.initializers, this.environmentProperties,
this.systemProperties.and(pairs), this.classLoader, this.parent, this.configurations);
}
/**
@@ -204,9 +199,8 @@ public abstract class AbstractApplicationContextRunner<SELF extends AbstractAppl
* @see FilteredClassLoader
*/
public SELF withClassLoader(ClassLoader classLoader) {
return newInstance(this.contextFactory, this.initializers,
this.environmentProperties, this.systemProperties, classLoader,
this.parent, this.configurations);
return newInstance(this.contextFactory, this.initializers, this.environmentProperties, this.systemProperties,
classLoader, this.parent, this.configurations);
}
/**
@@ -216,9 +210,8 @@ public abstract class AbstractApplicationContextRunner<SELF extends AbstractAppl
* @return a new instance with the updated parent
*/
public SELF withParent(ApplicationContext parent) {
return newInstance(this.contextFactory, this.initializers,
this.environmentProperties, this.systemProperties, this.classLoader,
parent, this.configurations);
return newInstance(this.contextFactory, this.initializers, this.environmentProperties, this.systemProperties,
this.classLoader, parent, this.configurations);
}
/**
@@ -238,9 +231,8 @@ public abstract class AbstractApplicationContextRunner<SELF extends AbstractAppl
*/
public SELF withConfiguration(Configurations configurations) {
Assert.notNull(configurations, "Configurations must not be null");
return newInstance(this.contextFactory, this.initializers,
this.environmentProperties, this.systemProperties, this.classLoader,
this.parent, add(this.configurations, configurations));
return newInstance(this.contextFactory, this.initializers, this.environmentProperties, this.systemProperties,
this.classLoader, this.parent, add(this.configurations, configurations));
}
/**
@@ -260,9 +252,8 @@ public abstract class AbstractApplicationContextRunner<SELF extends AbstractAppl
}
protected abstract SELF newInstance(Supplier<C> contextFactory,
List<ApplicationContextInitializer<? super C>> initializers,
TestPropertyValues environmentProperties, TestPropertyValues systemProperties,
ClassLoader classLoader, ApplicationContext parent,
List<ApplicationContextInitializer<? super C>> initializers, TestPropertyValues environmentProperties,
TestPropertyValues systemProperties, ClassLoader classLoader, ApplicationContext parent,
List<Configurations> configurations);
/**
@@ -304,12 +295,10 @@ public abstract class AbstractApplicationContextRunner<SELF extends AbstractAppl
@SuppressWarnings("unchecked")
private A createAssertableContext() {
ResolvableType resolvableType = ResolvableType
.forClass(AbstractApplicationContextRunner.class, getClass());
ResolvableType resolvableType = ResolvableType.forClass(AbstractApplicationContextRunner.class, getClass());
Class<A> assertType = (Class<A>) resolvableType.resolveGeneric(1);
Class<C> contextType = (Class<C>) resolvableType.resolveGeneric(2);
return ApplicationContextAssertProvider.get(assertType, contextType,
this::createAndLoadContext);
return ApplicationContextAssertProvider.get(assertType, contextType, this::createAndLoadContext);
}
private C createAndLoadContext() {

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -54,31 +54,25 @@ public class ApplicationContextRunner extends
* {@code contextFactory} as the underlying source.
* @param contextFactory a supplier that returns a new instance on each call
*/
public ApplicationContextRunner(
Supplier<ConfigurableApplicationContext> contextFactory) {
public ApplicationContextRunner(Supplier<ConfigurableApplicationContext> contextFactory) {
super(contextFactory);
}
private ApplicationContextRunner(
Supplier<ConfigurableApplicationContext> contextFactory,
private ApplicationContextRunner(Supplier<ConfigurableApplicationContext> contextFactory,
List<ApplicationContextInitializer<? super ConfigurableApplicationContext>> initializers,
TestPropertyValues environmentProperties, TestPropertyValues systemProperties,
ClassLoader classLoader, ApplicationContext parent,
List<Configurations> configurations) {
super(contextFactory, initializers, environmentProperties, systemProperties,
classLoader, parent, configurations);
}
@Override
protected ApplicationContextRunner newInstance(
Supplier<ConfigurableApplicationContext> contextFactory,
List<ApplicationContextInitializer<? super ConfigurableApplicationContext>> initializers,
TestPropertyValues environmentProperties, TestPropertyValues systemProperties,
ClassLoader classLoader, ApplicationContext parent,
List<Configurations> configurations) {
return new ApplicationContextRunner(contextFactory, initializers,
environmentProperties, systemProperties, classLoader, parent,
TestPropertyValues environmentProperties, TestPropertyValues systemProperties, ClassLoader classLoader,
ApplicationContext parent, List<Configurations> configurations) {
super(contextFactory, initializers, environmentProperties, systemProperties, classLoader, parent,
configurations);
}
@Override
protected ApplicationContextRunner newInstance(Supplier<ConfigurableApplicationContext> contextFactory,
List<ApplicationContextInitializer<? super ConfigurableApplicationContext>> initializers,
TestPropertyValues environmentProperties, TestPropertyValues systemProperties, ClassLoader classLoader,
ApplicationContext parent, List<Configurations> configurations) {
return new ApplicationContextRunner(contextFactory, initializers, environmentProperties, systemProperties,
classLoader, parent, configurations);
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -54,31 +54,26 @@ public final class ReactiveWebApplicationContextRunner extends
* {@code contextFactory} as the underlying source.
* @param contextFactory a supplier that returns a new instance on each call
*/
public ReactiveWebApplicationContextRunner(
Supplier<ConfigurableReactiveWebApplicationContext> contextFactory) {
public ReactiveWebApplicationContextRunner(Supplier<ConfigurableReactiveWebApplicationContext> contextFactory) {
super(contextFactory);
}
private ReactiveWebApplicationContextRunner(
Supplier<ConfigurableReactiveWebApplicationContext> contextFactory,
private ReactiveWebApplicationContextRunner(Supplier<ConfigurableReactiveWebApplicationContext> contextFactory,
List<ApplicationContextInitializer<? super ConfigurableReactiveWebApplicationContext>> initializers,
TestPropertyValues environmentProperties, TestPropertyValues systemProperties,
ClassLoader classLoader, ApplicationContext parent,
List<Configurations> configurations) {
super(contextFactory, initializers, environmentProperties, systemProperties,
classLoader, parent, configurations);
TestPropertyValues environmentProperties, TestPropertyValues systemProperties, ClassLoader classLoader,
ApplicationContext parent, List<Configurations> configurations) {
super(contextFactory, initializers, environmentProperties, systemProperties, classLoader, parent,
configurations);
}
@Override
protected ReactiveWebApplicationContextRunner newInstance(
Supplier<ConfigurableReactiveWebApplicationContext> contextFactory,
List<ApplicationContextInitializer<? super ConfigurableReactiveWebApplicationContext>> initializers,
TestPropertyValues environmentProperties, TestPropertyValues systemProperties,
ClassLoader classLoader, ApplicationContext parent,
List<Configurations> configurations) {
return new ReactiveWebApplicationContextRunner(contextFactory, initializers,
environmentProperties, systemProperties, classLoader, parent,
configurations);
TestPropertyValues environmentProperties, TestPropertyValues systemProperties, ClassLoader classLoader,
ApplicationContext parent, List<Configurations> configurations) {
return new ReactiveWebApplicationContextRunner(contextFactory, initializers, environmentProperties,
systemProperties, classLoader, parent, configurations);
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -58,31 +58,25 @@ public final class WebApplicationContextRunner extends
* {@code contextFactory} as the underlying source.
* @param contextFactory a supplier that returns a new instance on each call
*/
public WebApplicationContextRunner(
Supplier<ConfigurableWebApplicationContext> contextFactory) {
public WebApplicationContextRunner(Supplier<ConfigurableWebApplicationContext> contextFactory) {
super(contextFactory);
}
private WebApplicationContextRunner(
Supplier<ConfigurableWebApplicationContext> contextFactory,
private WebApplicationContextRunner(Supplier<ConfigurableWebApplicationContext> contextFactory,
List<ApplicationContextInitializer<? super ConfigurableWebApplicationContext>> initializers,
TestPropertyValues environmentProperties, TestPropertyValues systemProperties,
ClassLoader classLoader, ApplicationContext parent,
List<Configurations> configurations) {
super(contextFactory, initializers, environmentProperties, systemProperties,
classLoader, parent, configurations);
TestPropertyValues environmentProperties, TestPropertyValues systemProperties, ClassLoader classLoader,
ApplicationContext parent, List<Configurations> configurations) {
super(contextFactory, initializers, environmentProperties, systemProperties, classLoader, parent,
configurations);
}
@Override
protected WebApplicationContextRunner newInstance(
Supplier<ConfigurableWebApplicationContext> contextFactory,
protected WebApplicationContextRunner newInstance(Supplier<ConfigurableWebApplicationContext> contextFactory,
List<ApplicationContextInitializer<? super ConfigurableWebApplicationContext>> initializers,
TestPropertyValues environmentProperties, TestPropertyValues systemProperties,
ClassLoader classLoader, ApplicationContext parent,
List<Configurations> configurations) {
return new WebApplicationContextRunner(contextFactory, initializers,
environmentProperties, systemProperties, classLoader, parent,
configurations);
TestPropertyValues environmentProperties, TestPropertyValues systemProperties, ClassLoader classLoader,
ApplicationContext parent, List<Configurations> configurations) {
return new WebApplicationContextRunner(contextFactory, initializers, environmentProperties, systemProperties,
classLoader, parent, configurations);
}
/**

View File

@@ -320,8 +320,7 @@ public abstract class AbstractJsonMarshalTester<T> {
}
private void verify() {
Assert.state(this.resourceLoadClass != null,
"Uninitialized JsonMarshalTester (ResourceLoadClass is null)");
Assert.state(this.resourceLoadClass != null, "Uninitialized JsonMarshalTester (ResourceLoadClass is null)");
Assert.state(this.type != null, "Uninitialized JsonMarshalTester (Type is null)");
}
@@ -332,8 +331,7 @@ public abstract class AbstractJsonMarshalTester<T> {
* @return the JSON string
* @throws IOException on write error
*/
protected abstract String writeObject(T value, ResolvableType type)
throws IOException;
protected abstract String writeObject(T value, ResolvableType type) throws IOException;
/**
* Read from the specified input stream to create an object of the specified type. The
@@ -343,8 +341,7 @@ public abstract class AbstractJsonMarshalTester<T> {
* @return the resulting object
* @throws IOException on read error
*/
protected T readObject(InputStream inputStream, ResolvableType type)
throws IOException {
protected T readObject(InputStream inputStream, ResolvableType type) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
return readObject(reader, type);
}
@@ -356,8 +353,7 @@ public abstract class AbstractJsonMarshalTester<T> {
* @return the resulting object
* @throws IOException on read error
*/
protected abstract T readObject(Reader reader, ResolvableType type)
throws IOException;
protected abstract T readObject(Reader reader, ResolvableType type) throws IOException;
/**
* Utility class used to support field initialization. Used by subclasses to support
@@ -370,8 +366,7 @@ public abstract class AbstractJsonMarshalTester<T> {
private final Class<?> testerClass;
@SuppressWarnings("rawtypes")
protected FieldInitializer(
Class<? extends AbstractJsonMarshalTester> testerClass) {
protected FieldInitializer(Class<? extends AbstractJsonMarshalTester> testerClass) {
Assert.notNull(testerClass, "TesterClass must not be null");
this.testerClass = testerClass;
}
@@ -389,8 +384,7 @@ public abstract class AbstractJsonMarshalTester<T> {
(field) -> doWithField(field, testInstance, marshaller));
}
protected void doWithField(Field field, Object test,
ObjectFactory<M> marshaller) {
protected void doWithField(Field field, Object test, ObjectFactory<M> marshaller) {
if (this.testerClass.isAssignableFrom(field.getType())) {
ReflectionUtils.makeAccessible(field);
Object existingValue = ReflectionUtils.getField(field, test);
@@ -402,12 +396,11 @@ public abstract class AbstractJsonMarshalTester<T> {
private void setupField(Field field, Object test, ObjectFactory<M> marshaller) {
ResolvableType type = ResolvableType.forField(field).getGeneric();
ReflectionUtils.setField(field, test,
createTester(test.getClass(), type, marshaller.getObject()));
ReflectionUtils.setField(field, test, createTester(test.getClass(), type, marshaller.getObject()));
}
protected abstract AbstractJsonMarshalTester<Object> createTester(
Class<?> resourceLoadClass, ResolvableType type, M marshaller);
protected abstract AbstractJsonMarshalTester<Object> createTester(Class<?> resourceLoadClass,
ResolvableType type, M marshaller);
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -44,15 +44,12 @@ class DuplicateJsonObjectContextCustomizerFactory implements ContextCustomizerFa
return new DuplicateJsonObjectContextCustomizer();
}
private static class DuplicateJsonObjectContextCustomizer
implements ContextCustomizer {
private static class DuplicateJsonObjectContextCustomizer implements ContextCustomizer {
private final Log logger = LogFactory
.getLog(DuplicateJsonObjectContextCustomizer.class);
private final Log logger = LogFactory.getLog(DuplicateJsonObjectContextCustomizer.class);
@Override
public void customizeContext(ConfigurableApplicationContext context,
MergedContextConfiguration mergedConfig) {
public void customizeContext(ConfigurableApplicationContext context, MergedContextConfiguration mergedConfig) {
List<URL> jsonObjects = findJsonObjects();
if (jsonObjects.size() > 1) {
logDuplicateJsonObjectsWarning(jsonObjects);
@@ -62,8 +59,7 @@ class DuplicateJsonObjectContextCustomizerFactory implements ContextCustomizerFa
private List<URL> findJsonObjects() {
List<URL> jsonObjects = new ArrayList<>();
try {
Enumeration<URL> resources = getClass().getClassLoader()
.getResources("org/json/JSONObject.class");
Enumeration<URL> resources = getClass().getClassLoader().getResources("org/json/JSONObject.class");
while (resources.hasMoreElements()) {
jsonObjects.add(resources.nextElement());
}
@@ -76,13 +72,12 @@ class DuplicateJsonObjectContextCustomizerFactory implements ContextCustomizerFa
private void logDuplicateJsonObjectsWarning(List<URL> jsonObjects) {
StringBuilder message = new StringBuilder(
String.format("%n%nFound multiple occurrences of"
+ " org.json.JSONObject on the class path:%n%n"));
String.format("%n%nFound multiple occurrences of" + " org.json.JSONObject on the class path:%n%n"));
for (URL jsonObject : jsonObjects) {
message.append(String.format("\t%s%n", jsonObject));
}
message.append(String.format("%nYou may wish to exclude one of them to ensure"
+ " predictable runtime behavior%n"));
message.append(String
.format("%nYou may wish to exclude one of them to ensure" + " predictable runtime behavior%n"));
this.logger.warn(message);
}

View File

@@ -119,8 +119,8 @@ public class GsonTester<T> extends AbstractJsonMarshalTester<T> {
}
@Override
protected AbstractJsonMarshalTester<Object> createTester(
Class<?> resourceLoadClass, ResolvableType type, Gson marshaller) {
protected AbstractJsonMarshalTester<Object> createTester(Class<?> resourceLoadClass, ResolvableType type,
Gson marshaller) {
return new GsonTester<>(resourceLoadClass, type, marshaller);
}

View File

@@ -83,13 +83,11 @@ public class JacksonTester<T> extends AbstractJsonMarshalTester<T> {
* @param type the type under test
* @param objectMapper the Jackson object mapper
*/
public JacksonTester(Class<?> resourceLoadClass, ResolvableType type,
ObjectMapper objectMapper) {
public JacksonTester(Class<?> resourceLoadClass, ResolvableType type, ObjectMapper objectMapper) {
this(resourceLoadClass, type, objectMapper, null);
}
public JacksonTester(Class<?> resourceLoadClass, ResolvableType type,
ObjectMapper objectMapper, Class<?> view) {
public JacksonTester(Class<?> resourceLoadClass, ResolvableType type, ObjectMapper objectMapper, Class<?> view) {
super(resourceLoadClass, type);
Assert.notNull(objectMapper, "ObjectMapper must not be null");
this.objectMapper = objectMapper;
@@ -98,15 +96,13 @@ public class JacksonTester<T> extends AbstractJsonMarshalTester<T> {
@Override
protected JsonContent<T> getJsonContent(String json) {
Configuration configuration = Configuration.builder()
.jsonProvider(new JacksonJsonProvider(this.objectMapper))
Configuration configuration = Configuration.builder().jsonProvider(new JacksonJsonProvider(this.objectMapper))
.mappingProvider(new JacksonMappingProvider(this.objectMapper)).build();
return new JsonContent<>(getResourceLoadClass(), getType(), json, configuration);
}
@Override
protected T readObject(InputStream inputStream, ResolvableType type)
throws IOException {
protected T readObject(InputStream inputStream, ResolvableType type) throws IOException {
return getObjectReader(type).readValue(inputStream);
}
@@ -158,8 +154,7 @@ public class JacksonTester<T> extends AbstractJsonMarshalTester<T> {
* @param objectMapperFactory a factory to create the object mapper
* @see #initFields(Object, ObjectMapper)
*/
public static void initFields(Object testInstance,
ObjectFactory<ObjectMapper> objectMapperFactory) {
public static void initFields(Object testInstance, ObjectFactory<ObjectMapper> objectMapperFactory) {
new JacksonFieldInitializer().initFields(testInstance, objectMapperFactory);
}
@@ -170,8 +165,7 @@ public class JacksonTester<T> extends AbstractJsonMarshalTester<T> {
* @return the new instance
*/
public JacksonTester<T> forView(Class<?> view) {
return new JacksonTester<>(this.getResourceLoadClass(), this.getType(),
this.objectMapper, view);
return new JacksonTester<>(this.getResourceLoadClass(), this.getType(), this.objectMapper, view);
}
/**
@@ -184,8 +178,7 @@ public class JacksonTester<T> extends AbstractJsonMarshalTester<T> {
}
@Override
protected AbstractJsonMarshalTester<Object> createTester(
Class<?> resourceLoadClass, ResolvableType type,
protected AbstractJsonMarshalTester<Object> createTester(Class<?> resourceLoadClass, ResolvableType type,
ObjectMapper marshaller) {
return new JacksonTester<>(resourceLoadClass, type, marshaller);
}

View File

@@ -59,8 +59,7 @@ public final class JsonContent<T> implements AssertProvider<JsonContentAssert> {
* @param json the actual JSON content
* @param configuration the JsonPath configuration
*/
JsonContent(Class<?> resourceLoadClass, ResolvableType type, String json,
Configuration configuration) {
JsonContent(Class<?> resourceLoadClass, ResolvableType type, String json, Configuration configuration) {
Assert.notNull(resourceLoadClass, "ResourceLoadClass must not be null");
Assert.notNull(json, "JSON must not be null");
Assert.notNull(configuration, "Configuration must not be null");
@@ -79,8 +78,7 @@ public final class JsonContent<T> implements AssertProvider<JsonContentAssert> {
@Override
@Deprecated
public JsonContentAssert assertThat() {
return new JsonContentAssert(this.resourceLoadClass, null, this.json,
this.configuration);
return new JsonContentAssert(this.resourceLoadClass, null, this.json, this.configuration);
}
/**

View File

@@ -72,8 +72,7 @@ public class JsonContentAssert extends AbstractAssert<JsonContentAssert, CharSeq
* @param json the actual JSON content
* @since 1.4.1
*/
public JsonContentAssert(Class<?> resourceLoadClass, Charset charset,
CharSequence json) {
public JsonContentAssert(Class<?> resourceLoadClass, Charset charset, CharSequence json) {
this(resourceLoadClass, charset, json, Configuration.defaultConfiguration());
}
@@ -85,8 +84,7 @@ public class JsonContentAssert extends AbstractAssert<JsonContentAssert, CharSeq
* @param json the actual JSON content
* @param configuration the json-path configuration
*/
JsonContentAssert(Class<?> resourceLoadClass, Charset charset, CharSequence json,
Configuration configuration) {
JsonContentAssert(Class<?> resourceLoadClass, Charset charset, CharSequence json, Configuration configuration) {
super(json, JsonContentAssert.class);
this.configuration = configuration;
this.loader = new JsonLoader(resourceLoadClass, charset);
@@ -114,8 +112,7 @@ public class JsonContentAssert extends AbstractAssert<JsonContentAssert, CharSeq
if (expected instanceof Resource) {
return isEqualToJson((Resource) expected);
}
throw new AssertionError(
"Unsupported type for JSON assert " + expected.getClass());
throw new AssertionError("Unsupported type for JSON assert " + expected.getClass());
}
/**
@@ -217,8 +214,7 @@ public class JsonContentAssert extends AbstractAssert<JsonContentAssert, CharSeq
* @return {@code this} assertion object
* @throws AssertionError if the actual JSON value is not equal to the given one
*/
public JsonContentAssert isStrictlyEqualToJson(String path,
Class<?> resourceLoadClass) {
public JsonContentAssert isStrictlyEqualToJson(String path, Class<?> resourceLoadClass) {
String expectedJson = this.loader.getJson(path, resourceLoadClass);
return assertNotFailed(compare(expectedJson, JSONCompareMode.STRICT));
}
@@ -231,8 +227,7 @@ public class JsonContentAssert extends AbstractAssert<JsonContentAssert, CharSeq
* @throws AssertionError if the actual JSON value is not equal to the given one
*/
public JsonContentAssert isStrictlyEqualToJson(byte[] expected) {
return assertNotFailed(
compare(this.loader.getJson(expected), JSONCompareMode.STRICT));
return assertNotFailed(compare(this.loader.getJson(expected), JSONCompareMode.STRICT));
}
/**
@@ -281,8 +276,7 @@ public class JsonContentAssert extends AbstractAssert<JsonContentAssert, CharSeq
* @return {@code this} assertion object
* @throws AssertionError if the actual JSON value is not equal to the given one
*/
public JsonContentAssert isEqualToJson(CharSequence expected,
JSONCompareMode compareMode) {
public JsonContentAssert isEqualToJson(CharSequence expected, JSONCompareMode compareMode) {
String expectedJson = this.loader.getJson(expected);
return assertNotFailed(compare(expectedJson, compareMode));
}
@@ -295,8 +289,7 @@ public class JsonContentAssert extends AbstractAssert<JsonContentAssert, CharSeq
* @return {@code this} assertion object
* @throws AssertionError if the actual JSON value is not equal to the given one
*/
public JsonContentAssert isEqualToJson(String path, Class<?> resourceLoadClass,
JSONCompareMode compareMode) {
public JsonContentAssert isEqualToJson(String path, Class<?> resourceLoadClass, JSONCompareMode compareMode) {
String expectedJson = this.loader.getJson(path, resourceLoadClass);
return assertNotFailed(compare(expectedJson, compareMode));
}
@@ -332,8 +325,7 @@ public class JsonContentAssert extends AbstractAssert<JsonContentAssert, CharSeq
* @return {@code this} assertion object
* @throws AssertionError if the actual JSON value is not equal to the given one
*/
public JsonContentAssert isEqualToJson(InputStream expected,
JSONCompareMode compareMode) {
public JsonContentAssert isEqualToJson(InputStream expected, JSONCompareMode compareMode) {
return assertNotFailed(compare(this.loader.getJson(expected), compareMode));
}
@@ -344,8 +336,7 @@ public class JsonContentAssert extends AbstractAssert<JsonContentAssert, CharSeq
* @return {@code this} assertion object
* @throws AssertionError if the actual JSON value is not equal to the given one
*/
public JsonContentAssert isEqualToJson(Resource expected,
JSONCompareMode compareMode) {
public JsonContentAssert isEqualToJson(Resource expected, JSONCompareMode compareMode) {
String expectedJson = this.loader.getJson(expected);
return assertNotFailed(compare(expectedJson, compareMode));
}
@@ -360,8 +351,7 @@ public class JsonContentAssert extends AbstractAssert<JsonContentAssert, CharSeq
* @return {@code this} assertion object
* @throws AssertionError if the actual JSON value is not equal to the given one
*/
public JsonContentAssert isEqualToJson(CharSequence expected,
JSONComparator comparator) {
public JsonContentAssert isEqualToJson(CharSequence expected, JSONComparator comparator) {
String expectedJson = this.loader.getJson(expected);
return assertNotFailed(compare(expectedJson, comparator));
}
@@ -374,8 +364,7 @@ public class JsonContentAssert extends AbstractAssert<JsonContentAssert, CharSeq
* @return {@code this} assertion object
* @throws AssertionError if the actual JSON value is not equal to the given one
*/
public JsonContentAssert isEqualToJson(String path, Class<?> resourceLoadClass,
JSONComparator comparator) {
public JsonContentAssert isEqualToJson(String path, Class<?> resourceLoadClass, JSONComparator comparator) {
String expectedJson = this.loader.getJson(path, resourceLoadClass);
return assertNotFailed(compare(expectedJson, comparator));
}
@@ -411,8 +400,7 @@ public class JsonContentAssert extends AbstractAssert<JsonContentAssert, CharSeq
* @return {@code this} assertion object
* @throws AssertionError if the actual JSON value is not equal to the given one
*/
public JsonContentAssert isEqualToJson(InputStream expected,
JSONComparator comparator) {
public JsonContentAssert isEqualToJson(InputStream expected, JSONComparator comparator) {
String expectedJson = this.loader.getJson(expected);
return assertNotFailed(compare(expectedJson, comparator));
}
@@ -451,8 +439,7 @@ public class JsonContentAssert extends AbstractAssert<JsonContentAssert, CharSeq
if (expected instanceof Resource) {
return isNotEqualToJson((Resource) expected);
}
throw new AssertionError(
"Unsupported type for JSON assert " + expected.getClass());
throw new AssertionError("Unsupported type for JSON assert " + expected.getClass());
}
/**
@@ -527,8 +514,7 @@ public class JsonContentAssert extends AbstractAssert<JsonContentAssert, CharSeq
* @throws AssertionError if the actual JSON value is equal to the given one
*/
public JsonContentAssert isNotEqualToJson(Resource expected) {
return assertNotPassed(
compare(this.loader.getJson(expected), JSONCompareMode.LENIENT));
return assertNotPassed(compare(this.loader.getJson(expected), JSONCompareMode.LENIENT));
}
/**
@@ -554,8 +540,7 @@ public class JsonContentAssert extends AbstractAssert<JsonContentAssert, CharSeq
* @return {@code this} assertion object
* @throws AssertionError if the actual JSON value is equal to the given one
*/
public JsonContentAssert isNotStrictlyEqualToJson(String path,
Class<?> resourceLoadClass) {
public JsonContentAssert isNotStrictlyEqualToJson(String path, Class<?> resourceLoadClass) {
String expectedJson = this.loader.getJson(path, resourceLoadClass);
return assertNotPassed(compare(expectedJson, JSONCompareMode.STRICT));
}
@@ -618,8 +603,7 @@ public class JsonContentAssert extends AbstractAssert<JsonContentAssert, CharSeq
* @return {@code this} assertion object
* @throws AssertionError if the actual JSON value is equal to the given one
*/
public JsonContentAssert isNotEqualToJson(CharSequence expected,
JSONCompareMode compareMode) {
public JsonContentAssert isNotEqualToJson(CharSequence expected, JSONCompareMode compareMode) {
String expectedJson = this.loader.getJson(expected);
return assertNotPassed(compare(expectedJson, compareMode));
}
@@ -632,8 +616,7 @@ public class JsonContentAssert extends AbstractAssert<JsonContentAssert, CharSeq
* @return {@code this} assertion object
* @throws AssertionError if the actual JSON value is equal to the given one
*/
public JsonContentAssert isNotEqualToJson(String path, Class<?> resourceLoadClass,
JSONCompareMode compareMode) {
public JsonContentAssert isNotEqualToJson(String path, Class<?> resourceLoadClass, JSONCompareMode compareMode) {
String expectedJson = this.loader.getJson(path, resourceLoadClass);
return assertNotPassed(compare(expectedJson, compareMode));
}
@@ -645,8 +628,7 @@ public class JsonContentAssert extends AbstractAssert<JsonContentAssert, CharSeq
* @return {@code this} assertion object
* @throws AssertionError if the actual JSON value is equal to the given one
*/
public JsonContentAssert isNotEqualToJson(byte[] expected,
JSONCompareMode compareMode) {
public JsonContentAssert isNotEqualToJson(byte[] expected, JSONCompareMode compareMode) {
String expectedJson = this.loader.getJson(expected);
return assertNotPassed(compare(expectedJson, compareMode));
}
@@ -658,8 +640,7 @@ public class JsonContentAssert extends AbstractAssert<JsonContentAssert, CharSeq
* @return {@code this} assertion object
* @throws AssertionError if the actual JSON value is equal to the given one
*/
public JsonContentAssert isNotEqualToJson(File expected,
JSONCompareMode compareMode) {
public JsonContentAssert isNotEqualToJson(File expected, JSONCompareMode compareMode) {
String expectedJson = this.loader.getJson(expected);
return assertNotPassed(compare(expectedJson, compareMode));
}
@@ -671,8 +652,7 @@ public class JsonContentAssert extends AbstractAssert<JsonContentAssert, CharSeq
* @return {@code this} assertion object
* @throws AssertionError if the actual JSON value is equal to the given one
*/
public JsonContentAssert isNotEqualToJson(InputStream expected,
JSONCompareMode compareMode) {
public JsonContentAssert isNotEqualToJson(InputStream expected, JSONCompareMode compareMode) {
String expectedJson = this.loader.getJson(expected);
return assertNotPassed(compare(expectedJson, compareMode));
}
@@ -684,8 +664,7 @@ public class JsonContentAssert extends AbstractAssert<JsonContentAssert, CharSeq
* @return {@code this} assertion object
* @throws AssertionError if the actual JSON value is equal to the given one
*/
public JsonContentAssert isNotEqualToJson(Resource expected,
JSONCompareMode compareMode) {
public JsonContentAssert isNotEqualToJson(Resource expected, JSONCompareMode compareMode) {
String expectedJson = this.loader.getJson(expected);
return assertNotPassed(compare(expectedJson, compareMode));
}
@@ -700,8 +679,7 @@ public class JsonContentAssert extends AbstractAssert<JsonContentAssert, CharSeq
* @return {@code this} assertion object
* @throws AssertionError if the actual JSON value is equal to the given one
*/
public JsonContentAssert isNotEqualToJson(CharSequence expected,
JSONComparator comparator) {
public JsonContentAssert isNotEqualToJson(CharSequence expected, JSONComparator comparator) {
String expectedJson = this.loader.getJson(expected);
return assertNotPassed(compare(expectedJson, comparator));
}
@@ -714,8 +692,7 @@ public class JsonContentAssert extends AbstractAssert<JsonContentAssert, CharSeq
* @return {@code this} assertion object
* @throws AssertionError if the actual JSON value is equal to the given one
*/
public JsonContentAssert isNotEqualToJson(String path, Class<?> resourceLoadClass,
JSONComparator comparator) {
public JsonContentAssert isNotEqualToJson(String path, Class<?> resourceLoadClass, JSONComparator comparator) {
String expectedJson = this.loader.getJson(path, resourceLoadClass);
return assertNotPassed(compare(expectedJson, comparator));
}
@@ -727,8 +704,7 @@ public class JsonContentAssert extends AbstractAssert<JsonContentAssert, CharSeq
* @return {@code this} assertion object
* @throws AssertionError if the actual JSON value is equal to the given one
*/
public JsonContentAssert isNotEqualToJson(byte[] expected,
JSONComparator comparator) {
public JsonContentAssert isNotEqualToJson(byte[] expected, JSONComparator comparator) {
String expectedJson = this.loader.getJson(expected);
return assertNotPassed(compare(expectedJson, comparator));
}
@@ -752,8 +728,7 @@ public class JsonContentAssert extends AbstractAssert<JsonContentAssert, CharSeq
* @return {@code this} assertion object
* @throws AssertionError if the actual JSON value is equal to the given one
*/
public JsonContentAssert isNotEqualToJson(InputStream expected,
JSONComparator comparator) {
public JsonContentAssert isNotEqualToJson(InputStream expected, JSONComparator comparator) {
String expectedJson = this.loader.getJson(expected);
return assertNotPassed(compare(expectedJson, comparator));
}
@@ -765,8 +740,7 @@ public class JsonContentAssert extends AbstractAssert<JsonContentAssert, CharSeq
* @return {@code this} assertion object
* @throws AssertionError if the actual JSON value is equal to the given one
*/
public JsonContentAssert isNotEqualToJson(Resource expected,
JSONComparator comparator) {
public JsonContentAssert isNotEqualToJson(Resource expected, JSONComparator comparator) {
String expectedJson = this.loader.getJson(expected);
return assertNotPassed(compare(expectedJson, comparator));
}
@@ -795,8 +769,7 @@ public class JsonContentAssert extends AbstractAssert<JsonContentAssert, CharSeq
* @return {@code this} assertion object
* @throws AssertionError if the value at the given path is missing or not a string
*/
public JsonContentAssert hasJsonPathStringValue(CharSequence expression,
Object... args) {
public JsonContentAssert hasJsonPathStringValue(CharSequence expression, Object... args) {
new JsonPathValue(expression, args).assertHasValue(String.class, "a string");
return this;
}
@@ -810,8 +783,7 @@ public class JsonContentAssert extends AbstractAssert<JsonContentAssert, CharSeq
* @return {@code this} assertion object
* @throws AssertionError if the value at the given path is missing or not a number
*/
public JsonContentAssert hasJsonPathNumberValue(CharSequence expression,
Object... args) {
public JsonContentAssert hasJsonPathNumberValue(CharSequence expression, Object... args) {
new JsonPathValue(expression, args).assertHasValue(Number.class, "a number");
return this;
}
@@ -825,8 +797,7 @@ public class JsonContentAssert extends AbstractAssert<JsonContentAssert, CharSeq
* @return {@code this} assertion object
* @throws AssertionError if the value at the given path is missing or not a boolean
*/
public JsonContentAssert hasJsonPathBooleanValue(CharSequence expression,
Object... args) {
public JsonContentAssert hasJsonPathBooleanValue(CharSequence expression, Object... args) {
new JsonPathValue(expression, args).assertHasValue(Boolean.class, "a boolean");
return this;
}
@@ -840,8 +811,7 @@ public class JsonContentAssert extends AbstractAssert<JsonContentAssert, CharSeq
* @return {@code this} assertion object
* @throws AssertionError if the value at the given path is missing or not an array
*/
public JsonContentAssert hasJsonPathArrayValue(CharSequence expression,
Object... args) {
public JsonContentAssert hasJsonPathArrayValue(CharSequence expression, Object... args) {
new JsonPathValue(expression, args).assertHasValue(List.class, "an array");
return this;
}
@@ -854,8 +824,7 @@ public class JsonContentAssert extends AbstractAssert<JsonContentAssert, CharSeq
* @return {@code this} assertion object
* @throws AssertionError if the value at the given path is missing or not a map
*/
public JsonContentAssert hasJsonPathMapValue(CharSequence expression,
Object... args) {
public JsonContentAssert hasJsonPathMapValue(CharSequence expression, Object... args) {
new JsonPathValue(expression, args).assertHasValue(Map.class, "a map");
return this;
}
@@ -869,8 +838,7 @@ public class JsonContentAssert extends AbstractAssert<JsonContentAssert, CharSeq
* @return {@code this} assertion object
* @throws AssertionError if the value at the given path is not empty
*/
public JsonContentAssert hasEmptyJsonPathValue(CharSequence expression,
Object... args) {
public JsonContentAssert hasEmptyJsonPathValue(CharSequence expression, Object... args) {
new JsonPathValue(expression, args).assertHasEmptyValue();
return this;
}
@@ -885,8 +853,7 @@ public class JsonContentAssert extends AbstractAssert<JsonContentAssert, CharSeq
* @return {@code this} assertion object
* @throws AssertionError if the value at the given path is not missing
*/
public JsonContentAssert doesNotHaveJsonPathValue(CharSequence expression,
Object... args) {
public JsonContentAssert doesNotHaveJsonPathValue(CharSequence expression, Object... args) {
new JsonPathValue(expression, args).assertDoesNotHaveValue();
return this;
}
@@ -900,8 +867,7 @@ public class JsonContentAssert extends AbstractAssert<JsonContentAssert, CharSeq
* @return {@code this} assertion object
* @throws AssertionError if the value at the given path is empty
*/
public JsonContentAssert doesNotHaveEmptyJsonPathValue(CharSequence expression,
Object... args) {
public JsonContentAssert doesNotHaveEmptyJsonPathValue(CharSequence expression, Object... args) {
new JsonPathValue(expression, args).assertDoesNotHaveEmptyValue();
return this;
}
@@ -914,8 +880,7 @@ public class JsonContentAssert extends AbstractAssert<JsonContentAssert, CharSeq
* @return a new assertion object whose object under test is the extracted item
* @throws AssertionError if the path is not valid
*/
public AbstractObjectAssert<?, Object> extractingJsonPathValue(
CharSequence expression, Object... args) {
public AbstractObjectAssert<?, Object> extractingJsonPathValue(CharSequence expression, Object... args) {
return Assertions.assertThat(new JsonPathValue(expression, args).getValue(false));
}
@@ -927,10 +892,9 @@ public class JsonContentAssert extends AbstractAssert<JsonContentAssert, CharSeq
* @return a new assertion object whose object under test is the extracted item
* @throws AssertionError if the path is not valid or does not result in a string
*/
public AbstractCharSequenceAssert<?, String> extractingJsonPathStringValue(
CharSequence expression, Object... args) {
return Assertions.assertThat(
extractingJsonPathValue(expression, args, String.class, "a string"));
public AbstractCharSequenceAssert<?, String> extractingJsonPathStringValue(CharSequence expression,
Object... args) {
return Assertions.assertThat(extractingJsonPathValue(expression, args, String.class, "a string"));
}
/**
@@ -941,10 +905,8 @@ public class JsonContentAssert extends AbstractAssert<JsonContentAssert, CharSeq
* @return a new assertion object whose object under test is the extracted item
* @throws AssertionError if the path is not valid or does not result in a number
*/
public AbstractObjectAssert<?, Number> extractingJsonPathNumberValue(
CharSequence expression, Object... args) {
return Assertions.assertThat(
extractingJsonPathValue(expression, args, Number.class, "a number"));
public AbstractObjectAssert<?, Number> extractingJsonPathNumberValue(CharSequence expression, Object... args) {
return Assertions.assertThat(extractingJsonPathValue(expression, args, Number.class, "a number"));
}
/**
@@ -955,10 +917,8 @@ public class JsonContentAssert extends AbstractAssert<JsonContentAssert, CharSeq
* @return a new assertion object whose object under test is the extracted item
* @throws AssertionError if the path is not valid or does not result in a boolean
*/
public AbstractBooleanAssert<?> extractingJsonPathBooleanValue(
CharSequence expression, Object... args) {
return Assertions.assertThat(
extractingJsonPathValue(expression, args, Boolean.class, "a boolean"));
public AbstractBooleanAssert<?> extractingJsonPathBooleanValue(CharSequence expression, Object... args) {
return Assertions.assertThat(extractingJsonPathValue(expression, args, Boolean.class, "a boolean"));
}
/**
@@ -971,10 +931,8 @@ public class JsonContentAssert extends AbstractAssert<JsonContentAssert, CharSeq
* @throws AssertionError if the path is not valid or does not result in an array
*/
@SuppressWarnings("unchecked")
public <E> ListAssert<E> extractingJsonPathArrayValue(CharSequence expression,
Object... args) {
return Assertions.assertThat(
extractingJsonPathValue(expression, args, List.class, "an array"));
public <E> ListAssert<E> extractingJsonPathArrayValue(CharSequence expression, Object... args) {
return Assertions.assertThat(extractingJsonPathValue(expression, args, List.class, "an array"));
}
/**
@@ -988,15 +946,13 @@ public class JsonContentAssert extends AbstractAssert<JsonContentAssert, CharSeq
* @throws AssertionError if the path is not valid or does not result in a map
*/
@SuppressWarnings("unchecked")
public <K, V> MapAssert<K, V> extractingJsonPathMapValue(CharSequence expression,
Object... args) {
return Assertions.assertThat(
extractingJsonPathValue(expression, args, Map.class, "a map"));
public <K, V> MapAssert<K, V> extractingJsonPathMapValue(CharSequence expression, Object... args) {
return Assertions.assertThat(extractingJsonPathValue(expression, args, Map.class, "a map"));
}
@SuppressWarnings("unchecked")
private <T> T extractingJsonPathValue(CharSequence expression, Object[] args,
Class<T> type, String expectedDescription) {
private <T> T extractingJsonPathValue(CharSequence expression, Object[] args, Class<T> type,
String expectedDescription) {
JsonPathValue value = new JsonPathValue(expression, args);
if (value.getValue(false) != null) {
value.assertHasValue(type, expectedDescription);
@@ -1004,14 +960,12 @@ public class JsonContentAssert extends AbstractAssert<JsonContentAssert, CharSeq
return (T) value.getValue(false);
}
private JSONCompareResult compare(CharSequence expectedJson,
JSONCompareMode compareMode) {
private JSONCompareResult compare(CharSequence expectedJson, JSONCompareMode compareMode) {
if (this.actual == null) {
return compareForNull(expectedJson);
}
try {
return JSONCompare.compareJSON(
(expectedJson != null) ? expectedJson.toString() : null,
return JSONCompare.compareJSON((expectedJson != null) ? expectedJson.toString() : null,
this.actual.toString(), compareMode);
}
catch (Exception ex) {
@@ -1022,14 +976,12 @@ public class JsonContentAssert extends AbstractAssert<JsonContentAssert, CharSeq
}
}
private JSONCompareResult compare(CharSequence expectedJson,
JSONComparator comparator) {
private JSONCompareResult compare(CharSequence expectedJson, JSONComparator comparator) {
if (this.actual == null) {
return compareForNull(expectedJson);
}
try {
return JSONCompare.compareJSON(
(expectedJson != null) ? expectedJson.toString() : null,
return JSONCompare.compareJSON((expectedJson != null) ? expectedJson.toString() : null,
this.actual.toString(), comparator);
}
catch (Exception ex) {
@@ -1073,8 +1025,7 @@ public class JsonContentAssert extends AbstractAssert<JsonContentAssert, CharSeq
private final JsonPath jsonPath;
JsonPathValue(CharSequence expression, Object... args) {
org.springframework.util.Assert.hasText(
(expression != null) ? expression.toString() : null,
org.springframework.util.Assert.hasText((expression != null) ? expression.toString() : null,
"expression must not be null or empty");
this.expression = String.format(expression.toString(), args);
this.jsonPath = JsonPath.compile(this.expression);
@@ -1143,9 +1094,8 @@ public class JsonContentAssert extends AbstractAssert<JsonContentAssert, CharSeq
}
private String getExpectedValueMessage(String expectedDescription) {
return String.format("Expected %s at JSON path \"%s\" but found: %s",
expectedDescription, this.expression, ObjectUtils.nullSafeToString(
StringUtils.quoteIfString(getValue(false))));
return String.format("Expected %s at JSON path \"%s\" but found: %s", expectedDescription, this.expression,
ObjectUtils.nullSafeToString(StringUtils.quoteIfString(getValue(false))));
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -55,8 +55,7 @@ class JsonLoader {
return null;
}
if (source.toString().endsWith(".json")) {
return getJson(
new ClassPathResource(source.toString(), this.resourceLoadClass));
return getJson(new ClassPathResource(source.toString(), this.resourceLoadClass));
}
return source.toString();
}
@@ -89,8 +88,7 @@ class JsonLoader {
String getJson(InputStream source) {
try {
return FileCopyUtils
.copyToString(new InputStreamReader(source, this.charset));
return FileCopyUtils.copyToString(new InputStreamReader(source, this.charset));
}
catch (IOException ex) {
throw new IllegalStateException("Unable to load JSON from InputStream", ex);

View File

@@ -119,8 +119,8 @@ public class JsonbTester<T> extends AbstractJsonMarshalTester<T> {
}
@Override
protected AbstractJsonMarshalTester<Object> createTester(
Class<?> resourceLoadClass, ResolvableType type, Jsonb marshaller) {
protected AbstractJsonMarshalTester<Object> createTester(Class<?> resourceLoadClass, ResolvableType type,
Jsonb marshaller) {
return new JsonbTester<>(resourceLoadClass, type, marshaller);
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -32,8 +32,7 @@ import org.assertj.core.internal.Objects;
* @author Phillip Webb
* @since 1.4.0
*/
public class ObjectContentAssert<A>
extends AbstractObjectAssert<ObjectContentAssert<A>, A> {
public class ObjectContentAssert<A> extends AbstractObjectAssert<ObjectContentAssert<A>, A> {
protected ObjectContentAssert(A actual) {
super(actual, ObjectContentAssert.class);

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -36,8 +36,7 @@ abstract class Definition {
private final QualifierDefinition qualifier;
Definition(String name, MockReset reset, boolean proxyTargetAware,
QualifierDefinition qualifier) {
Definition(String name, MockReset reset, boolean proxyTargetAware, QualifierDefinition qualifier) {
this.name = name;
this.reset = (reset != null) ? reset : MockReset.AFTER;
this.proxyTargetAware = proxyTargetAware;
@@ -88,8 +87,7 @@ abstract class Definition {
boolean result = true;
result = result && ObjectUtils.nullSafeEquals(this.name, other.name);
result = result && ObjectUtils.nullSafeEquals(this.reset, other.reset);
result = result && ObjectUtils.nullSafeEquals(this.proxyTargetAware,
other.proxyTargetAware);
result = result && ObjectUtils.nullSafeEquals(this.proxyTargetAware, other.proxyTargetAware);
result = result && ObjectUtils.nullSafeEquals(this.qualifier, other.qualifier);
return result;
}
@@ -99,8 +97,7 @@ abstract class Definition {
int result = 1;
result = MULTIPLIER * result + ObjectUtils.nullSafeHashCode(this.name);
result = MULTIPLIER * result + ObjectUtils.nullSafeHashCode(this.reset);
result = MULTIPLIER * result
+ ObjectUtils.nullSafeHashCode(this.proxyTargetAware);
result = MULTIPLIER * result + ObjectUtils.nullSafeHashCode(this.proxyTargetAware);
result = MULTIPLIER * result + ObjectUtils.nullSafeHashCode(this.qualifier);
return result;
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2017 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -63,28 +63,23 @@ class DefinitionsParser {
}
private void parseElement(AnnotatedElement element) {
for (MockBean annotation : AnnotationUtils.getRepeatableAnnotations(element,
MockBean.class, MockBeans.class)) {
for (MockBean annotation : AnnotationUtils.getRepeatableAnnotations(element, MockBean.class, MockBeans.class)) {
parseMockBeanAnnotation(annotation, element);
}
for (SpyBean annotation : AnnotationUtils.getRepeatableAnnotations(element,
SpyBean.class, SpyBeans.class)) {
for (SpyBean annotation : AnnotationUtils.getRepeatableAnnotations(element, SpyBean.class, SpyBeans.class)) {
parseSpyBeanAnnotation(annotation, element);
}
}
private void parseMockBeanAnnotation(MockBean annotation, AnnotatedElement element) {
Set<ResolvableType> typesToMock = getOrDeduceTypes(element, annotation.value());
Assert.state(!typesToMock.isEmpty(),
() -> "Unable to deduce type to mock from " + element);
Assert.state(!typesToMock.isEmpty(), () -> "Unable to deduce type to mock from " + element);
if (StringUtils.hasLength(annotation.name())) {
Assert.state(typesToMock.size() == 1,
"The name attribute can only be used when mocking a single class");
Assert.state(typesToMock.size() == 1, "The name attribute can only be used when mocking a single class");
}
for (ResolvableType typeToMock : typesToMock) {
MockDefinition definition = new MockDefinition(annotation.name(), typeToMock,
annotation.extraInterfaces(), annotation.answer(),
annotation.serializable(), annotation.reset(),
MockDefinition definition = new MockDefinition(annotation.name(), typeToMock, annotation.extraInterfaces(),
annotation.answer(), annotation.serializable(), annotation.reset(),
QualifierDefinition.forElement(element));
addDefinition(element, definition, "mock");
}
@@ -92,33 +87,27 @@ class DefinitionsParser {
private void parseSpyBeanAnnotation(SpyBean annotation, AnnotatedElement element) {
Set<ResolvableType> typesToSpy = getOrDeduceTypes(element, annotation.value());
Assert.state(!typesToSpy.isEmpty(),
() -> "Unable to deduce type to spy from " + element);
Assert.state(!typesToSpy.isEmpty(), () -> "Unable to deduce type to spy from " + element);
if (StringUtils.hasLength(annotation.name())) {
Assert.state(typesToSpy.size() == 1,
"The name attribute can only be used when spying a single class");
Assert.state(typesToSpy.size() == 1, "The name attribute can only be used when spying a single class");
}
for (ResolvableType typeToSpy : typesToSpy) {
SpyDefinition definition = new SpyDefinition(annotation.name(), typeToSpy,
annotation.reset(), annotation.proxyTargetAware(),
QualifierDefinition.forElement(element));
SpyDefinition definition = new SpyDefinition(annotation.name(), typeToSpy, annotation.reset(),
annotation.proxyTargetAware(), QualifierDefinition.forElement(element));
addDefinition(element, definition, "spy");
}
}
private void addDefinition(AnnotatedElement element, Definition definition,
String type) {
private void addDefinition(AnnotatedElement element, Definition definition, String type) {
boolean isNewDefinition = this.definitions.add(definition);
Assert.state(isNewDefinition,
() -> "Duplicate " + type + " definition " + definition);
Assert.state(isNewDefinition, () -> "Duplicate " + type + " definition " + definition);
if (element instanceof Field) {
Field field = (Field) element;
this.definitionFields.put(definition, field);
}
}
private Set<ResolvableType> getOrDeduceTypes(AnnotatedElement element,
Class<?>[] value) {
private Set<ResolvableType> getOrDeduceTypes(AnnotatedElement element, Class<?>[] value) {
Set<ResolvableType> types = new LinkedHashSet<>();
for (Class<?> clazz : value) {
types.add(ResolvableType.forClass(clazz));

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -49,9 +49,8 @@ class MockDefinition extends Definition {
private final boolean serializable;
MockDefinition(String name, ResolvableType typeToMock, Class<?>[] extraInterfaces,
Answers answer, boolean serializable, MockReset reset,
QualifierDefinition qualifier) {
MockDefinition(String name, ResolvableType typeToMock, Class<?>[] extraInterfaces, Answers answer,
boolean serializable, MockReset reset, QualifierDefinition qualifier) {
super(name, reset, false, qualifier);
Assert.notNull(typeToMock, "TypeToMock must not be null");
this.typeToMock = typeToMock;
@@ -111,8 +110,7 @@ class MockDefinition extends Definition {
MockDefinition other = (MockDefinition) obj;
boolean result = super.equals(obj);
result = result && ObjectUtils.nullSafeEquals(this.typeToMock, other.typeToMock);
result = result && ObjectUtils.nullSafeEquals(this.extraInterfaces,
other.extraInterfaces);
result = result && ObjectUtils.nullSafeEquals(this.extraInterfaces, other.extraInterfaces);
result = result && ObjectUtils.nullSafeEquals(this.answer, other.answer);
result = result && this.serializable == other.serializable;
return result;
@@ -130,11 +128,9 @@ class MockDefinition extends Definition {
@Override
public String toString() {
return new ToStringCreator(this).append("name", getName())
.append("typeToMock", this.typeToMock)
.append("extraInterfaces", this.extraInterfaces)
.append("answer", this.answer).append("serializable", this.serializable)
.append("reset", getReset()).toString();
return new ToStringCreator(this).append("name", getName()).append("typeToMock", this.typeToMock)
.append("extraInterfaces", this.extraInterfaces).append("answer", this.answer)
.append("serializable", this.serializable).append("reset", getReset()).toString();
}
public <T> T createMock() {

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -41,8 +41,7 @@ class MockitoContextCustomizer implements ContextCustomizer {
public void customizeContext(ConfigurableApplicationContext context,
MergedContextConfiguration mergedContextConfiguration) {
if (context instanceof BeanDefinitionRegistry) {
MockitoPostProcessor.register((BeanDefinitionRegistry) context,
this.definitions);
MockitoPostProcessor.register((BeanDefinitionRegistry) context, this.definitions);
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -76,16 +76,14 @@ import org.springframework.util.StringUtils;
* @since 1.4.0
*/
public class MockitoPostProcessor extends InstantiationAwareBeanPostProcessorAdapter
implements BeanClassLoaderAware, BeanFactoryAware, BeanFactoryPostProcessor,
Ordered {
implements BeanClassLoaderAware, BeanFactoryAware, BeanFactoryPostProcessor, Ordered {
private static final String FACTORY_BEAN_OBJECT_TYPE = "factoryBeanObjectType";
private static final String BEAN_NAME = MockitoPostProcessor.class.getName();
private static final String CONFIGURATION_CLASS_ATTRIBUTE = Conventions
.getQualifiedAttributeName(ConfigurationClassPostProcessor.class,
"configurationClass");
.getQualifiedAttributeName(ConfigurationClassPostProcessor.class, "configurationClass");
private static final BeanNameGenerator beanNameGenerator = new DefaultBeanNameGenerator();
@@ -125,16 +123,13 @@ public class MockitoPostProcessor extends InstantiationAwareBeanPostProcessorAda
}
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory)
throws BeansException {
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
Assert.isInstanceOf(BeanDefinitionRegistry.class, beanFactory,
"@MockBean can only be used on bean factories that "
+ "implement BeanDefinitionRegistry");
"@MockBean can only be used on bean factories that " + "implement BeanDefinitionRegistry");
postProcessBeanFactory(beanFactory, (BeanDefinitionRegistry) beanFactory);
}
private void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory,
BeanDefinitionRegistry registry) {
private void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory, BeanDefinitionRegistry registry) {
beanFactory.registerSingleton(MockitoBeans.class.getName(), this.mockitoBeans);
DefinitionsParser parser = new DefinitionsParser(this.definitions);
for (Class<?> configurationClass : getConfigurationClasses(beanFactory)) {
@@ -147,19 +142,15 @@ public class MockitoPostProcessor extends InstantiationAwareBeanPostProcessorAda
}
}
private Set<Class<?>> getConfigurationClasses(
ConfigurableListableBeanFactory beanFactory) {
private Set<Class<?>> getConfigurationClasses(ConfigurableListableBeanFactory beanFactory) {
Set<Class<?>> configurationClasses = new LinkedHashSet<>();
for (BeanDefinition beanDefinition : getConfigurationBeanDefinitions(beanFactory)
.values()) {
configurationClasses.add(ClassUtils.resolveClassName(
beanDefinition.getBeanClassName(), this.classLoader));
for (BeanDefinition beanDefinition : getConfigurationBeanDefinitions(beanFactory).values()) {
configurationClasses.add(ClassUtils.resolveClassName(beanDefinition.getBeanClassName(), this.classLoader));
}
return configurationClasses;
}
private Map<String, BeanDefinition> getConfigurationBeanDefinitions(
ConfigurableListableBeanFactory beanFactory) {
private Map<String, BeanDefinition> getConfigurationBeanDefinitions(ConfigurableListableBeanFactory beanFactory) {
Map<String, BeanDefinition> definitions = new LinkedHashMap<>();
for (String beanName : beanFactory.getBeanDefinitionNames()) {
BeanDefinition definition = beanFactory.getBeanDefinition(beanName);
@@ -170,8 +161,8 @@ public class MockitoPostProcessor extends InstantiationAwareBeanPostProcessorAda
return definitions;
}
private void register(ConfigurableListableBeanFactory beanFactory,
BeanDefinitionRegistry registry, Definition definition, Field field) {
private void register(ConfigurableListableBeanFactory beanFactory, BeanDefinitionRegistry registry,
Definition definition, Field field) {
if (definition instanceof MockDefinition) {
registerMock(beanFactory, registry, (MockDefinition) definition, field);
}
@@ -180,8 +171,8 @@ public class MockitoPostProcessor extends InstantiationAwareBeanPostProcessorAda
}
}
private void registerMock(ConfigurableListableBeanFactory beanFactory,
BeanDefinitionRegistry registry, MockDefinition definition, Field field) {
private void registerMock(ConfigurableListableBeanFactory beanFactory, BeanDefinitionRegistry registry,
MockDefinition definition, Field field) {
RootBeanDefinition beanDefinition = createBeanDefinition(definition);
String beanName = getBeanName(beanFactory, registry, definition, beanDefinition);
String transformedBeanName = BeanFactoryUtils.transformedBeanName(beanName);
@@ -201,8 +192,7 @@ public class MockitoPostProcessor extends InstantiationAwareBeanPostProcessorAda
}
private RootBeanDefinition createBeanDefinition(MockDefinition mockDefinition) {
RootBeanDefinition definition = new RootBeanDefinition(
mockDefinition.getTypeToMock().resolve());
RootBeanDefinition definition = new RootBeanDefinition(mockDefinition.getTypeToMock().resolve());
definition.setTargetType(mockDefinition.getTypeToMock());
if (mockDefinition.getQualifier() != null) {
mockDefinition.getQualifier().applyTo(definition);
@@ -210,40 +200,35 @@ public class MockitoPostProcessor extends InstantiationAwareBeanPostProcessorAda
return definition;
}
private String getBeanName(ConfigurableListableBeanFactory beanFactory,
BeanDefinitionRegistry registry, MockDefinition mockDefinition,
RootBeanDefinition beanDefinition) {
private String getBeanName(ConfigurableListableBeanFactory beanFactory, BeanDefinitionRegistry registry,
MockDefinition mockDefinition, RootBeanDefinition beanDefinition) {
if (StringUtils.hasLength(mockDefinition.getName())) {
return mockDefinition.getName();
}
Set<String> existingBeans = getExistingBeans(beanFactory,
mockDefinition.getTypeToMock(), mockDefinition.getQualifier());
Set<String> existingBeans = getExistingBeans(beanFactory, mockDefinition.getTypeToMock(),
mockDefinition.getQualifier());
if (existingBeans.isEmpty()) {
return MockitoPostProcessor.beanNameGenerator.generateBeanName(beanDefinition,
registry);
return MockitoPostProcessor.beanNameGenerator.generateBeanName(beanDefinition, registry);
}
if (existingBeans.size() == 1) {
return existingBeans.iterator().next();
}
String primaryCandidate = determinePrimaryCandidate(registry, existingBeans,
mockDefinition.getTypeToMock());
String primaryCandidate = determinePrimaryCandidate(registry, existingBeans, mockDefinition.getTypeToMock());
if (primaryCandidate != null) {
return primaryCandidate;
}
throw new IllegalStateException(
"Unable to register mock bean " + mockDefinition.getTypeToMock()
+ " expected a single matching bean to replace but found "
+ existingBeans);
throw new IllegalStateException("Unable to register mock bean " + mockDefinition.getTypeToMock()
+ " expected a single matching bean to replace but found " + existingBeans);
}
private void copyBeanDefinitionDetails(BeanDefinition from, RootBeanDefinition to) {
to.setPrimary(from.isPrimary());
}
private void registerSpy(ConfigurableListableBeanFactory beanFactory,
BeanDefinitionRegistry registry, SpyDefinition spyDefinition, Field field) {
Set<String> existingBeans = getExistingBeans(beanFactory,
spyDefinition.getTypeToSpy(), spyDefinition.getQualifier());
private void registerSpy(ConfigurableListableBeanFactory beanFactory, BeanDefinitionRegistry registry,
SpyDefinition spyDefinition, Field field) {
Set<String> existingBeans = getExistingBeans(beanFactory, spyDefinition.getTypeToSpy(),
spyDefinition.getQualifier());
if (ObjectUtils.isEmpty(existingBeans)) {
createSpy(registry, spyDefinition, field);
}
@@ -252,8 +237,8 @@ public class MockitoPostProcessor extends InstantiationAwareBeanPostProcessorAda
}
}
private Set<String> getExistingBeans(ConfigurableListableBeanFactory beanFactory,
ResolvableType type, QualifierDefinition qualifier) {
private Set<String> getExistingBeans(ConfigurableListableBeanFactory beanFactory, ResolvableType type,
QualifierDefinition qualifier) {
Set<String> candidates = new TreeSet<>();
for (String candidate : getExistingBeans(beanFactory, type)) {
if (qualifier == null || qualifier.matches(beanFactory, candidate)) {
@@ -263,10 +248,8 @@ public class MockitoPostProcessor extends InstantiationAwareBeanPostProcessorAda
return candidates;
}
private Set<String> getExistingBeans(ConfigurableListableBeanFactory beanFactory,
ResolvableType type) {
Set<String> beans = new LinkedHashSet<>(
Arrays.asList(beanFactory.getBeanNamesForType(type)));
private Set<String> getExistingBeans(ConfigurableListableBeanFactory beanFactory, ResolvableType type) {
Set<String> beans = new LinkedHashSet<>(Arrays.asList(beanFactory.getBeanNamesForType(type)));
String typeName = type.resolve(Object.class).getName();
for (String beanName : beanFactory.getBeanNamesForType(FactoryBean.class)) {
beanName = BeanFactoryUtils.transformedBeanName(beanName);
@@ -288,49 +271,43 @@ public class MockitoPostProcessor extends InstantiationAwareBeanPostProcessorAda
}
}
private void createSpy(BeanDefinitionRegistry registry, SpyDefinition spyDefinition,
Field field) {
RootBeanDefinition beanDefinition = new RootBeanDefinition(
spyDefinition.getTypeToSpy().resolve());
String beanName = MockitoPostProcessor.beanNameGenerator
.generateBeanName(beanDefinition, registry);
private void createSpy(BeanDefinitionRegistry registry, SpyDefinition spyDefinition, Field field) {
RootBeanDefinition beanDefinition = new RootBeanDefinition(spyDefinition.getTypeToSpy().resolve());
String beanName = MockitoPostProcessor.beanNameGenerator.generateBeanName(beanDefinition, registry);
registry.registerBeanDefinition(beanName, beanDefinition);
registerSpy(spyDefinition, field, beanName);
}
private void registerSpies(BeanDefinitionRegistry registry,
SpyDefinition spyDefinition, Field field, Collection<String> existingBeans) {
private void registerSpies(BeanDefinitionRegistry registry, SpyDefinition spyDefinition, Field field,
Collection<String> existingBeans) {
try {
String beanName = determineBeanName(existingBeans, spyDefinition, registry);
registerSpy(spyDefinition, field, beanName);
}
catch (RuntimeException ex) {
throw new IllegalStateException(
"Unable to register spy bean " + spyDefinition.getTypeToSpy(), ex);
throw new IllegalStateException("Unable to register spy bean " + spyDefinition.getTypeToSpy(), ex);
}
}
private String determineBeanName(Collection<String> existingBeans,
SpyDefinition definition, BeanDefinitionRegistry registry) {
private String determineBeanName(Collection<String> existingBeans, SpyDefinition definition,
BeanDefinitionRegistry registry) {
if (StringUtils.hasText(definition.getName())) {
return definition.getName();
}
if (existingBeans.size() == 1) {
return existingBeans.iterator().next();
}
return determinePrimaryCandidate(registry, existingBeans,
definition.getTypeToSpy());
return determinePrimaryCandidate(registry, existingBeans, definition.getTypeToSpy());
}
private String determinePrimaryCandidate(BeanDefinitionRegistry registry,
Collection<String> candidateBeanNames, ResolvableType type) {
private String determinePrimaryCandidate(BeanDefinitionRegistry registry, Collection<String> candidateBeanNames,
ResolvableType type) {
String primaryBeanName = null;
for (String candidateBeanName : candidateBeanNames) {
BeanDefinition beanDefinition = registry.getBeanDefinition(candidateBeanName);
if (beanDefinition.isPrimary()) {
if (primaryBeanName != null) {
throw new NoUniqueBeanDefinitionException(type.resolve(),
candidateBeanNames.size(),
throw new NoUniqueBeanDefinitionException(type.resolve(), candidateBeanNames.size(),
"more than one 'primary' bean found among candidates: "
+ Arrays.asList(candidateBeanNames));
}
@@ -348,8 +325,7 @@ public class MockitoPostProcessor extends InstantiationAwareBeanPostProcessorAda
}
}
protected final Object createSpyIfNecessary(Object bean, String beanName)
throws BeansException {
protected final Object createSpyIfNecessary(Object bean, String beanName) throws BeansException {
SpyDefinition definition = this.spies.get(beanName);
if (definition != null) {
bean = definition.createSpy(beanName, bean);
@@ -358,11 +334,9 @@ public class MockitoPostProcessor extends InstantiationAwareBeanPostProcessorAda
}
@Override
public PropertyValues postProcessPropertyValues(PropertyValues pvs,
PropertyDescriptor[] pds, final Object bean, String beanName)
throws BeansException {
ReflectionUtils.doWithFields(bean.getClass(),
(field) -> postProcessField(bean, field));
public PropertyValues postProcessPropertyValues(PropertyValues pvs, PropertyDescriptor[] pds, final Object bean,
String beanName) throws BeansException {
ReflectionUtils.doWithFields(bean.getClass(), (field) -> postProcessField(bean, field));
return pvs;
}
@@ -375,8 +349,7 @@ public class MockitoPostProcessor extends InstantiationAwareBeanPostProcessorAda
void inject(Field field, Object target, Definition definition) {
String beanName = this.beanNameRegistry.get(definition);
Assert.state(StringUtils.hasLength(beanName),
() -> "No bean found for definition " + definition);
Assert.state(StringUtils.hasLength(beanName), () -> "No bean found for definition " + definition);
inject(field, target, beanName);
}
@@ -413,8 +386,7 @@ public class MockitoPostProcessor extends InstantiationAwareBeanPostProcessorAda
* @param registry the bean definition registry
* @param definitions the initial mock/spy definitions
*/
public static void register(BeanDefinitionRegistry registry,
Set<Definition> definitions) {
public static void register(BeanDefinitionRegistry registry, Set<Definition> definitions) {
register(registry, MockitoPostProcessor.class, definitions);
}
@@ -426,13 +398,11 @@ public class MockitoPostProcessor extends InstantiationAwareBeanPostProcessorAda
* @param definitions the initial mock/spy definitions
*/
@SuppressWarnings("unchecked")
public static void register(BeanDefinitionRegistry registry,
Class<? extends MockitoPostProcessor> postProcessor,
public static void register(BeanDefinitionRegistry registry, Class<? extends MockitoPostProcessor> postProcessor,
Set<Definition> definitions) {
SpyPostProcessor.register(registry);
BeanDefinition definition = getOrAddBeanDefinition(registry, postProcessor);
ValueHolder constructorArg = definition.getConstructorArgumentValues()
.getIndexedArgumentValue(0, Set.class);
ValueHolder constructorArg = definition.getConstructorArgumentValues().getIndexedArgumentValue(0, Set.class);
Set<Definition> existing = (Set<Definition>) constructorArg.getValue();
if (definitions != null) {
existing.addAll(definitions);
@@ -444,10 +414,8 @@ public class MockitoPostProcessor extends InstantiationAwareBeanPostProcessorAda
if (!registry.containsBeanDefinition(BEAN_NAME)) {
RootBeanDefinition definition = new RootBeanDefinition(postProcessor);
definition.setRole(BeanDefinition.ROLE_INFRASTRUCTURE);
ConstructorArgumentValues constructorArguments = definition
.getConstructorArgumentValues();
constructorArguments.addIndexedArgumentValue(0,
new LinkedHashSet<MockDefinition>());
ConstructorArgumentValues constructorArguments = definition.getConstructorArgumentValues();
constructorArguments.addIndexedArgumentValue(0, new LinkedHashSet<MockDefinition>());
registry.registerBeanDefinition(BEAN_NAME, definition);
return definition;
}
@@ -458,8 +426,7 @@ public class MockitoPostProcessor extends InstantiationAwareBeanPostProcessorAda
* {@link BeanPostProcessor} to handle {@link SpyBean} definitions. Registered as a
* separate processor so that it can be ordered above AOP post processors.
*/
static class SpyPostProcessor extends InstantiationAwareBeanPostProcessorAdapter
implements PriorityOrdered {
static class SpyPostProcessor extends InstantiationAwareBeanPostProcessorAdapter implements PriorityOrdered {
private static final String BEAN_NAME = SpyPostProcessor.class.getName();
@@ -475,14 +442,12 @@ public class MockitoPostProcessor extends InstantiationAwareBeanPostProcessorAda
}
@Override
public Object getEarlyBeanReference(Object bean, String beanName)
throws BeansException {
public Object getEarlyBeanReference(Object bean, String beanName) throws BeansException {
return this.mockitoPostProcessor.createSpyIfNecessary(bean, beanName);
}
@Override
public Object postProcessAfterInitialization(Object bean, String beanName)
throws BeansException {
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
if (bean instanceof FactoryBean) {
return bean;
}
@@ -491,11 +456,9 @@ public class MockitoPostProcessor extends InstantiationAwareBeanPostProcessorAda
public static void register(BeanDefinitionRegistry registry) {
if (!registry.containsBeanDefinition(BEAN_NAME)) {
RootBeanDefinition definition = new RootBeanDefinition(
SpyPostProcessor.class);
RootBeanDefinition definition = new RootBeanDefinition(SpyPostProcessor.class);
definition.setRole(BeanDefinition.ROLE_INFRASTRUCTURE);
ConstructorArgumentValues constructorArguments = definition
.getConstructorArgumentValues();
ConstructorArgumentValues constructorArguments = definition.getConstructorArgumentValues();
constructorArguments.addIndexedArgumentValue(0,
new RuntimeBeanReference(MockitoPostProcessor.BEAN_NAME));
registry.registerBeanDefinition(BEAN_NAME, definition);

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -56,8 +56,8 @@ public class MockitoTestExecutionListener extends AbstractTestExecutionListener
@Override
public void beforeTestMethod(TestContext testContext) throws Exception {
if (Boolean.TRUE.equals(testContext.getAttribute(
DependencyInjectionTestExecutionListener.REINJECT_DEPENDENCIES_ATTRIBUTE))) {
if (Boolean.TRUE.equals(
testContext.getAttribute(DependencyInjectionTestExecutionListener.REINJECT_DEPENDENCIES_ATTRIBUTE))) {
initMocks(testContext);
reinjectFields(testContext);
}
@@ -76,23 +76,19 @@ public class MockitoTestExecutionListener extends AbstractTestExecutionListener
}
private void injectFields(TestContext testContext) {
postProcessFields(testContext,
(mockitoField, postProcessor) -> postProcessor.inject(mockitoField.field,
mockitoField.target, mockitoField.definition));
postProcessFields(testContext, (mockitoField, postProcessor) -> postProcessor.inject(mockitoField.field,
mockitoField.target, mockitoField.definition));
}
private void reinjectFields(final TestContext testContext) {
postProcessFields(testContext, (mockitoField, postProcessor) -> {
ReflectionUtils.makeAccessible(mockitoField.field);
ReflectionUtils.setField(mockitoField.field, testContext.getTestInstance(),
null);
postProcessor.inject(mockitoField.field, mockitoField.target,
mockitoField.definition);
ReflectionUtils.setField(mockitoField.field, testContext.getTestInstance(), null);
postProcessor.inject(mockitoField.field, mockitoField.target, mockitoField.definition);
});
}
private void postProcessFields(TestContext testContext,
BiConsumer<MockitoField, MockitoPostProcessor> consumer) {
private void postProcessFields(TestContext testContext, BiConsumer<MockitoField, MockitoPostProcessor> consumer) {
DefinitionsParser parser = new DefinitionsParser();
parser.parse(testContext.getTestClass());
if (!parser.getDefinitions().isEmpty()) {
@@ -101,8 +97,7 @@ public class MockitoTestExecutionListener extends AbstractTestExecutionListener
for (Definition definition : parser.getDefinitions()) {
Field field = parser.getField(definition);
if (field != null) {
consumer.accept(new MockitoField(field, testContext.getTestInstance(),
definition), postProcessor);
consumer.accept(new MockitoField(field, testContext.getTestInstance(), definition), postProcessor);
}
}
}
@@ -116,8 +111,7 @@ public class MockitoTestExecutionListener extends AbstractTestExecutionListener
private final Set<Annotation> annotations = new LinkedHashSet<>();
@Override
public void doWith(Field field)
throws IllegalArgumentException, IllegalAccessException {
public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException {
for (Annotation annotation : field.getDeclaredAnnotations()) {
if (annotation.annotationType().getName().startsWith("org.mockito")) {
this.annotations.add(annotation);

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -42,8 +42,7 @@ import org.springframework.util.ClassUtils;
*/
public class ResetMocksTestExecutionListener extends AbstractTestExecutionListener {
private static final boolean MOCKITO_IS_PRESENT = ClassUtils.isPresent(
"org.mockito.MockSettings",
private static final boolean MOCKITO_IS_PRESENT = ClassUtils.isPresent("org.mockito.MockSettings",
ResetMocksTestExecutionListener.class.getClassLoader());
@Override
@@ -71,12 +70,10 @@ public class ResetMocksTestExecutionListener extends AbstractTestExecutionListen
}
}
private void resetMocks(ConfigurableApplicationContext applicationContext,
MockReset reset) {
private void resetMocks(ConfigurableApplicationContext applicationContext, MockReset reset) {
ConfigurableListableBeanFactory beanFactory = applicationContext.getBeanFactory();
String[] names = beanFactory.getBeanDefinitionNames();
Set<String> instantiatedSingletons = new HashSet<>(
Arrays.asList(beanFactory.getSingletonNames()));
Set<String> instantiatedSingletons = new HashSet<>(Arrays.asList(beanFactory.getSingletonNames()));
for (String name : names) {
BeanDefinition definition = beanFactory.getBeanDefinition(name);
if (definition.isSingleton() && instantiatedSingletons.contains(name)) {

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -39,8 +39,8 @@ class SpyDefinition extends Definition {
private final ResolvableType typeToSpy;
SpyDefinition(String name, ResolvableType typeToSpy, MockReset reset,
boolean proxyTargetAware, QualifierDefinition qualifier) {
SpyDefinition(String name, ResolvableType typeToSpy, MockReset reset, boolean proxyTargetAware,
QualifierDefinition qualifier) {
super(name, reset, proxyTargetAware, qualifier);
Assert.notNull(typeToSpy, "TypeToSpy must not be null");
this.typeToSpy = typeToSpy;
@@ -74,9 +74,8 @@ class SpyDefinition extends Definition {
@Override
public String toString() {
return new ToStringCreator(this).append("name", getName())
.append("typeToSpy", this.typeToSpy).append("reset", getReset())
.toString();
return new ToStringCreator(this).append("name", getName()).append("typeToSpy", this.typeToSpy)
.append("reset", getReset()).toString();
}
public <T> T createSpy(Object instance) {
@@ -97,8 +96,7 @@ class SpyDefinition extends Definition {
settings.spiedInstance(instance);
settings.defaultAnswer(Mockito.CALLS_REAL_METHODS);
if (this.isProxyTargetAware()) {
settings.verificationStartedListeners(
new SpringAopBypassingVerificationStartedListener());
settings.verificationStartedListeners(new SpringAopBypassingVerificationStartedListener());
}
return (T) Mockito.mock(instance.getClass(), settings);
}
@@ -107,8 +105,7 @@ class SpyDefinition extends Definition {
* A {@link VerificationStartedListener} that bypasses any proxy created by Spring AOP
* when the verification of a spy starts.
*/
private static final class SpringAopBypassingVerificationStartedListener
implements VerificationStartedListener {
private static final class SpringAopBypassingVerificationStartedListener implements VerificationStartedListener {
@Override
public void onVerificationStarted(VerificationStartedEvent event) {

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2017 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -36,9 +36,8 @@ import org.springframework.mock.web.MockServletContext;
*/
public class SpringBootMockServletContext extends MockServletContext {
private static final String[] SPRING_BOOT_RESOURCE_LOCATIONS = new String[] {
"classpath:META-INF/resources", "classpath:resources", "classpath:static",
"classpath:public" };
private static final String[] SPRING_BOOT_RESOURCE_LOCATIONS = new String[] { "classpath:META-INF/resources",
"classpath:resources", "classpath:static", "classpath:public" };
private final ResourceLoader resourceLoader;
@@ -48,8 +47,7 @@ public class SpringBootMockServletContext extends MockServletContext {
this(resourceBasePath, new FileSystemResourceLoader());
}
public SpringBootMockServletContext(String resourceBasePath,
ResourceLoader resourceLoader) {
public SpringBootMockServletContext(String resourceBasePath, ResourceLoader resourceLoader) {
super(resourceBasePath, resourceLoader);
this.resourceLoader = resourceLoader;
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -50,8 +50,7 @@ import org.springframework.util.StringUtils;
*/
public final class TestPropertyValues {
private static final TestPropertyValues EMPTY = new TestPropertyValues(
Collections.emptyMap());
private static final TestPropertyValues EMPTY = new TestPropertyValues(Collections.emptyMap());
private final Map<String, Object> properties;
@@ -145,8 +144,7 @@ public final class TestPropertyValues {
if (sources.contains(name)) {
PropertySource<?> propertySource = sources.get(name);
if (propertySource.getClass() == type.getSourceClass()) {
((Map<String, Object>) propertySource.getSource())
.putAll(this.properties);
((Map<String, Object>) propertySource.getSource()).putAll(this.properties);
return;
}
}
@@ -300,8 +298,7 @@ public final class TestPropertyValues {
private Map<String, String> apply(Map<String, ?> properties) {
Map<String, String> previous = new LinkedHashMap<>();
properties.forEach((name, value) -> previous.put(name,
setOrClear(name, (String) value)));
properties.forEach((name, value) -> previous.put(name, setOrClear(name, (String) value)));
return previous;
}

View File

@@ -34,30 +34,24 @@ import org.springframework.util.ClassUtils;
* @author Madhura Bhave
* @author Andy Wilkinson
*/
class SpringBootTestRandomPortEnvironmentPostProcessor
implements EnvironmentPostProcessor {
class SpringBootTestRandomPortEnvironmentPostProcessor implements EnvironmentPostProcessor {
private static final String MANAGEMENT_PORT_PROPERTY = "management.server.port";
private static final String SERVER_PORT_PROPERTY = "server.port";
@Override
public void postProcessEnvironment(ConfigurableEnvironment environment,
SpringApplication application) {
public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {
MapPropertySource source = (MapPropertySource) environment.getPropertySources()
.get(TestPropertySourceUtils.INLINED_PROPERTIES_PROPERTY_SOURCE_NAME);
if (source == null || isTestServerPortFixed(source, environment)
|| isTestManagementPortConfigured(source)) {
if (source == null || isTestServerPortFixed(source, environment) || isTestManagementPortConfigured(source)) {
return;
}
Integer managementPort = getPropertyAsInteger(environment,
MANAGEMENT_PORT_PROPERTY, null);
if (managementPort == null || managementPort.equals(-1)
|| managementPort.equals(0)) {
Integer managementPort = getPropertyAsInteger(environment, MANAGEMENT_PORT_PROPERTY, null);
if (managementPort == null || managementPort.equals(-1) || managementPort.equals(0)) {
return;
}
Integer serverPort = getPropertyAsInteger(environment, SERVER_PORT_PROPERTY,
8080);
Integer serverPort = getPropertyAsInteger(environment, SERVER_PORT_PROPERTY, 8080);
if (!managementPort.equals(serverPort)) {
source.getSource().put(MANAGEMENT_PORT_PROPERTY, "0");
}
@@ -66,23 +60,19 @@ class SpringBootTestRandomPortEnvironmentPostProcessor
}
}
private boolean isTestServerPortFixed(MapPropertySource source,
ConfigurableEnvironment environment) {
return !Integer.valueOf(0)
.equals(getPropertyAsInteger(source, SERVER_PORT_PROPERTY, environment));
private boolean isTestServerPortFixed(MapPropertySource source, ConfigurableEnvironment environment) {
return !Integer.valueOf(0).equals(getPropertyAsInteger(source, SERVER_PORT_PROPERTY, environment));
}
private boolean isTestManagementPortConfigured(PropertySource<?> source) {
return source.getProperty(MANAGEMENT_PORT_PROPERTY) != null;
}
private Integer getPropertyAsInteger(ConfigurableEnvironment environment,
String property, Integer defaultValue) {
return environment.getPropertySources().stream()
.filter((source) -> !source.getName().equals(
TestPropertySourceUtils.INLINED_PROPERTIES_PROPERTY_SOURCE_NAME))
.map((source) -> getPropertyAsInteger(source, property, environment))
.filter(Objects::nonNull).findFirst().orElse(defaultValue);
private Integer getPropertyAsInteger(ConfigurableEnvironment environment, String property, Integer defaultValue) {
return environment.getPropertySources().stream().filter(
(source) -> !source.getName().equals(TestPropertySourceUtils.INLINED_PROPERTIES_PROPERTY_SOURCE_NAME))
.map((source) -> getPropertyAsInteger(source, property, environment)).filter(Objects::nonNull)
.findFirst().orElse(defaultValue);
}
private Integer getPropertyAsInteger(PropertySource<?> source, String property,
@@ -105,8 +95,7 @@ class SpringBootTestRandomPortEnvironmentPostProcessor
}
}
private Integer getResolvedValueIfPossible(ConfigurableEnvironment environment,
String value) {
private Integer getResolvedValueIfPossible(ConfigurableEnvironment environment, String value) {
String resolvedValue = environment.resolveRequiredPlaceholders(value);
return environment.getConversionService().convert(resolvedValue, Integer.class);
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -70,8 +70,7 @@ public class LocalHostUriTemplateHandler extends RootUriTemplateHandler {
* @param handler the delegate handler
* @since 2.0.3
*/
public LocalHostUriTemplateHandler(Environment environment, String scheme,
UriTemplateHandler handler) {
public LocalHostUriTemplateHandler(Environment environment, String scheme, UriTemplateHandler handler) {
super(handler);
Assert.notNull(environment, "Environment must not be null");
Assert.notNull(scheme, "Scheme must not be null");

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2017 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -65,8 +65,7 @@ public class MockServerRestTemplateCustomizer implements RestTemplateCustomizer
this.expectationManager = SimpleRequestExpectationManager.class;
}
public MockServerRestTemplateCustomizer(
Class<? extends RequestExpectationManager> expectationManager) {
public MockServerRestTemplateCustomizer(Class<? extends RequestExpectationManager> expectationManager) {
Assert.notNull(expectationManager, "ExpectationManager must not be null");
this.expectationManager = expectationManager;
}
@@ -84,11 +83,9 @@ public class MockServerRestTemplateCustomizer implements RestTemplateCustomizer
public void customize(RestTemplate restTemplate) {
RequestExpectationManager expectationManager = createExpectationManager();
if (this.detectRootUri) {
expectationManager = RootUriRequestExpectationManager
.forRestTemplate(restTemplate, expectationManager);
expectationManager = RootUriRequestExpectationManager.forRestTemplate(restTemplate, expectationManager);
}
MockRestServiceServer server = MockRestServiceServer.bindTo(restTemplate)
.build(expectationManager);
MockRestServiceServer server = MockRestServiceServer.bindTo(restTemplate).build(expectationManager);
this.expectationManagers.put(restTemplate, expectationManager);
this.servers.put(restTemplate, server);
}
@@ -98,14 +95,10 @@ public class MockServerRestTemplateCustomizer implements RestTemplateCustomizer
}
public MockRestServiceServer getServer() {
Assert.state(!this.servers.isEmpty(),
"Unable to return a single MockRestServiceServer since "
+ "MockServerRestTemplateCustomizer has not been bound to "
+ "a RestTemplate");
Assert.state(this.servers.size() == 1,
"Unable to return a single MockRestServiceServer since "
+ "MockServerRestTemplateCustomizer has been bound to "
+ "more than one RestTemplate");
Assert.state(!this.servers.isEmpty(), "Unable to return a single MockRestServiceServer since "
+ "MockServerRestTemplateCustomizer has not been bound to " + "a RestTemplate");
Assert.state(this.servers.size() == 1, "Unable to return a single MockRestServiceServer since "
+ "MockServerRestTemplateCustomizer has been bound to " + "more than one RestTemplate");
return this.servers.values().iterator().next();
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2017 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -59,8 +59,7 @@ public class RootUriRequestExpectationManager implements RequestExpectationManag
private final RequestExpectationManager expectationManager;
public RootUriRequestExpectationManager(String rootUri,
RequestExpectationManager expectationManager) {
public RootUriRequestExpectationManager(String rootUri, RequestExpectationManager expectationManager) {
Assert.notNull(rootUri, "RootUri must not be null");
Assert.notNull(expectationManager, "ExpectationManager must not be null");
this.rootUri = rootUri;
@@ -68,14 +67,12 @@ public class RootUriRequestExpectationManager implements RequestExpectationManag
}
@Override
public ResponseActions expectRequest(ExpectedCount count,
RequestMatcher requestMatcher) {
public ResponseActions expectRequest(ExpectedCount count, RequestMatcher requestMatcher) {
return this.expectationManager.expectRequest(count, requestMatcher);
}
@Override
public ClientHttpResponse validateRequest(ClientHttpRequest request)
throws IOException {
public ClientHttpResponse validateRequest(ClientHttpRequest request) throws IOException {
String uri = request.getURI().toString();
if (uri.startsWith(this.rootUri)) {
request = replaceURI(request, uri.substring(this.rootUri.length()));
@@ -87,15 +84,14 @@ public class RootUriRequestExpectationManager implements RequestExpectationManag
String message = ex.getMessage();
String prefix = "Request URI expected:</";
if (message != null && message.startsWith(prefix)) {
throw new AssertionError("Request URI expected:<" + this.rootUri
+ message.substring(prefix.length() - 1));
throw new AssertionError(
"Request URI expected:<" + this.rootUri + message.substring(prefix.length() - 1));
}
throw ex;
}
}
private ClientHttpRequest replaceURI(ClientHttpRequest request,
String replacementUri) {
private ClientHttpRequest replaceURI(ClientHttpRequest request, String replacementUri) {
URI uri;
try {
uri = new URI(replacementUri);
@@ -157,8 +153,7 @@ public class RootUriRequestExpectationManager implements RequestExpectationManag
Assert.notNull(restTemplate, "RestTemplate must not be null");
UriTemplateHandler templateHandler = restTemplate.getUriTemplateHandler();
if (templateHandler instanceof RootUriTemplateHandler) {
return new RootUriRequestExpectationManager(
((RootUriTemplateHandler) templateHandler).getRootUri(),
return new RootUriRequestExpectationManager(((RootUriTemplateHandler) templateHandler).getRootUri(),
expectationManager);
}
return expectationManager;
@@ -167,8 +162,7 @@ public class RootUriRequestExpectationManager implements RequestExpectationManag
/**
* {@link ClientHttpRequest} wrapper to replace the request URI.
*/
private static class ReplaceUriClientHttpRequest extends HttpRequestWrapper
implements ClientHttpRequest {
private static class ReplaceUriClientHttpRequest extends HttpRequestWrapper implements ClientHttpRequest {
private final URI uri;

View File

@@ -118,8 +118,7 @@ public class TestRestTemplate {
* @param password the password (or {@code null})
* @param httpClientOptions client options to use if the Apache HTTP Client is used
*/
public TestRestTemplate(String username, String password,
HttpClientOption... httpClientOptions) {
public TestRestTemplate(String username, String password, HttpClientOption... httpClientOptions) {
this(new RestTemplateBuilder(), username, password, httpClientOptions);
}
@@ -132,42 +131,34 @@ public class TestRestTemplate {
* @param httpClientOptions client options to use if the Apache HTTP Client is used
* @since 2.0.0
*/
public TestRestTemplate(RestTemplateBuilder restTemplateBuilder, String username,
String password, HttpClientOption... httpClientOptions) {
this((restTemplateBuilder != null) ? restTemplateBuilder.build() : null, username,
password, httpClientOptions);
public TestRestTemplate(RestTemplateBuilder restTemplateBuilder, String username, String password,
HttpClientOption... httpClientOptions) {
this((restTemplateBuilder != null) ? restTemplateBuilder.build() : null, username, password, httpClientOptions);
}
private TestRestTemplate(RestTemplate restTemplate, String username, String password,
HttpClientOption... httpClientOptions) {
Assert.notNull(restTemplate, "RestTemplate must not be null");
this.httpClientOptions = httpClientOptions;
if (getRequestFactoryClass(restTemplate)
.isAssignableFrom(HttpComponentsClientHttpRequestFactory.class)) {
restTemplate.setRequestFactory(
new CustomHttpComponentsClientHttpRequestFactory(httpClientOptions));
if (getRequestFactoryClass(restTemplate).isAssignableFrom(HttpComponentsClientHttpRequestFactory.class)) {
restTemplate.setRequestFactory(new CustomHttpComponentsClientHttpRequestFactory(httpClientOptions));
}
addAuthentication(restTemplate, username, password);
restTemplate.setErrorHandler(new NoOpResponseErrorHandler());
this.restTemplate = restTemplate;
}
private Class<? extends ClientHttpRequestFactory> getRequestFactoryClass(
RestTemplate restTemplate) {
private Class<? extends ClientHttpRequestFactory> getRequestFactoryClass(RestTemplate restTemplate) {
ClientHttpRequestFactory requestFactory = restTemplate.getRequestFactory();
if (InterceptingClientHttpRequestFactory.class
.isAssignableFrom(requestFactory.getClass())) {
Field requestFactoryField = ReflectionUtils.findField(RestTemplate.class,
"requestFactory");
if (InterceptingClientHttpRequestFactory.class.isAssignableFrom(requestFactory.getClass())) {
Field requestFactoryField = ReflectionUtils.findField(RestTemplate.class, "requestFactory");
ReflectionUtils.makeAccessible(requestFactoryField);
requestFactory = (ClientHttpRequestFactory) ReflectionUtils
.getField(requestFactoryField, restTemplate);
requestFactory = (ClientHttpRequestFactory) ReflectionUtils.getField(requestFactoryField, restTemplate);
}
return requestFactory.getClass();
}
private void addAuthentication(RestTemplate restTemplate, String username,
String password) {
private void addAuthentication(RestTemplate restTemplate, String username, String password) {
if (username == null) {
return;
}
@@ -219,8 +210,7 @@ public class TestRestTemplate {
* @throws RestClientException on client-side HTTP error on client-side HTTP error
* @see RestTemplate#getForObject(String, Class, Object...)
*/
public <T> T getForObject(String url, Class<T> responseType, Object... urlVariables)
throws RestClientException {
public <T> T getForObject(String url, Class<T> responseType, Object... urlVariables) throws RestClientException {
return this.restTemplate.getForObject(url, responseType, urlVariables);
}
@@ -237,8 +227,8 @@ public class TestRestTemplate {
* @throws RestClientException on client-side HTTP error
* @see RestTemplate#getForObject(String, Class, Object...)
*/
public <T> T getForObject(String url, Class<T> responseType,
Map<String, ?> urlVariables) throws RestClientException {
public <T> T getForObject(String url, Class<T> responseType, Map<String, ?> urlVariables)
throws RestClientException {
return this.restTemplate.getForObject(url, responseType, urlVariables);
}
@@ -270,8 +260,8 @@ public class TestRestTemplate {
* @see RestTemplate#getForEntity(java.lang.String, java.lang.Class,
* java.lang.Object[])
*/
public <T> ResponseEntity<T> getForEntity(String url, Class<T> responseType,
Object... urlVariables) throws RestClientException {
public <T> ResponseEntity<T> getForEntity(String url, Class<T> responseType, Object... urlVariables)
throws RestClientException {
return this.restTemplate.getForEntity(url, responseType, urlVariables);
}
@@ -288,8 +278,8 @@ public class TestRestTemplate {
* @throws RestClientException on client-side HTTP error
* @see RestTemplate#getForEntity(java.lang.String, java.lang.Class, java.util.Map)
*/
public <T> ResponseEntity<T> getForEntity(String url, Class<T> responseType,
Map<String, ?> urlVariables) throws RestClientException {
public <T> ResponseEntity<T> getForEntity(String url, Class<T> responseType, Map<String, ?> urlVariables)
throws RestClientException {
return this.restTemplate.getForEntity(url, responseType, urlVariables);
}
@@ -303,8 +293,7 @@ public class TestRestTemplate {
* @throws RestClientException on client-side HTTP error
* @see RestTemplate#getForEntity(java.net.URI, java.lang.Class)
*/
public <T> ResponseEntity<T> getForEntity(URI url, Class<T> responseType)
throws RestClientException {
public <T> ResponseEntity<T> getForEntity(URI url, Class<T> responseType) throws RestClientException {
return this.restTemplate.getForEntity(applyRootUriIfNecessary(url), responseType);
}
@@ -318,8 +307,7 @@ public class TestRestTemplate {
* @throws RestClientException on client-side HTTP error
* @see RestTemplate#headForHeaders(java.lang.String, java.lang.Object[])
*/
public HttpHeaders headForHeaders(String url, Object... urlVariables)
throws RestClientException {
public HttpHeaders headForHeaders(String url, Object... urlVariables) throws RestClientException {
return this.restTemplate.headForHeaders(url, urlVariables);
}
@@ -333,8 +321,7 @@ public class TestRestTemplate {
* @throws RestClientException on client-side HTTP error
* @see RestTemplate#headForHeaders(java.lang.String, java.util.Map)
*/
public HttpHeaders headForHeaders(String url, Map<String, ?> urlVariables)
throws RestClientException {
public HttpHeaders headForHeaders(String url, Map<String, ?> urlVariables) throws RestClientException {
return this.restTemplate.headForHeaders(url, urlVariables);
}
@@ -367,8 +354,7 @@ public class TestRestTemplate {
* @see RestTemplate#postForLocation(java.lang.String, java.lang.Object,
* java.lang.Object[])
*/
public URI postForLocation(String url, Object request, Object... urlVariables)
throws RestClientException {
public URI postForLocation(String url, Object request, Object... urlVariables) throws RestClientException {
return this.restTemplate.postForLocation(url, request, urlVariables);
}
@@ -390,8 +376,7 @@ public class TestRestTemplate {
* @see RestTemplate#postForLocation(java.lang.String, java.lang.Object,
* java.util.Map)
*/
public URI postForLocation(String url, Object request, Map<String, ?> urlVariables)
throws RestClientException {
public URI postForLocation(String url, Object request, Map<String, ?> urlVariables) throws RestClientException {
return this.restTemplate.postForLocation(url, request, urlVariables);
}
@@ -432,8 +417,8 @@ public class TestRestTemplate {
* @see RestTemplate#postForObject(java.lang.String, java.lang.Object,
* java.lang.Class, java.lang.Object[])
*/
public <T> T postForObject(String url, Object request, Class<T> responseType,
Object... urlVariables) throws RestClientException {
public <T> T postForObject(String url, Object request, Class<T> responseType, Object... urlVariables)
throws RestClientException {
return this.restTemplate.postForObject(url, request, responseType, urlVariables);
}
@@ -456,8 +441,8 @@ public class TestRestTemplate {
* @see RestTemplate#postForObject(java.lang.String, java.lang.Object,
* java.lang.Class, java.util.Map)
*/
public <T> T postForObject(String url, Object request, Class<T> responseType,
Map<String, ?> urlVariables) throws RestClientException {
public <T> T postForObject(String url, Object request, Class<T> responseType, Map<String, ?> urlVariables)
throws RestClientException {
return this.restTemplate.postForObject(url, request, responseType, urlVariables);
}
@@ -476,10 +461,8 @@ public class TestRestTemplate {
* @see HttpEntity
* @see RestTemplate#postForObject(java.net.URI, java.lang.Object, java.lang.Class)
*/
public <T> T postForObject(URI url, Object request, Class<T> responseType)
throws RestClientException {
return this.restTemplate.postForObject(applyRootUriIfNecessary(url), request,
responseType);
public <T> T postForObject(URI url, Object request, Class<T> responseType) throws RestClientException {
return this.restTemplate.postForObject(applyRootUriIfNecessary(url), request, responseType);
}
/**
@@ -501,8 +484,8 @@ public class TestRestTemplate {
* @see RestTemplate#postForEntity(java.lang.String, java.lang.Object,
* java.lang.Class, java.lang.Object[])
*/
public <T> ResponseEntity<T> postForEntity(String url, Object request,
Class<T> responseType, Object... urlVariables) throws RestClientException {
public <T> ResponseEntity<T> postForEntity(String url, Object request, Class<T> responseType,
Object... urlVariables) throws RestClientException {
return this.restTemplate.postForEntity(url, request, responseType, urlVariables);
}
@@ -525,9 +508,8 @@ public class TestRestTemplate {
* @see RestTemplate#postForEntity(java.lang.String, java.lang.Object,
* java.lang.Class, java.util.Map)
*/
public <T> ResponseEntity<T> postForEntity(String url, Object request,
Class<T> responseType, Map<String, ?> urlVariables)
throws RestClientException {
public <T> ResponseEntity<T> postForEntity(String url, Object request, Class<T> responseType,
Map<String, ?> urlVariables) throws RestClientException {
return this.restTemplate.postForEntity(url, request, responseType, urlVariables);
}
@@ -546,10 +528,9 @@ public class TestRestTemplate {
* @see HttpEntity
* @see RestTemplate#postForEntity(java.net.URI, java.lang.Object, java.lang.Class)
*/
public <T> ResponseEntity<T> postForEntity(URI url, Object request,
Class<T> responseType) throws RestClientException {
return this.restTemplate.postForEntity(applyRootUriIfNecessary(url), request,
responseType);
public <T> ResponseEntity<T> postForEntity(URI url, Object request, Class<T> responseType)
throws RestClientException {
return this.restTemplate.postForEntity(applyRootUriIfNecessary(url), request, responseType);
}
/**
@@ -566,8 +547,7 @@ public class TestRestTemplate {
* @see HttpEntity
* @see RestTemplate#put(java.lang.String, java.lang.Object, java.lang.Object[])
*/
public void put(String url, Object request, Object... urlVariables)
throws RestClientException {
public void put(String url, Object request, Object... urlVariables) throws RestClientException {
this.restTemplate.put(url, request, urlVariables);
}
@@ -585,8 +565,7 @@ public class TestRestTemplate {
* @see HttpEntity
* @see RestTemplate#put(java.lang.String, java.lang.Object, java.util.Map)
*/
public void put(String url, Object request, Map<String, ?> urlVariables)
throws RestClientException {
public void put(String url, Object request, Map<String, ?> urlVariables) throws RestClientException {
this.restTemplate.put(url, request, urlVariables);
}
@@ -623,8 +602,8 @@ public class TestRestTemplate {
* @since 1.4.4
* @see HttpEntity
*/
public <T> T patchForObject(String url, Object request, Class<T> responseType,
Object... uriVariables) throws RestClientException {
public <T> T patchForObject(String url, Object request, Class<T> responseType, Object... uriVariables)
throws RestClientException {
return this.restTemplate.patchForObject(url, request, responseType, uriVariables);
}
@@ -646,8 +625,8 @@ public class TestRestTemplate {
* @since 1.4.4
* @see HttpEntity
*/
public <T> T patchForObject(String url, Object request, Class<T> responseType,
Map<String, ?> uriVariables) throws RestClientException {
public <T> T patchForObject(String url, Object request, Class<T> responseType, Map<String, ?> uriVariables)
throws RestClientException {
return this.restTemplate.patchForObject(url, request, responseType, uriVariables);
}
@@ -666,10 +645,8 @@ public class TestRestTemplate {
* @since 1.4.4
* @see HttpEntity
*/
public <T> T patchForObject(URI url, Object request, Class<T> responseType)
throws RestClientException {
return this.restTemplate.patchForObject(applyRootUriIfNecessary(url), request,
responseType);
public <T> T patchForObject(URI url, Object request, Class<T> responseType) throws RestClientException {
return this.restTemplate.patchForObject(applyRootUriIfNecessary(url), request, responseType);
}
@@ -695,8 +672,7 @@ public class TestRestTemplate {
* @throws RestClientException on client-side HTTP error
* @see RestTemplate#delete(java.lang.String, java.util.Map)
*/
public void delete(String url, Map<String, ?> urlVariables)
throws RestClientException {
public void delete(String url, Map<String, ?> urlVariables) throws RestClientException {
this.restTemplate.delete(url, urlVariables);
}
@@ -720,8 +696,7 @@ public class TestRestTemplate {
* @throws RestClientException on client-side HTTP error
* @see RestTemplate#optionsForAllow(java.lang.String, java.lang.Object[])
*/
public Set<HttpMethod> optionsForAllow(String url, Object... urlVariables)
throws RestClientException {
public Set<HttpMethod> optionsForAllow(String url, Object... urlVariables) throws RestClientException {
return this.restTemplate.optionsForAllow(url, urlVariables);
}
@@ -735,8 +710,7 @@ public class TestRestTemplate {
* @throws RestClientException on client-side HTTP error
* @see RestTemplate#optionsForAllow(java.lang.String, java.util.Map)
*/
public Set<HttpMethod> optionsForAllow(String url, Map<String, ?> urlVariables)
throws RestClientException {
public Set<HttpMethod> optionsForAllow(String url, Map<String, ?> urlVariables) throws RestClientException {
return this.restTemplate.optionsForAllow(url, urlVariables);
}
@@ -768,11 +742,9 @@ public class TestRestTemplate {
* @see RestTemplate#exchange(java.lang.String, org.springframework.http.HttpMethod,
* org.springframework.http.HttpEntity, java.lang.Class, java.lang.Object[])
*/
public <T> ResponseEntity<T> exchange(String url, HttpMethod method,
HttpEntity<?> requestEntity, Class<T> responseType, Object... urlVariables)
throws RestClientException {
return this.restTemplate.exchange(url, method, requestEntity, responseType,
urlVariables);
public <T> ResponseEntity<T> exchange(String url, HttpMethod method, HttpEntity<?> requestEntity,
Class<T> responseType, Object... urlVariables) throws RestClientException {
return this.restTemplate.exchange(url, method, requestEntity, responseType, urlVariables);
}
/**
@@ -792,11 +764,9 @@ public class TestRestTemplate {
* @see RestTemplate#exchange(java.lang.String, org.springframework.http.HttpMethod,
* org.springframework.http.HttpEntity, java.lang.Class, java.util.Map)
*/
public <T> ResponseEntity<T> exchange(String url, HttpMethod method,
HttpEntity<?> requestEntity, Class<T> responseType,
Map<String, ?> urlVariables) throws RestClientException {
return this.restTemplate.exchange(url, method, requestEntity, responseType,
urlVariables);
public <T> ResponseEntity<T> exchange(String url, HttpMethod method, HttpEntity<?> requestEntity,
Class<T> responseType, Map<String, ?> urlVariables) throws RestClientException {
return this.restTemplate.exchange(url, method, requestEntity, responseType, urlVariables);
}
/**
@@ -813,11 +783,9 @@ public class TestRestTemplate {
* @see RestTemplate#exchange(java.net.URI, org.springframework.http.HttpMethod,
* org.springframework.http.HttpEntity, java.lang.Class)
*/
public <T> ResponseEntity<T> exchange(URI url, HttpMethod method,
HttpEntity<?> requestEntity, Class<T> responseType)
throws RestClientException {
return this.restTemplate.exchange(applyRootUriIfNecessary(url), method,
requestEntity, responseType);
public <T> ResponseEntity<T> exchange(URI url, HttpMethod method, HttpEntity<?> requestEntity,
Class<T> responseType) throws RestClientException {
return this.restTemplate.exchange(applyRootUriIfNecessary(url), method, requestEntity, responseType);
}
/**
@@ -841,11 +809,9 @@ public class TestRestTemplate {
* org.springframework.http.HttpEntity,
* org.springframework.core.ParameterizedTypeReference, java.lang.Object[])
*/
public <T> ResponseEntity<T> exchange(String url, HttpMethod method,
HttpEntity<?> requestEntity, ParameterizedTypeReference<T> responseType,
Object... urlVariables) throws RestClientException {
return this.restTemplate.exchange(url, method, requestEntity, responseType,
urlVariables);
public <T> ResponseEntity<T> exchange(String url, HttpMethod method, HttpEntity<?> requestEntity,
ParameterizedTypeReference<T> responseType, Object... urlVariables) throws RestClientException {
return this.restTemplate.exchange(url, method, requestEntity, responseType, urlVariables);
}
/**
@@ -869,11 +835,9 @@ public class TestRestTemplate {
* org.springframework.http.HttpEntity,
* org.springframework.core.ParameterizedTypeReference, java.util.Map)
*/
public <T> ResponseEntity<T> exchange(String url, HttpMethod method,
HttpEntity<?> requestEntity, ParameterizedTypeReference<T> responseType,
Map<String, ?> urlVariables) throws RestClientException {
return this.restTemplate.exchange(url, method, requestEntity, responseType,
urlVariables);
public <T> ResponseEntity<T> exchange(String url, HttpMethod method, HttpEntity<?> requestEntity,
ParameterizedTypeReference<T> responseType, Map<String, ?> urlVariables) throws RestClientException {
return this.restTemplate.exchange(url, method, requestEntity, responseType, urlVariables);
}
/**
@@ -896,11 +860,9 @@ public class TestRestTemplate {
* org.springframework.http.HttpEntity,
* org.springframework.core.ParameterizedTypeReference)
*/
public <T> ResponseEntity<T> exchange(URI url, HttpMethod method,
HttpEntity<?> requestEntity, ParameterizedTypeReference<T> responseType)
throws RestClientException {
return this.restTemplate.exchange(applyRootUriIfNecessary(url), method,
requestEntity, responseType);
public <T> ResponseEntity<T> exchange(URI url, HttpMethod method, HttpEntity<?> requestEntity,
ParameterizedTypeReference<T> responseType) throws RestClientException {
return this.restTemplate.exchange(applyRootUriIfNecessary(url), method, requestEntity, responseType);
}
/**
@@ -918,10 +880,9 @@ public class TestRestTemplate {
* @throws RestClientException on client-side HTTP error
* @see RestTemplate#exchange(org.springframework.http.RequestEntity, java.lang.Class)
*/
public <T> ResponseEntity<T> exchange(RequestEntity<?> requestEntity,
Class<T> responseType) throws RestClientException {
return this.restTemplate.exchange(
createRequestEntityWithRootAppliedUri(requestEntity), responseType);
public <T> ResponseEntity<T> exchange(RequestEntity<?> requestEntity, Class<T> responseType)
throws RestClientException {
return this.restTemplate.exchange(createRequestEntityWithRootAppliedUri(requestEntity), responseType);
}
/**
@@ -941,10 +902,9 @@ public class TestRestTemplate {
* @see RestTemplate#exchange(org.springframework.http.RequestEntity,
* org.springframework.core.ParameterizedTypeReference)
*/
public <T> ResponseEntity<T> exchange(RequestEntity<?> requestEntity,
ParameterizedTypeReference<T> responseType) throws RestClientException {
return this.restTemplate.exchange(
createRequestEntityWithRootAppliedUri(requestEntity), responseType);
public <T> ResponseEntity<T> exchange(RequestEntity<?> requestEntity, ParameterizedTypeReference<T> responseType)
throws RestClientException {
return this.restTemplate.exchange(createRequestEntityWithRootAppliedUri(requestEntity), responseType);
}
/**
@@ -965,10 +925,8 @@ public class TestRestTemplate {
* org.springframework.web.client.ResponseExtractor, java.lang.Object[])
*/
public <T> T execute(String url, HttpMethod method, RequestCallback requestCallback,
ResponseExtractor<T> responseExtractor, Object... urlVariables)
throws RestClientException {
return this.restTemplate.execute(url, method, requestCallback, responseExtractor,
urlVariables);
ResponseExtractor<T> responseExtractor, Object... urlVariables) throws RestClientException {
return this.restTemplate.execute(url, method, requestCallback, responseExtractor, urlVariables);
}
/**
@@ -989,10 +947,8 @@ public class TestRestTemplate {
* org.springframework.web.client.ResponseExtractor, java.util.Map)
*/
public <T> T execute(String url, HttpMethod method, RequestCallback requestCallback,
ResponseExtractor<T> responseExtractor, Map<String, ?> urlVariables)
throws RestClientException {
return this.restTemplate.execute(url, method, requestCallback, responseExtractor,
urlVariables);
ResponseExtractor<T> responseExtractor, Map<String, ?> urlVariables) throws RestClientException {
return this.restTemplate.execute(url, method, requestCallback, responseExtractor, urlVariables);
}
/**
@@ -1011,8 +967,7 @@ public class TestRestTemplate {
*/
public <T> T execute(URI url, HttpMethod method, RequestCallback requestCallback,
ResponseExtractor<T> responseExtractor) throws RestClientException {
return this.restTemplate.execute(applyRootUriIfNecessary(url), method,
requestCallback, responseExtractor);
return this.restTemplate.execute(applyRootUriIfNecessary(url), method, requestCallback, responseExtractor);
}
/**
@@ -1035,23 +990,20 @@ public class TestRestTemplate {
* @since 1.4.1
*/
public TestRestTemplate withBasicAuth(String username, String password) {
RestTemplate restTemplate = new RestTemplateBuilder()
.requestFactory(getRequestFactorySupplier())
RestTemplate restTemplate = new RestTemplateBuilder().requestFactory(getRequestFactorySupplier())
.messageConverters(getRestTemplate().getMessageConverters())
.interceptors(getRestTemplate().getInterceptors())
.uriTemplateHandler(getRestTemplate().getUriTemplateHandler()).build();
TestRestTemplate testRestTemplate = new TestRestTemplate(restTemplate, username,
password, this.httpClientOptions);
testRestTemplate.getRestTemplate()
.setErrorHandler(getRestTemplate().getErrorHandler());
TestRestTemplate testRestTemplate = new TestRestTemplate(restTemplate, username, password,
this.httpClientOptions);
testRestTemplate.getRestTemplate().setErrorHandler(getRestTemplate().getErrorHandler());
return testRestTemplate;
}
private Supplier<ClientHttpRequestFactory> getRequestFactorySupplier() {
return () -> {
try {
return BeanUtils
.instantiateClass(getRequestFactoryClass(getRestTemplate()));
return BeanUtils.instantiateClass(getRequestFactoryClass(getRestTemplate()));
}
catch (BeanInstantiationException ex) {
return new ClientHttpRequestFactorySupplier().get();
@@ -1060,19 +1012,15 @@ public class TestRestTemplate {
}
@SuppressWarnings({ "rawtypes", "unchecked" })
private RequestEntity<?> createRequestEntityWithRootAppliedUri(
RequestEntity<?> requestEntity) {
return new RequestEntity(requestEntity.getBody(), requestEntity.getHeaders(),
requestEntity.getMethod(),
private RequestEntity<?> createRequestEntityWithRootAppliedUri(RequestEntity<?> requestEntity) {
return new RequestEntity(requestEntity.getBody(), requestEntity.getHeaders(), requestEntity.getMethod(),
applyRootUriIfNecessary(requestEntity.getUrl()), requestEntity.getType());
}
private URI applyRootUriIfNecessary(URI uri) {
UriTemplateHandler uriTemplateHandler = this.restTemplate.getUriTemplateHandler();
if ((uriTemplateHandler instanceof RootUriTemplateHandler)
&& uri.toString().startsWith("/")) {
return URI.create(((RootUriTemplateHandler) uriTemplateHandler).getRootUri()
+ uri.toString());
if ((uriTemplateHandler instanceof RootUriTemplateHandler) && uri.toString().startsWith("/")) {
return URI.create(((RootUriTemplateHandler) uriTemplateHandler).getRootUri() + uri.toString());
}
return uri;
}
@@ -1102,19 +1050,16 @@ public class TestRestTemplate {
/**
* {@link HttpComponentsClientHttpRequestFactory} to apply customizations.
*/
protected static class CustomHttpComponentsClientHttpRequestFactory
extends HttpComponentsClientHttpRequestFactory {
protected static class CustomHttpComponentsClientHttpRequestFactory extends HttpComponentsClientHttpRequestFactory {
private final String cookieSpec;
private final boolean enableRedirects;
public CustomHttpComponentsClientHttpRequestFactory(
HttpClientOption[] httpClientOptions) {
Set<HttpClientOption> options = new HashSet<>(
Arrays.asList(httpClientOptions));
this.cookieSpec = (options.contains(HttpClientOption.ENABLE_COOKIES)
? CookieSpecs.STANDARD : CookieSpecs.IGNORE_COOKIES);
public CustomHttpComponentsClientHttpRequestFactory(HttpClientOption[] httpClientOptions) {
Set<HttpClientOption> options = new HashSet<>(Arrays.asList(httpClientOptions));
this.cookieSpec = (options.contains(HttpClientOption.ENABLE_COOKIES) ? CookieSpecs.STANDARD
: CookieSpecs.IGNORE_COOKIES);
this.enableRedirects = options.contains(HttpClientOption.ENABLE_REDIRECTS);
if (options.contains(HttpClientOption.SSL)) {
setHttpClient(createSslHttpClient());
@@ -1124,9 +1069,7 @@ public class TestRestTemplate {
private HttpClient createSslHttpClient() {
try {
SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(
new SSLContextBuilder()
.loadTrustMaterial(null, new TrustSelfSignedStrategy())
.build());
new SSLContextBuilder().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build());
return HttpClients.custom().setSSLSocketFactory(socketFactory).build();
}
catch (Exception ex) {
@@ -1142,8 +1085,7 @@ public class TestRestTemplate {
}
protected RequestConfig getRequestConfig() {
Builder builder = RequestConfig.custom().setCookieSpec(this.cookieSpec)
.setAuthenticationEnabled(false)
Builder builder = RequestConfig.custom().setCookieSpec(this.cookieSpec).setAuthenticationEnabled(false)
.setRedirectsEnabled(this.enableRedirects);
return builder.build();
}

View File

@@ -52,8 +52,8 @@ class TestRestTemplateContextCustomizer implements ContextCustomizer {
@Override
public void customizeContext(ConfigurableApplicationContext context,
MergedContextConfiguration mergedContextConfiguration) {
SpringBootTest annotation = AnnotatedElementUtils.getMergedAnnotation(
mergedContextConfiguration.getTestClass(), SpringBootTest.class);
SpringBootTest annotation = AnnotatedElementUtils.getMergedAnnotation(mergedContextConfiguration.getTestClass(),
SpringBootTest.class);
if (annotation.webEnvironment().isEmbedded()) {
registerTestRestTemplate(context);
}
@@ -67,11 +67,9 @@ class TestRestTemplateContextCustomizer implements ContextCustomizer {
}
private void registerTestRestTemplate(BeanDefinitionRegistry registry) {
RootBeanDefinition definition = new RootBeanDefinition(
TestRestTemplateRegistrar.class);
RootBeanDefinition definition = new RootBeanDefinition(TestRestTemplateRegistrar.class);
definition.setRole(BeanDefinition.ROLE_INFRASTRUCTURE);
registry.registerBeanDefinition(TestRestTemplateRegistrar.class.getName(),
definition);
registry.registerBeanDefinition(TestRestTemplateRegistrar.class.getName(), definition);
}
@Override
@@ -108,11 +106,9 @@ class TestRestTemplateContextCustomizer implements ContextCustomizer {
}
@Override
public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry)
throws BeansException {
if (BeanFactoryUtils.beanNamesForTypeIncludingAncestors(
(ListableBeanFactory) this.beanFactory, TestRestTemplate.class, false,
false).length == 0) {
public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {
if (BeanFactoryUtils.beanNamesForTypeIncludingAncestors((ListableBeanFactory) this.beanFactory,
TestRestTemplate.class, false, false).length == 0) {
registry.registerBeanDefinition(TestRestTemplate.class.getName(),
new RootBeanDefinition(TestRestTemplateFactory.class));
}
@@ -120,8 +116,7 @@ class TestRestTemplateContextCustomizer implements ContextCustomizer {
}
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory)
throws BeansException {
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
}
}
@@ -129,8 +124,7 @@ class TestRestTemplateContextCustomizer implements ContextCustomizer {
/**
* {@link FactoryBean} used to create and configure a {@link TestRestTemplate}.
*/
public static class TestRestTemplateFactory
implements FactoryBean<TestRestTemplate>, ApplicationContextAware {
public static class TestRestTemplateFactory implements FactoryBean<TestRestTemplate>, ApplicationContextAware {
private static final HttpClientOption[] DEFAULT_OPTIONS = {};
@@ -139,14 +133,13 @@ class TestRestTemplateContextCustomizer implements ContextCustomizer {
private TestRestTemplate template;
@Override
public void setApplicationContext(ApplicationContext applicationContext)
throws BeansException {
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
RestTemplateBuilder builder = getRestTemplateBuilder(applicationContext);
boolean sslEnabled = isSslEnabled(applicationContext);
TestRestTemplate template = new TestRestTemplate(builder, null, null,
sslEnabled ? SSL_OPTIONS : DEFAULT_OPTIONS);
LocalHostUriTemplateHandler handler = new LocalHostUriTemplateHandler(
applicationContext.getEnvironment(), sslEnabled ? "https" : "http");
LocalHostUriTemplateHandler handler = new LocalHostUriTemplateHandler(applicationContext.getEnvironment(),
sslEnabled ? "https" : "http");
template.setUriTemplateHandler(handler);
this.template = template;
}
@@ -155,16 +148,14 @@ class TestRestTemplateContextCustomizer implements ContextCustomizer {
try {
AbstractServletWebServerFactory webServerFactory = context
.getBean(AbstractServletWebServerFactory.class);
return webServerFactory.getSsl() != null
&& webServerFactory.getSsl().isEnabled();
return webServerFactory.getSsl() != null && webServerFactory.getSsl().isEnabled();
}
catch (NoSuchBeanDefinitionException ex) {
return false;
}
}
private RestTemplateBuilder getRestTemplateBuilder(
ApplicationContext applicationContext) {
private RestTemplateBuilder getRestTemplateBuilder(ApplicationContext applicationContext) {
try {
return applicationContext.getBean(RestTemplateBuilder.class);
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -35,8 +35,7 @@ class TestRestTemplateContextCustomizerFactory implements ContextCustomizerFacto
@Override
public ContextCustomizer createContextCustomizer(Class<?> testClass,
List<ContextConfigurationAttributes> configAttributes) {
if (AnnotatedElementUtils.findMergedAnnotation(testClass,
SpringBootTest.class) != null) {
if (AnnotatedElementUtils.findMergedAnnotation(testClass, SpringBootTest.class) != null) {
return new TestRestTemplateContextCustomizer();
}
return null;

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2017 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -39,22 +39,19 @@ public class LocalHostWebConnectionHtmlUnitDriver extends WebConnectionHtmlUnitD
this.environment = environment;
}
public LocalHostWebConnectionHtmlUnitDriver(Environment environment,
boolean enableJavascript) {
public LocalHostWebConnectionHtmlUnitDriver(Environment environment, boolean enableJavascript) {
super(enableJavascript);
Assert.notNull(environment, "Environment must not be null");
this.environment = environment;
}
public LocalHostWebConnectionHtmlUnitDriver(Environment environment,
BrowserVersion browserVersion) {
public LocalHostWebConnectionHtmlUnitDriver(Environment environment, BrowserVersion browserVersion) {
super(browserVersion);
Assert.notNull(environment, "Environment must not be null");
this.environment = environment;
}
public LocalHostWebConnectionHtmlUnitDriver(Environment environment,
Capabilities capabilities) {
public LocalHostWebConnectionHtmlUnitDriver(Environment environment, Capabilities capabilities) {
super(capabilities);
Assert.notNull(environment, "Environment must not be null");
this.environment = environment;

View File

@@ -53,10 +53,9 @@ import org.springframework.web.reactive.function.client.ExchangeStrategies;
class WebTestClientContextCustomizer implements ContextCustomizer {
@Override
public void customizeContext(ConfigurableApplicationContext context,
MergedContextConfiguration mergedConfig) {
SpringBootTest annotation = AnnotatedElementUtils
.getMergedAnnotation(mergedConfig.getTestClass(), SpringBootTest.class);
public void customizeContext(ConfigurableApplicationContext context, MergedContextConfiguration mergedConfig) {
SpringBootTest annotation = AnnotatedElementUtils.getMergedAnnotation(mergedConfig.getTestClass(),
SpringBootTest.class);
if (annotation.webEnvironment().isEmbedded()) {
registerWebTestClient(context);
}
@@ -70,11 +69,9 @@ class WebTestClientContextCustomizer implements ContextCustomizer {
}
private void registerWebTestClient(BeanDefinitionRegistry registry) {
RootBeanDefinition definition = new RootBeanDefinition(
WebTestClientRegistrar.class);
RootBeanDefinition definition = new RootBeanDefinition(WebTestClientRegistrar.class);
definition.setRole(BeanDefinition.ROLE_INFRASTRUCTURE);
registry.registerBeanDefinition(WebTestClientRegistrar.class.getName(),
definition);
registry.registerBeanDefinition(WebTestClientRegistrar.class.getName(), definition);
}
@Override
@@ -108,11 +105,9 @@ class WebTestClientContextCustomizer implements ContextCustomizer {
}
@Override
public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry)
throws BeansException {
if (BeanFactoryUtils.beanNamesForTypeIncludingAncestors(
(ListableBeanFactory) this.beanFactory, WebTestClient.class, false,
false).length == 0) {
public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {
if (BeanFactoryUtils.beanNamesForTypeIncludingAncestors((ListableBeanFactory) this.beanFactory,
WebTestClient.class, false, false).length == 0) {
registry.registerBeanDefinition(WebTestClient.class.getName(),
new RootBeanDefinition(WebTestClientFactory.class));
}
@@ -120,8 +115,7 @@ class WebTestClientContextCustomizer implements ContextCustomizer {
}
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory)
throws BeansException {
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
}
}
@@ -129,16 +123,14 @@ class WebTestClientContextCustomizer implements ContextCustomizer {
/**
* {@link FactoryBean} used to create and configure a {@link WebTestClient}.
*/
public static class WebTestClientFactory
implements FactoryBean<WebTestClient>, ApplicationContextAware {
public static class WebTestClientFactory implements FactoryBean<WebTestClient>, ApplicationContextAware {
private ApplicationContext applicationContext;
private WebTestClient object;
@Override
public void setApplicationContext(ApplicationContext applicationContext)
throws BeansException {
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
@@ -162,8 +154,7 @@ class WebTestClientContextCustomizer implements ContextCustomizer {
private WebTestClient createWebTestClient() {
boolean sslEnabled = isSslEnabled(this.applicationContext);
String port = this.applicationContext.getEnvironment()
.getProperty("local.server.port", "8080");
String port = this.applicationContext.getEnvironment().getProperty("local.server.port", "8080");
String baseUrl = (sslEnabled ? "https" : "http") + "://localhost:" + port;
WebTestClient.Builder builder = WebTestClient.bindToServer();
customizeWebTestClientCodecs(builder, this.applicationContext);
@@ -174,22 +165,18 @@ class WebTestClientContextCustomizer implements ContextCustomizer {
try {
AbstractReactiveWebServerFactory webServerFactory = context
.getBean(AbstractReactiveWebServerFactory.class);
return webServerFactory.getSsl() != null
&& webServerFactory.getSsl().isEnabled();
return webServerFactory.getSsl() != null && webServerFactory.getSsl().isEnabled();
}
catch (NoSuchBeanDefinitionException ex) {
return false;
}
}
private void customizeWebTestClientCodecs(WebTestClient.Builder clientBuilder,
ApplicationContext context) {
Collection<CodecCustomizer> codecCustomizers = context
.getBeansOfType(CodecCustomizer.class).values();
private void customizeWebTestClientCodecs(WebTestClient.Builder clientBuilder, ApplicationContext context) {
Collection<CodecCustomizer> codecCustomizers = context.getBeansOfType(CodecCustomizer.class).values();
if (!CollectionUtils.isEmpty(codecCustomizers)) {
clientBuilder.exchangeStrategies(ExchangeStrategies.builder()
.codecs((codecs) -> codecCustomizers.forEach(
(codecCustomizer) -> codecCustomizer.customize(codecs)))
clientBuilder.exchangeStrategies(ExchangeStrategies.builder().codecs(
(codecs) -> codecCustomizers.forEach((codecCustomizer) -> codecCustomizer.customize(codecs)))
.build());
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -37,8 +37,8 @@ class WebTestClientContextCustomizerFactory implements ContextCustomizerFactory
@Override
public ContextCustomizer createContextCustomizer(Class<?> testClass,
List<ContextConfigurationAttributes> configAttributes) {
if (isWebClientPresent() && AnnotatedElementUtils.findMergedAnnotation(testClass,
SpringBootTest.class) != null) {
if (isWebClientPresent()
&& AnnotatedElementUtils.findMergedAnnotation(testClass, SpringBootTest.class) != null) {
return new WebTestClientContextCustomizer();
}
return null;