Merge branch '2.1.x'
Closes gh-17079
This commit is contained in:
@@ -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);
|
||||
}
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -75,24 +75,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);
|
||||
}
|
||||
|
||||
@@ -101,14 +97,13 @@ 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");
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
@@ -165,12 +160,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;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -180,8 +172,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();
|
||||
|
||||
@@ -192,13 +183,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) {
|
||||
@@ -243,12 +232,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()) {
|
||||
@@ -260,13 +247,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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -280,15 +266,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 = AnnotationMetadata
|
||||
.introspect(testClass);
|
||||
AnnotationMetadata testClassMetadata = AnnotationMetadata.introspect(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;
|
||||
}
|
||||
@@ -305,12 +288,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)) {
|
||||
@@ -330,17 +311,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
|
||||
|
||||
@@ -41,8 +41,7 @@ class ImportsContextCustomizerFactory implements ContextCustomizerFactory {
|
||||
@Override
|
||||
public ContextCustomizer createContextCustomizer(Class<?> testClass,
|
||||
List<ContextConfigurationAttributes> configAttributes) {
|
||||
if (MergedAnnotations.from(testClass, SearchStrategy.EXHAUSTIVE)
|
||||
.isPresent(Import.class)) {
|
||||
if (MergedAnnotations.from(testClass, SearchStrategy.EXHAUSTIVE).isPresent(Import.class)) {
|
||||
assertHasNoBeanMethods(testClass);
|
||||
return new ImportsContextCustomizer(testClass);
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
|
||||
@@ -83,18 +83,13 @@ public class SpringBootContextLoader extends AbstractContextLoader {
|
||||
private static final String[] NO_ARGS = new String[0];
|
||||
|
||||
@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));
|
||||
@@ -103,16 +98,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)) {
|
||||
@@ -158,16 +150,12 @@ public class SpringBootContextLoader extends AbstractContextLoader {
|
||||
* @see SpringApplication#run(String...)
|
||||
*/
|
||||
protected String[] getArgs(MergedContextConfiguration config) {
|
||||
return MergedAnnotations.from(config.getTestClass(), SearchStrategy.EXHAUSTIVE)
|
||||
.get(SpringBootTest.class).getValue("args", String[].class)
|
||||
.orElse(NO_ARGS);
|
||||
return MergedAnnotations.from(config.getTestClass(), SearchStrategy.EXHAUSTIVE).get(SpringBootTest.class)
|
||||
.getValue("args", String[].class).orElse(NO_ARGS);
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
@@ -191,10 +179,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)));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -209,8 +196,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));
|
||||
@@ -221,26 +208,21 @@ 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) {
|
||||
return MergedAnnotations.from(config.getTestClass(), SearchStrategy.EXHAUSTIVE)
|
||||
.get(SpringBootTest.class)
|
||||
.getValue("webEnvironment", WebEnvironment.class)
|
||||
.orElse(WebEnvironment.NONE).isEmbedded();
|
||||
return MergedAnnotations.from(config.getTestClass(), SearchStrategy.EXHAUSTIVE).get(SpringBootTest.class)
|
||||
.getValue("webEnvironment", WebEnvironment.class).orElse(WebEnvironment.NONE).isEmbedded();
|
||||
}
|
||||
|
||||
@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);
|
||||
}
|
||||
}
|
||||
@@ -255,14 +237,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
|
||||
@@ -282,21 +263,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));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -325,8 +303,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;
|
||||
}
|
||||
|
||||
@@ -84,24 +84,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()) {
|
||||
@@ -114,8 +111,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);
|
||||
}
|
||||
@@ -134,8 +130,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) {
|
||||
@@ -145,51 +140,38 @@ 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)) {
|
||||
String resourceBasePath = MergedAnnotations
|
||||
.from(mergedConfig.getTestClass(), SearchStrategy.EXHAUSTIVE)
|
||||
.get(WebAppConfiguration.class)
|
||||
.getValue(MergedAnnotation.VALUE, String.class)
|
||||
&& (webEnvironment.isEmbedded() || webEnvironment == WebEnvironment.MOCK)) {
|
||||
String resourceBasePath = MergedAnnotations.from(mergedConfig.getTestClass(), SearchStrategy.EXHAUSTIVE)
|
||||
.get(WebAppConfiguration.class).getValue(MergedAnnotation.VALUE, String.class)
|
||||
.orElse("src/main/webapp");
|
||||
mergedConfig = new WebMergedContextConfiguration(mergedConfig,
|
||||
resourceBasePath);
|
||||
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);
|
||||
}
|
||||
|
||||
@@ -209,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;
|
||||
@@ -233,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);
|
||||
}
|
||||
|
||||
@@ -267,8 +242,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();
|
||||
@@ -296,8 +270,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);
|
||||
@@ -332,26 +305,22 @@ public class SpringBootTestContextBootstrapper extends DefaultTestContextBootstr
|
||||
}
|
||||
|
||||
protected SpringBootTest getAnnotation(Class<?> testClass) {
|
||||
return MergedAnnotations.from(testClass, SearchStrategy.INHERITED_ANNOTATIONS)
|
||||
.get(SpringBootTest.class).synthesize(MergedAnnotation::isPresent)
|
||||
.orElse(null);
|
||||
return MergedAnnotations.from(testClass, SearchStrategy.INHERITED_ANNOTATIONS).get(SpringBootTest.class)
|
||||
.synthesize(MergedAnnotation::isPresent).orElse(null);
|
||||
}
|
||||
|
||||
protected void verifyConfiguration(Class<?> testClass) {
|
||||
SpringBootTest springBootTest = getAnnotation(testClass);
|
||||
if (springBootTest != null && isListeningOnPort(springBootTest.webEnvironment())
|
||||
&& MergedAnnotations.from(testClass, SearchStrategy.INHERITED_ANNOTATIONS)
|
||||
.isPresent(WebAppConfiguration.class)) {
|
||||
if (springBootTest != null && isListeningOnPort(springBootTest.webEnvironment()) && MergedAnnotations
|
||||
.from(testClass, SearchStrategy.INHERITED_ANNOTATIONS).isPresent(WebAppConfiguration.class)) {
|
||||
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 boolean isListeningOnPort(WebEnvironment webEnvironment) {
|
||||
return webEnvironment == WebEnvironment.DEFINED_PORT
|
||||
|| webEnvironment == WebEnvironment.RANDOM_PORT;
|
||||
return webEnvironment == WebEnvironment.DEFINED_PORT || webEnvironment == WebEnvironment.RANDOM_PORT;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -360,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());
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -374,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());
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
|
||||
@@ -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.
|
||||
@@ -101,17 +101,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));
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -36,12 +36,11 @@ class TestTypeExcludeFilter extends TypeExcludeFilter {
|
||||
"org.junit.jupiter.api.extension.ExtendWith", "org.testng.annotations.Test" };
|
||||
|
||||
private static final String[] METHOD_ANNOTATIONS = { "org.junit.Test",
|
||||
"org.junit.platform.commons.annotation.Testable",
|
||||
"org.testng.annotations.Test" };
|
||||
"org.junit.platform.commons.annotation.Testable", "org.testng.annotations.Test" };
|
||||
|
||||
@Override
|
||||
public boolean match(MetadataReader metadataReader,
|
||||
MetadataReaderFactory metadataReaderFactory) throws IOException {
|
||||
public boolean match(MetadataReader metadataReader, MetadataReaderFactory metadataReaderFactory)
|
||||
throws IOException {
|
||||
if (isTestConfiguration(metadataReader)) {
|
||||
return true;
|
||||
}
|
||||
@@ -51,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;
|
||||
}
|
||||
}
|
||||
@@ -64,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) {
|
||||
|
||||
@@ -124,9 +124,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(),
|
||||
Collections.emptyList());
|
||||
this(contextFactory, Collections.emptyList(), TestPropertyValues.empty(), TestPropertyValues.empty(), null,
|
||||
null, Collections.emptyList(), Collections.emptyList());
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -141,11 +140,9 @@ 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<BeanRegistration<?>> beanRegistrations,
|
||||
List<Configurations> configurations) {
|
||||
List<ApplicationContextInitializer<? super C>> initializers, TestPropertyValues environmentProperties,
|
||||
TestPropertyValues systemProperties, ClassLoader classLoader, ApplicationContext parent,
|
||||
List<BeanRegistration<?>> beanRegistrations, List<Configurations> configurations) {
|
||||
Assert.notNull(contextFactory, "ContextFactory must not be null");
|
||||
Assert.notNull(environmentProperties, "EnvironmentProperties must not be null");
|
||||
Assert.notNull(systemProperties, "SystemProperties must not be null");
|
||||
@@ -169,9 +166,8 @@ public abstract class AbstractApplicationContextRunner<SELF extends AbstractAppl
|
||||
*/
|
||||
public SELF withInitializer(ApplicationContextInitializer<? super C> 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.beanRegistrations, this.configurations);
|
||||
return newInstance(this.contextFactory, add(this.initializers, initializer), this.environmentProperties,
|
||||
this.systemProperties, this.classLoader, this.parent, this.beanRegistrations, this.configurations);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -185,10 +181,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.beanRegistrations,
|
||||
this.configurations);
|
||||
return newInstance(this.contextFactory, this.initializers, this.environmentProperties.and(pairs),
|
||||
this.systemProperties, this.classLoader, this.parent, this.beanRegistrations, this.configurations);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -202,9 +196,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.beanRegistrations,
|
||||
return newInstance(this.contextFactory, this.initializers, this.environmentProperties,
|
||||
this.systemProperties.and(pairs), this.classLoader, this.parent, this.beanRegistrations,
|
||||
this.configurations);
|
||||
}
|
||||
|
||||
@@ -216,9 +209,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.beanRegistrations, this.configurations);
|
||||
return newInstance(this.contextFactory, this.initializers, this.environmentProperties, this.systemProperties,
|
||||
classLoader, this.parent, this.beanRegistrations, this.configurations);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -228,9 +220,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.beanRegistrations, this.configurations);
|
||||
return newInstance(this.contextFactory, this.initializers, this.environmentProperties, this.systemProperties,
|
||||
this.classLoader, parent, this.beanRegistrations, this.configurations);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -265,12 +256,9 @@ public abstract class AbstractApplicationContextRunner<SELF extends AbstractAppl
|
||||
* @return a new instance with the updated bean
|
||||
*/
|
||||
public <T> SELF withBean(String name, Class<T> type, Object... constructorArgs) {
|
||||
return newInstance(this.contextFactory, this.initializers,
|
||||
this.environmentProperties, this.systemProperties, this.classLoader,
|
||||
this.parent,
|
||||
add(this.beanRegistrations,
|
||||
new BeanRegistration<>(name, type, constructorArgs)),
|
||||
this.configurations);
|
||||
return newInstance(this.contextFactory, this.initializers, this.environmentProperties, this.systemProperties,
|
||||
this.classLoader, this.parent,
|
||||
add(this.beanRegistrations, new BeanRegistration<>(name, type, constructorArgs)), this.configurations);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -287,8 +275,7 @@ public abstract class AbstractApplicationContextRunner<SELF extends AbstractAppl
|
||||
* @param <T> the type of the bean
|
||||
* @return a new instance with the updated bean
|
||||
*/
|
||||
public <T> SELF withBean(Class<T> type, Supplier<T> supplier,
|
||||
BeanDefinitionCustomizer... customizers) {
|
||||
public <T> SELF withBean(Class<T> type, Supplier<T> supplier, BeanDefinitionCustomizer... customizers) {
|
||||
return withBean(null, type, supplier, customizers);
|
||||
}
|
||||
|
||||
@@ -309,11 +296,9 @@ public abstract class AbstractApplicationContextRunner<SELF extends AbstractAppl
|
||||
*/
|
||||
public <T> SELF withBean(String name, Class<T> type, Supplier<T> supplier,
|
||||
BeanDefinitionCustomizer... customizers) {
|
||||
return newInstance(this.contextFactory, this.initializers,
|
||||
this.environmentProperties, this.systemProperties, this.classLoader,
|
||||
this.parent,
|
||||
add(this.beanRegistrations,
|
||||
new BeanRegistration<>(name, type, supplier, customizers)),
|
||||
return newInstance(this.contextFactory, this.initializers, this.environmentProperties, this.systemProperties,
|
||||
this.classLoader, this.parent,
|
||||
add(this.beanRegistrations, new BeanRegistration<>(name, type, supplier, customizers)),
|
||||
this.configurations);
|
||||
}
|
||||
|
||||
@@ -334,10 +319,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, this.beanRegistrations,
|
||||
add(this.configurations, configurations));
|
||||
return newInstance(this.contextFactory, this.initializers, this.environmentProperties, this.systemProperties,
|
||||
this.classLoader, this.parent, this.beanRegistrations, add(this.configurations, configurations));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -357,11 +340,9 @@ 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<BeanRegistration<?>> beanRegistrations,
|
||||
List<Configurations> configurations);
|
||||
List<ApplicationContextInitializer<? super C>> initializers, TestPropertyValues environmentProperties,
|
||||
TestPropertyValues systemProperties, ClassLoader classLoader, ApplicationContext parent,
|
||||
List<BeanRegistration<?>> beanRegistrations, List<Configurations> configurations);
|
||||
|
||||
/**
|
||||
* Create and refresh a new {@link ApplicationContext} based on the current state of
|
||||
@@ -402,12 +383,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() {
|
||||
@@ -464,14 +443,12 @@ public abstract class AbstractApplicationContextRunner<SELF extends AbstractAppl
|
||||
Consumer<GenericApplicationContext> registrar;
|
||||
|
||||
public BeanRegistration(String name, Class<T> type, Object... constructorArgs) {
|
||||
this.registrar = (context) -> context.registerBean(name, type,
|
||||
constructorArgs);
|
||||
this.registrar = (context) -> context.registerBean(name, type, constructorArgs);
|
||||
}
|
||||
|
||||
public BeanRegistration(String name, Class<T> type, Supplier<T> supplier,
|
||||
BeanDefinitionCustomizer... customizers) {
|
||||
this.registrar = (context) -> context.registerBean(name, type, supplier,
|
||||
customizers);
|
||||
this.registrar = (context) -> context.registerBean(name, type, supplier, customizers);
|
||||
}
|
||||
|
||||
public void apply(ConfigurableApplicationContext context) {
|
||||
|
||||
@@ -54,33 +54,27 @@ 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<BeanRegistration<?>> beanRegistrations,
|
||||
TestPropertyValues environmentProperties, TestPropertyValues systemProperties, ClassLoader classLoader,
|
||||
ApplicationContext parent, List<BeanRegistration<?>> beanRegistrations,
|
||||
List<Configurations> configurations) {
|
||||
super(contextFactory, initializers, environmentProperties, systemProperties,
|
||||
classLoader, parent, beanRegistrations, configurations);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected ApplicationContextRunner newInstance(
|
||||
Supplier<ConfigurableApplicationContext> contextFactory,
|
||||
List<ApplicationContextInitializer<? super ConfigurableApplicationContext>> initializers,
|
||||
TestPropertyValues environmentProperties, TestPropertyValues systemProperties,
|
||||
ClassLoader classLoader, ApplicationContext parent,
|
||||
List<BeanRegistration<?>> beanRegistrations,
|
||||
List<Configurations> configurations) {
|
||||
return new ApplicationContextRunner(contextFactory, initializers,
|
||||
environmentProperties, systemProperties, classLoader, parent,
|
||||
super(contextFactory, initializers, environmentProperties, systemProperties, classLoader, parent,
|
||||
beanRegistrations, configurations);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected ApplicationContextRunner newInstance(Supplier<ConfigurableApplicationContext> contextFactory,
|
||||
List<ApplicationContextInitializer<? super ConfigurableApplicationContext>> initializers,
|
||||
TestPropertyValues environmentProperties, TestPropertyValues systemProperties, ClassLoader classLoader,
|
||||
ApplicationContext parent, List<BeanRegistration<?>> beanRegistrations,
|
||||
List<Configurations> configurations) {
|
||||
return new ApplicationContextRunner(contextFactory, initializers, environmentProperties, systemProperties,
|
||||
classLoader, parent, beanRegistrations, configurations);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -54,33 +54,28 @@ 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<BeanRegistration<?>> beanRegistrations,
|
||||
TestPropertyValues environmentProperties, TestPropertyValues systemProperties, ClassLoader classLoader,
|
||||
ApplicationContext parent, List<BeanRegistration<?>> beanRegistrations,
|
||||
List<Configurations> configurations) {
|
||||
super(contextFactory, initializers, environmentProperties, systemProperties,
|
||||
classLoader, parent, beanRegistrations, configurations);
|
||||
super(contextFactory, initializers, environmentProperties, systemProperties, classLoader, parent,
|
||||
beanRegistrations, configurations);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected ReactiveWebApplicationContextRunner newInstance(
|
||||
Supplier<ConfigurableReactiveWebApplicationContext> contextFactory,
|
||||
List<ApplicationContextInitializer<? super ConfigurableReactiveWebApplicationContext>> initializers,
|
||||
TestPropertyValues environmentProperties, TestPropertyValues systemProperties,
|
||||
ClassLoader classLoader, ApplicationContext parent,
|
||||
List<BeanRegistration<?>> beanRegistrations,
|
||||
TestPropertyValues environmentProperties, TestPropertyValues systemProperties, ClassLoader classLoader,
|
||||
ApplicationContext parent, List<BeanRegistration<?>> beanRegistrations,
|
||||
List<Configurations> configurations) {
|
||||
return new ReactiveWebApplicationContextRunner(contextFactory, initializers,
|
||||
environmentProperties, systemProperties, classLoader, parent,
|
||||
beanRegistrations, configurations);
|
||||
return new ReactiveWebApplicationContextRunner(contextFactory, initializers, environmentProperties,
|
||||
systemProperties, classLoader, parent, beanRegistrations, configurations);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -58,33 +58,27 @@ 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<BeanRegistration<?>> beanRegistrations,
|
||||
TestPropertyValues environmentProperties, TestPropertyValues systemProperties, ClassLoader classLoader,
|
||||
ApplicationContext parent, List<BeanRegistration<?>> beanRegistrations,
|
||||
List<Configurations> configurations) {
|
||||
super(contextFactory, initializers, environmentProperties, systemProperties,
|
||||
classLoader, parent, beanRegistrations, configurations);
|
||||
super(contextFactory, initializers, environmentProperties, systemProperties, classLoader, parent,
|
||||
beanRegistrations, 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<BeanRegistration<?>> beanRegistrations,
|
||||
TestPropertyValues environmentProperties, TestPropertyValues systemProperties, ClassLoader classLoader,
|
||||
ApplicationContext parent, List<BeanRegistration<?>> beanRegistrations,
|
||||
List<Configurations> configurations) {
|
||||
return new WebApplicationContextRunner(contextFactory, initializers,
|
||||
environmentProperties, systemProperties, classLoader, parent,
|
||||
beanRegistrations, configurations);
|
||||
return new WebApplicationContextRunner(contextFactory, initializers, environmentProperties, systemProperties,
|
||||
classLoader, parent, beanRegistrations, configurations);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -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);
|
||||
|
||||
}
|
||||
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -73,8 +73,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());
|
||||
}
|
||||
|
||||
@@ -86,8 +85,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);
|
||||
@@ -218,8 +216,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));
|
||||
}
|
||||
@@ -232,8 +229,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));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -282,8 +278,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));
|
||||
}
|
||||
@@ -296,8 +291,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));
|
||||
}
|
||||
@@ -333,8 +327,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));
|
||||
}
|
||||
|
||||
@@ -345,8 +338,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));
|
||||
}
|
||||
@@ -361,8 +353,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));
|
||||
}
|
||||
@@ -375,8 +366,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));
|
||||
}
|
||||
@@ -412,8 +402,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));
|
||||
}
|
||||
@@ -528,8 +517,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));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -555,8 +543,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));
|
||||
}
|
||||
@@ -619,8 +606,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));
|
||||
}
|
||||
@@ -633,8 +619,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));
|
||||
}
|
||||
@@ -646,8 +631,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));
|
||||
}
|
||||
@@ -659,8 +643,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));
|
||||
}
|
||||
@@ -672,8 +655,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));
|
||||
}
|
||||
@@ -685,8 +667,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));
|
||||
}
|
||||
@@ -701,8 +682,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));
|
||||
}
|
||||
@@ -715,8 +695,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));
|
||||
}
|
||||
@@ -728,8 +707,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));
|
||||
}
|
||||
@@ -753,8 +731,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));
|
||||
}
|
||||
@@ -766,8 +743,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));
|
||||
}
|
||||
@@ -796,8 +772,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;
|
||||
}
|
||||
@@ -811,8 +786,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;
|
||||
}
|
||||
@@ -826,8 +800,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;
|
||||
}
|
||||
@@ -841,8 +814,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;
|
||||
}
|
||||
@@ -855,8 +827,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;
|
||||
}
|
||||
@@ -870,8 +841,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;
|
||||
}
|
||||
@@ -886,8 +856,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;
|
||||
}
|
||||
@@ -901,8 +870,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;
|
||||
}
|
||||
@@ -915,8 +883,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));
|
||||
}
|
||||
|
||||
@@ -928,10 +895,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"));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -942,10 +908,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"));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -956,10 +920,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"));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -972,10 +934,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"));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -989,15 +949,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);
|
||||
@@ -1005,14 +963,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) {
|
||||
@@ -1023,14 +979,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) {
|
||||
@@ -1074,8 +1028,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);
|
||||
@@ -1144,9 +1097,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))));
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -65,8 +65,7 @@ class DefinitionsParser {
|
||||
}
|
||||
|
||||
private void parseElement(AnnotatedElement element) {
|
||||
MergedAnnotations annotations = MergedAnnotations.from(element,
|
||||
SearchStrategy.SUPERCLASS);
|
||||
MergedAnnotations annotations = MergedAnnotations.from(element, SearchStrategy.SUPERCLASS);
|
||||
annotations.stream(MockBean.class).map(MergedAnnotation::synthesize)
|
||||
.forEach((annotation) -> parseMockBeanAnnotation(annotation, element));
|
||||
annotations.stream(SpyBean.class).map(MergedAnnotation::synthesize)
|
||||
@@ -75,16 +74,13 @@ class DefinitionsParser {
|
||||
|
||||
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 +88,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));
|
||||
|
||||
@@ -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() {
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
@@ -459,8 +427,7 @@ public class MockitoPostProcessor extends InstantiationAwareBeanPostProcessorAda
|
||||
* 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();
|
||||
|
||||
@@ -476,14 +443,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;
|
||||
}
|
||||
@@ -492,11 +457,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);
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -105,8 +105,7 @@ class QualifierDefinition {
|
||||
return true;
|
||||
}
|
||||
MergedAnnotations metaAnnotations = MergedAnnotations.from(type);
|
||||
return metaAnnotations.isPresent(MockBean.class)
|
||||
|| metaAnnotations.isPresent(SpyBean.class);
|
||||
return metaAnnotations.isPresent(MockBean.class) || metaAnnotations.isPresent(SpyBean.class);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -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)) {
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -147,8 +147,7 @@ class OutputCapture implements CapturedOutput {
|
||||
|
||||
private final PrintStreamCapture err;
|
||||
|
||||
private final List<CapturedString> capturedStrings = Collections
|
||||
.synchronizedList(new ArrayList<>());
|
||||
private final List<CapturedString> capturedStrings = Collections.synchronizedList(new ArrayList<>());
|
||||
|
||||
SystemCapture() {
|
||||
this.out = new PrintStreamCapture(System.out, this::captureOut);
|
||||
|
||||
@@ -54,8 +54,8 @@ import org.junit.jupiter.api.extension.ParameterResolver;
|
||||
* @since 2.2.0
|
||||
* @see CapturedOutput
|
||||
*/
|
||||
public class OutputCaptureExtension implements BeforeAllCallback, AfterAllCallback,
|
||||
BeforeEachCallback, AfterEachCallback, ParameterResolver {
|
||||
public class OutputCaptureExtension
|
||||
implements BeforeAllCallback, AfterAllCallback, BeforeEachCallback, AfterEachCallback, ParameterResolver {
|
||||
|
||||
private final OutputCapture outputCapture = new OutputCapture();
|
||||
|
||||
@@ -84,14 +84,14 @@ public class OutputCaptureExtension implements BeforeAllCallback, AfterAllCallba
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean supportsParameter(ParameterContext parameterContext,
|
||||
ExtensionContext extensionContext) throws ParameterResolutionException {
|
||||
public boolean supportsParameter(ParameterContext parameterContext, ExtensionContext extensionContext)
|
||||
throws ParameterResolutionException {
|
||||
return CapturedOutput.class.equals(parameterContext.getParameter().getType());
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object resolveParameter(ParameterContext parameterContext,
|
||||
ExtensionContext extensionContext) throws ParameterResolutionException {
|
||||
public Object resolveParameter(ParameterContext parameterContext, ExtensionContext extensionContext)
|
||||
throws ParameterResolutionException {
|
||||
return this.outputCapture;
|
||||
}
|
||||
|
||||
|
||||
@@ -53,8 +53,7 @@ public class OutputCaptureRule implements TestRule {
|
||||
try {
|
||||
if (!OutputCaptureRule.this.matchers.isEmpty()) {
|
||||
String output = OutputCaptureRule.this.delegate.toString();
|
||||
Assert.assertThat(output,
|
||||
allOf(OutputCaptureRule.this.matchers));
|
||||
Assert.assertThat(output, allOf(OutputCaptureRule.this.matchers));
|
||||
}
|
||||
}
|
||||
finally {
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
@@ -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");
|
||||
|
||||
@@ -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();
|
||||
}
|
||||
|
||||
|
||||
@@ -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;
|
||||
|
||||
|
||||
@@ -109,8 +109,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);
|
||||
}
|
||||
|
||||
@@ -130,9 +129,8 @@ public class TestRestTemplate {
|
||||
if (httpClientOptions != null) {
|
||||
ClientHttpRequestFactory requestFactory = builder.buildRequestFactory();
|
||||
if (requestFactory instanceof HttpComponentsClientHttpRequestFactory) {
|
||||
builder = builder.requestFactory(
|
||||
() -> new CustomHttpComponentsClientHttpRequestFactory(
|
||||
httpClientOptions));
|
||||
builder = builder
|
||||
.requestFactory(() -> new CustomHttpComponentsClientHttpRequestFactory(httpClientOptions));
|
||||
}
|
||||
}
|
||||
if (username != null || password != null) {
|
||||
@@ -180,8 +178,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);
|
||||
}
|
||||
|
||||
@@ -198,8 +195,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);
|
||||
}
|
||||
|
||||
@@ -231,8 +228,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);
|
||||
}
|
||||
|
||||
@@ -249,8 +246,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);
|
||||
}
|
||||
|
||||
@@ -264,8 +261,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);
|
||||
}
|
||||
|
||||
@@ -279,8 +275,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);
|
||||
}
|
||||
|
||||
@@ -294,8 +289,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);
|
||||
}
|
||||
|
||||
@@ -328,8 +322,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);
|
||||
}
|
||||
|
||||
@@ -351,8 +344,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);
|
||||
}
|
||||
|
||||
@@ -393,8 +385,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);
|
||||
}
|
||||
|
||||
@@ -417,8 +409,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);
|
||||
}
|
||||
|
||||
@@ -437,10 +429,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);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -462,8 +452,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);
|
||||
}
|
||||
|
||||
@@ -486,9 +476,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);
|
||||
}
|
||||
|
||||
@@ -507,10 +496,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);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -527,8 +515,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);
|
||||
}
|
||||
|
||||
@@ -546,8 +533,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);
|
||||
}
|
||||
|
||||
@@ -584,8 +570,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);
|
||||
}
|
||||
|
||||
@@ -607,8 +593,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);
|
||||
}
|
||||
|
||||
@@ -627,10 +613,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);
|
||||
|
||||
}
|
||||
|
||||
@@ -656,8 +640,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);
|
||||
}
|
||||
|
||||
@@ -681,8 +664,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);
|
||||
}
|
||||
|
||||
@@ -696,8 +678,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);
|
||||
}
|
||||
|
||||
@@ -729,11 +710,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);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -753,11 +732,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);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -774,11 +751,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);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -802,11 +777,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);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -830,11 +803,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);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -857,11 +828,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);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -879,10 +848,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);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -902,10 +870,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);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -926,10 +893,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);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -950,10 +915,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);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -972,8 +935,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);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -996,26 +958,21 @@ public class TestRestTemplate {
|
||||
* @since 1.4.1
|
||||
*/
|
||||
public TestRestTemplate withBasicAuth(String username, String password) {
|
||||
TestRestTemplate template = new TestRestTemplate(this.builder, username, password,
|
||||
this.httpClientOptions);
|
||||
TestRestTemplate template = new TestRestTemplate(this.builder, username, password, this.httpClientOptions);
|
||||
template.setUriTemplateHandler(getRestTemplate().getUriTemplateHandler());
|
||||
return template;
|
||||
}
|
||||
|
||||
@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;
|
||||
}
|
||||
@@ -1045,19 +1002,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());
|
||||
@@ -1067,9 +1021,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) {
|
||||
@@ -1085,8 +1037,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();
|
||||
}
|
||||
|
||||
@@ -56,8 +56,7 @@ class TestRestTemplateContextCustomizer implements ContextCustomizer {
|
||||
public void customizeContext(ConfigurableApplicationContext context,
|
||||
MergedContextConfiguration mergedContextConfiguration) {
|
||||
MergedAnnotation<?> annotation = MergedAnnotations
|
||||
.from(mergedContextConfiguration.getTestClass(),
|
||||
SearchStrategy.INHERITED_ANNOTATIONS)
|
||||
.from(mergedContextConfiguration.getTestClass(), SearchStrategy.INHERITED_ANNOTATIONS)
|
||||
.get(SpringBootTest.class);
|
||||
if (annotation.getEnum("webEnvironment", WebEnvironment.class).isEmbedded()) {
|
||||
registerTestRestTemplate(context);
|
||||
@@ -72,11 +71,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
|
||||
@@ -113,11 +110,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));
|
||||
}
|
||||
@@ -125,8 +120,7 @@ class TestRestTemplateContextCustomizer implements ContextCustomizer {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory)
|
||||
throws BeansException {
|
||||
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
|
||||
}
|
||||
|
||||
}
|
||||
@@ -134,8 +128,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 = {};
|
||||
|
||||
@@ -144,14 +137,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;
|
||||
}
|
||||
@@ -160,16 +152,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);
|
||||
}
|
||||
|
||||
@@ -36,8 +36,7 @@ class TestRestTemplateContextCustomizerFactory implements ContextCustomizerFacto
|
||||
@Override
|
||||
public ContextCustomizer createContextCustomizer(Class<?> testClass,
|
||||
List<ContextConfigurationAttributes> configAttributes) {
|
||||
MergedAnnotations annotations = MergedAnnotations.from(testClass,
|
||||
SearchStrategy.INHERITED_ANNOTATIONS);
|
||||
MergedAnnotations annotations = MergedAnnotations.from(testClass, SearchStrategy.INHERITED_ANNOTATIONS);
|
||||
if (annotations.isPresent(SpringBootTest.class)) {
|
||||
return new TestRestTemplateContextCustomizer();
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -56,11 +56,9 @@ import org.springframework.web.reactive.function.client.ExchangeStrategies;
|
||||
class WebTestClientContextCustomizer implements ContextCustomizer {
|
||||
|
||||
@Override
|
||||
public void customizeContext(ConfigurableApplicationContext context,
|
||||
MergedContextConfiguration mergedConfig) {
|
||||
public void customizeContext(ConfigurableApplicationContext context, MergedContextConfiguration mergedConfig) {
|
||||
MergedAnnotation<?> annotation = MergedAnnotations
|
||||
.from(mergedConfig.getTestClass(), SearchStrategy.INHERITED_ANNOTATIONS)
|
||||
.get(SpringBootTest.class);
|
||||
.from(mergedConfig.getTestClass(), SearchStrategy.INHERITED_ANNOTATIONS).get(SpringBootTest.class);
|
||||
if (annotation.getEnum("webEnvironment", WebEnvironment.class).isEmbedded()) {
|
||||
registerWebTestClient(context);
|
||||
}
|
||||
@@ -74,11 +72,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
|
||||
@@ -112,11 +108,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));
|
||||
}
|
||||
@@ -124,8 +118,7 @@ class WebTestClientContextCustomizer implements ContextCustomizer {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory)
|
||||
throws BeansException {
|
||||
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
|
||||
}
|
||||
|
||||
}
|
||||
@@ -133,16 +126,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;
|
||||
}
|
||||
|
||||
@@ -166,8 +157,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);
|
||||
@@ -178,22 +168,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());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -38,8 +38,7 @@ class WebTestClientContextCustomizerFactory implements ContextCustomizerFactory
|
||||
@Override
|
||||
public ContextCustomizer createContextCustomizer(Class<?> testClass,
|
||||
List<ContextConfigurationAttributes> configAttributes) {
|
||||
MergedAnnotations annotations = MergedAnnotations.from(testClass,
|
||||
SearchStrategy.INHERITED_ANNOTATIONS);
|
||||
MergedAnnotations annotations = MergedAnnotations.from(testClass, SearchStrategy.INHERITED_ANNOTATIONS);
|
||||
if (isWebClientPresent() && annotations.isPresent(SpringBootTest.class)) {
|
||||
return new WebTestClientContextCustomizer();
|
||||
}
|
||||
|
||||
@@ -66,15 +66,13 @@ public abstract class AbstractSpringBootTestEmbeddedReactiveWebEnvironmentTests
|
||||
@Test
|
||||
public void runAndTestHttpEndpoint() {
|
||||
assertThat(this.port).isNotEqualTo(8080).isNotEqualTo(0);
|
||||
WebTestClient.bindToServer().baseUrl("http://localhost:" + this.port).build()
|
||||
.get().uri("/").exchange().expectBody(String.class)
|
||||
.isEqualTo("Hello World");
|
||||
WebTestClient.bindToServer().baseUrl("http://localhost:" + this.port).build().get().uri("/").exchange()
|
||||
.expectBody(String.class).isEqualTo("Hello World");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void injectWebTestClient() {
|
||||
this.webClient.get().uri("/").exchange().expectBody(String.class)
|
||||
.isEqualTo("Hello World");
|
||||
this.webClient.get().uri("/").exchange().expectBody(String.class).isEqualTo("Hello World");
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
@@ -71,8 +71,7 @@ public abstract class AbstractSpringBootTestWebServerWebEnvironmentTests {
|
||||
@Test
|
||||
public void runAndTestHttpEndpoint() {
|
||||
assertThat(this.port).isNotEqualTo(8080).isNotEqualTo(0);
|
||||
String body = new RestTemplate()
|
||||
.getForObject("http://localhost:" + this.port + "/", String.class);
|
||||
String body = new RestTemplate().getForObject("http://localhost:" + this.port + "/", String.class);
|
||||
assertThat(body).isEqualTo("Hello World");
|
||||
}
|
||||
|
||||
@@ -89,8 +88,7 @@ public abstract class AbstractSpringBootTestWebServerWebEnvironmentTests {
|
||||
|
||||
@Test
|
||||
public void validateWebApplicationContextIsSet() {
|
||||
assertThat(this.context).isSameAs(
|
||||
WebApplicationContextUtils.getWebApplicationContext(this.servletContext));
|
||||
assertThat(this.context).isSameAs(WebApplicationContextUtils.getWebApplicationContext(this.servletContext));
|
||||
}
|
||||
|
||||
protected abstract static class AbstractConfig {
|
||||
|
||||
@@ -32,20 +32,17 @@ import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException
|
||||
*/
|
||||
public class AnnotatedClassFinderTests {
|
||||
|
||||
private AnnotatedClassFinder finder = new AnnotatedClassFinder(
|
||||
SpringBootConfiguration.class);
|
||||
private AnnotatedClassFinder finder = new AnnotatedClassFinder(SpringBootConfiguration.class);
|
||||
|
||||
@Test
|
||||
public void findFromClassWhenSourceIsNullShouldThrowException() {
|
||||
assertThatIllegalArgumentException()
|
||||
.isThrownBy(() -> this.finder.findFromClass((Class<?>) null))
|
||||
assertThatIllegalArgumentException().isThrownBy(() -> this.finder.findFromClass((Class<?>) null))
|
||||
.withMessageContaining("Source must not be null");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void findFromPackageWhenSourceIsNullShouldThrowException() {
|
||||
assertThatIllegalArgumentException()
|
||||
.isThrownBy(() -> this.finder.findFromPackage((String) null))
|
||||
assertThatIllegalArgumentException().isThrownBy(() -> this.finder.findFromPackage((String) null))
|
||||
.withMessageContaining("Source must not be null");
|
||||
}
|
||||
|
||||
@@ -63,8 +60,7 @@ public class AnnotatedClassFinderTests {
|
||||
|
||||
@Test
|
||||
public void findFromPackageWhenConfigurationIsFoundShouldReturnConfiguration() {
|
||||
Class<?> config = this.finder
|
||||
.findFromPackage("org.springframework.boot.test.context.example.scan");
|
||||
Class<?> config = this.finder.findFromPackage("org.springframework.boot.test.context.example.scan");
|
||||
assertThat(config).isEqualTo(ExampleConfig.class);
|
||||
}
|
||||
|
||||
|
||||
@@ -39,8 +39,7 @@ public class FilteredClassLoaderTests {
|
||||
"org/springframework/boot/test/context/FilteredClassLoaderTestsResource.txt");
|
||||
|
||||
@Test
|
||||
public void loadClassWhenFilteredOnPackageShouldThrowClassNotFound()
|
||||
throws Exception {
|
||||
public void loadClassWhenFilteredOnPackageShouldThrowClassNotFound() throws Exception {
|
||||
try (FilteredClassLoader classLoader = new FilteredClassLoader(
|
||||
FilteredClassLoaderTests.class.getPackage().getName())) {
|
||||
assertThatExceptionOfType(ClassNotFoundException.class)
|
||||
@@ -50,8 +49,7 @@ public class FilteredClassLoaderTests {
|
||||
|
||||
@Test
|
||||
public void loadClassWhenFilteredOnClassShouldThrowClassNotFound() throws Exception {
|
||||
try (FilteredClassLoader classLoader = new FilteredClassLoader(
|
||||
FilteredClassLoaderTests.class)) {
|
||||
try (FilteredClassLoader classLoader = new FilteredClassLoader(FilteredClassLoaderTests.class)) {
|
||||
assertThatExceptionOfType(ClassNotFoundException.class)
|
||||
.isThrownBy(() -> classLoader.loadClass(getClass().getName()));
|
||||
}
|
||||
@@ -66,8 +64,7 @@ public class FilteredClassLoaderTests {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void loadResourceWhenFilteredOnResourceShouldReturnNotFound()
|
||||
throws Exception {
|
||||
public void loadResourceWhenFilteredOnResourceShouldReturnNotFound() throws Exception {
|
||||
try (FilteredClassLoader classLoader = new FilteredClassLoader(TEST_RESOURCE)) {
|
||||
final URL loaded = classLoader.getResource(TEST_RESOURCE.getPath());
|
||||
assertThat(loaded).isNull();
|
||||
@@ -76,49 +73,40 @@ public class FilteredClassLoaderTests {
|
||||
|
||||
@Test
|
||||
public void loadResourceWhenNotFilteredShouldLoadResource() throws Exception {
|
||||
try (FilteredClassLoader classLoader = new FilteredClassLoader(
|
||||
(resourceName) -> false)) {
|
||||
try (FilteredClassLoader classLoader = new FilteredClassLoader((resourceName) -> false)) {
|
||||
final URL loaded = classLoader.getResource(TEST_RESOURCE.getPath());
|
||||
assertThat(loaded).isNotNull();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void loadResourcesWhenFilteredOnResourceShouldReturnNotFound()
|
||||
throws Exception {
|
||||
public void loadResourcesWhenFilteredOnResourceShouldReturnNotFound() throws Exception {
|
||||
try (FilteredClassLoader classLoader = new FilteredClassLoader(TEST_RESOURCE)) {
|
||||
final Enumeration<URL> loaded = classLoader
|
||||
.getResources(TEST_RESOURCE.getPath());
|
||||
final Enumeration<URL> loaded = classLoader.getResources(TEST_RESOURCE.getPath());
|
||||
assertThat(loaded.hasMoreElements()).isFalse();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void loadResourcesWhenNotFilteredShouldLoadResource() throws Exception {
|
||||
try (FilteredClassLoader classLoader = new FilteredClassLoader(
|
||||
(resourceName) -> false)) {
|
||||
final Enumeration<URL> loaded = classLoader
|
||||
.getResources(TEST_RESOURCE.getPath());
|
||||
try (FilteredClassLoader classLoader = new FilteredClassLoader((resourceName) -> false)) {
|
||||
final Enumeration<URL> loaded = classLoader.getResources(TEST_RESOURCE.getPath());
|
||||
assertThat(loaded.hasMoreElements()).isTrue();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void loadResourceAsStreamWhenFilteredOnResourceShouldReturnNotFound()
|
||||
throws Exception {
|
||||
public void loadResourceAsStreamWhenFilteredOnResourceShouldReturnNotFound() throws Exception {
|
||||
try (FilteredClassLoader classLoader = new FilteredClassLoader(TEST_RESOURCE)) {
|
||||
final InputStream loaded = classLoader
|
||||
.getResourceAsStream(TEST_RESOURCE.getPath());
|
||||
final InputStream loaded = classLoader.getResourceAsStream(TEST_RESOURCE.getPath());
|
||||
assertThat(loaded).isNull();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void loadResourceAsStreamWhenNotFilteredShouldLoadResource() throws Exception {
|
||||
try (FilteredClassLoader classLoader = new FilteredClassLoader(
|
||||
(resourceName) -> false)) {
|
||||
final InputStream loaded = classLoader
|
||||
.getResourceAsStream(TEST_RESOURCE.getPath());
|
||||
try (FilteredClassLoader classLoader = new FilteredClassLoader((resourceName) -> false)) {
|
||||
final InputStream loaded = classLoader.getResourceAsStream(TEST_RESOURCE.getPath());
|
||||
assertThat(loaded).isNotNull();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -45,54 +45,45 @@ public class ImportsContextCustomizerFactoryTests {
|
||||
|
||||
@Test
|
||||
public void getContextCustomizerWhenHasNoImportAnnotationShouldReturnNull() {
|
||||
ContextCustomizer customizer = this.factory
|
||||
.createContextCustomizer(TestWithNoImport.class, null);
|
||||
ContextCustomizer customizer = this.factory.createContextCustomizer(TestWithNoImport.class, null);
|
||||
assertThat(customizer).isNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void getContextCustomizerWhenHasImportAnnotationShouldReturnCustomizer() {
|
||||
ContextCustomizer customizer = this.factory
|
||||
.createContextCustomizer(TestWithImport.class, null);
|
||||
ContextCustomizer customizer = this.factory.createContextCustomizer(TestWithImport.class, null);
|
||||
assertThat(customizer).isNotNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void getContextCustomizerWhenHasMetaImportAnnotationShouldReturnCustomizer() {
|
||||
ContextCustomizer customizer = this.factory
|
||||
.createContextCustomizer(TestWithMetaImport.class, null);
|
||||
ContextCustomizer customizer = this.factory.createContextCustomizer(TestWithMetaImport.class, null);
|
||||
assertThat(customizer).isNotNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void contextCustomizerEqualsAndHashCode() {
|
||||
ContextCustomizer customizer1 = this.factory
|
||||
.createContextCustomizer(TestWithImport.class, null);
|
||||
ContextCustomizer customizer2 = this.factory
|
||||
.createContextCustomizer(TestWithImport.class, null);
|
||||
ContextCustomizer customizer3 = this.factory
|
||||
.createContextCustomizer(TestWithImportAndMetaImport.class, null);
|
||||
ContextCustomizer customizer4 = this.factory
|
||||
.createContextCustomizer(TestWithSameImportAndMetaImport.class, null);
|
||||
ContextCustomizer customizer1 = this.factory.createContextCustomizer(TestWithImport.class, null);
|
||||
ContextCustomizer customizer2 = this.factory.createContextCustomizer(TestWithImport.class, null);
|
||||
ContextCustomizer customizer3 = this.factory.createContextCustomizer(TestWithImportAndMetaImport.class, null);
|
||||
ContextCustomizer customizer4 = this.factory.createContextCustomizer(TestWithSameImportAndMetaImport.class,
|
||||
null);
|
||||
assertThat(customizer1.hashCode()).isEqualTo(customizer1.hashCode());
|
||||
assertThat(customizer1.hashCode()).isEqualTo(customizer2.hashCode());
|
||||
assertThat(customizer1).isEqualTo(customizer1).isEqualTo(customizer2)
|
||||
.isNotEqualTo(customizer3);
|
||||
assertThat(customizer1).isEqualTo(customizer1).isEqualTo(customizer2).isNotEqualTo(customizer3);
|
||||
assertThat(customizer3).isEqualTo(customizer4);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void getContextCustomizerWhenClassHasBeanMethodsShouldThrowException() {
|
||||
assertThatIllegalStateException()
|
||||
.isThrownBy(() -> this.factory
|
||||
.createContextCustomizer(TestWithImportAndBeanMethod.class, null))
|
||||
.isThrownBy(() -> this.factory.createContextCustomizer(TestWithImportAndBeanMethod.class, null))
|
||||
.withMessageContaining("Test classes cannot include @Bean methods");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void contextCustomizerImportsBeans() {
|
||||
ContextCustomizer customizer = this.factory
|
||||
.createContextCustomizer(TestWithImport.class, null);
|
||||
ContextCustomizer customizer = this.factory.createContextCustomizer(TestWithImport.class, null);
|
||||
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
|
||||
customizer.customizeContext(context, mock(MergedContextConfiguration.class));
|
||||
context.refresh();
|
||||
@@ -101,8 +92,8 @@ public class ImportsContextCustomizerFactoryTests {
|
||||
|
||||
@Test
|
||||
public void selfAnnotatingAnnotationDoesNotCauseStackOverflow() {
|
||||
assertThat(this.factory.createContextCustomizer(
|
||||
TestWithImportAndSelfAnnotatingAnnotation.class, null)).isNotNull();
|
||||
assertThat(this.factory.createContextCustomizer(TestWithImportAndSelfAnnotatingAnnotation.class, null))
|
||||
.isNotNull();
|
||||
}
|
||||
|
||||
static class TestWithNoImport {
|
||||
|
||||
@@ -45,38 +45,31 @@ public class ImportsContextCustomizerTests {
|
||||
@Test
|
||||
public void importSelectorsCouldUseAnyAnnotations() {
|
||||
assertThat(new ImportsContextCustomizer(FirstImportSelectorAnnotatedClass.class))
|
||||
.isNotEqualTo(new ImportsContextCustomizer(
|
||||
SecondImportSelectorAnnotatedClass.class));
|
||||
.isNotEqualTo(new ImportsContextCustomizer(SecondImportSelectorAnnotatedClass.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void determinableImportSelector() {
|
||||
assertThat(new ImportsContextCustomizer(
|
||||
FirstDeterminableImportSelectorAnnotatedClass.class))
|
||||
.isEqualTo(new ImportsContextCustomizer(
|
||||
SecondDeterminableImportSelectorAnnotatedClass.class));
|
||||
assertThat(new ImportsContextCustomizer(FirstDeterminableImportSelectorAnnotatedClass.class))
|
||||
.isEqualTo(new ImportsContextCustomizer(SecondDeterminableImportSelectorAnnotatedClass.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void customizersForTestClassesWithDifferentKotlinMetadataAreEqual() {
|
||||
assertThat(new ImportsContextCustomizer(FirstKotlinAnnotatedTestClass.class))
|
||||
.isEqualTo(new ImportsContextCustomizer(
|
||||
SecondKotlinAnnotatedTestClass.class));
|
||||
.isEqualTo(new ImportsContextCustomizer(SecondKotlinAnnotatedTestClass.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void customizersForTestClassesWithDifferentSpockFrameworkAnnotationsAreEqual() {
|
||||
assertThat(
|
||||
new ImportsContextCustomizer(FirstSpockFrameworkAnnotatedTestClass.class))
|
||||
.isEqualTo(new ImportsContextCustomizer(
|
||||
SecondSpockFrameworkAnnotatedTestClass.class));
|
||||
assertThat(new ImportsContextCustomizer(FirstSpockFrameworkAnnotatedTestClass.class))
|
||||
.isEqualTo(new ImportsContextCustomizer(SecondSpockFrameworkAnnotatedTestClass.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void customizersForTestClassesWithDifferentSpockLangAnnotationsAreEqual() {
|
||||
assertThat(new ImportsContextCustomizer(FirstSpockLangAnnotatedTestClass.class))
|
||||
.isEqualTo(new ImportsContextCustomizer(
|
||||
SecondSpockLangAnnotatedTestClass.class));
|
||||
.isEqualTo(new ImportsContextCustomizer(SecondSpockLangAnnotatedTestClass.class));
|
||||
}
|
||||
|
||||
@Import(TestImportSelector.class)
|
||||
@@ -152,8 +145,7 @@ public class ImportsContextCustomizerTests {
|
||||
|
||||
}
|
||||
|
||||
static class TestDeterminableImportSelector
|
||||
implements ImportSelector, DeterminableImports {
|
||||
static class TestDeterminableImportSelector implements ImportSelector, DeterminableImports {
|
||||
|
||||
@Override
|
||||
public String[] selectImports(AnnotationMetadata arg0) {
|
||||
|
||||
@@ -67,14 +67,12 @@ public class SpringBootContextLoaderMockMvcTests {
|
||||
|
||||
@Test
|
||||
public void testMockHttpEndpoint() throws Exception {
|
||||
this.mvc.perform(get("/")).andExpect(status().isOk())
|
||||
.andExpect(content().string("Hello World"));
|
||||
this.mvc.perform(get("/")).andExpect(status().isOk()).andExpect(content().string("Hello World"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void validateWebApplicationContextIsSet() {
|
||||
assertThat(this.context).isSameAs(
|
||||
WebApplicationContextUtils.getWebApplicationContext(this.servletContext));
|
||||
assertThat(this.context).isSameAs(WebApplicationContextUtils.getWebApplicationContext(this.servletContext));
|
||||
}
|
||||
|
||||
@Configuration(proxyBeanMethods = false)
|
||||
|
||||
@@ -74,8 +74,7 @@ public class SpringBootContextLoaderTests {
|
||||
|
||||
@Test
|
||||
public void environmentPropertiesAnotherSeparatorInValue() {
|
||||
Map<String, Object> config = getEnvironmentProperties(
|
||||
AnotherSeparatorInValue.class);
|
||||
Map<String, Object> config = getEnvironmentProperties(AnotherSeparatorInValue.class);
|
||||
assertKey(config, "key", "my:Value");
|
||||
assertKey(config, "anotherKey", "another=Value");
|
||||
}
|
||||
@@ -90,12 +89,10 @@ public class SpringBootContextLoaderTests {
|
||||
}
|
||||
|
||||
private Map<String, Object> getEnvironmentProperties(Class<?> testClass) {
|
||||
TestContext context = new ExposedTestContextManager(testClass)
|
||||
.getExposedTestContext();
|
||||
MergedContextConfiguration config = (MergedContextConfiguration) ReflectionTestUtils
|
||||
.getField(context, "mergedContextConfiguration");
|
||||
return TestPropertySourceUtils
|
||||
.convertInlinedPropertiesToMap(config.getPropertySourceProperties());
|
||||
TestContext context = new ExposedTestContextManager(testClass).getExposedTestContext();
|
||||
MergedContextConfiguration config = (MergedContextConfiguration) ReflectionTestUtils.getField(context,
|
||||
"mergedContextConfiguration");
|
||||
return TestPropertySourceUtils.convertInlinedPropertiesToMap(config.getPropertySourceProperties());
|
||||
}
|
||||
|
||||
private void assertKey(Map<String, Object> actual, String key, Object value) {
|
||||
|
||||
@@ -41,8 +41,7 @@ public class SpringBootTestActiveProfileTests {
|
||||
|
||||
@Test
|
||||
public void profiles() {
|
||||
assertThat(this.context.getEnvironment().getActiveProfiles())
|
||||
.containsExactly("override");
|
||||
assertThat(this.context.getEnvironment().getActiveProfiles()).containsExactly("override");
|
||||
}
|
||||
|
||||
@Configuration(proxyBeanMethods = false)
|
||||
|
||||
@@ -40,8 +40,7 @@ public class SpringBootTestArgsTests {
|
||||
public void applicationArgumentsPopulated() {
|
||||
assertThat(this.args.getOptionNames()).containsOnly("option.foo");
|
||||
assertThat(this.args.getOptionValues("option.foo")).containsOnly("foo-value");
|
||||
assertThat(this.args.getNonOptionArgs())
|
||||
.containsOnly("other.bar=other-bar-value");
|
||||
assertThat(this.args.getNonOptionArgs()).containsOnly("other.bar=other-bar-value");
|
||||
}
|
||||
|
||||
@Configuration(proxyBeanMethods = false)
|
||||
|
||||
@@ -29,8 +29,8 @@ import org.springframework.web.reactive.config.EnableWebFlux;
|
||||
* @author Stephane Nicoll
|
||||
*/
|
||||
@DirtiesContext
|
||||
@SpringBootTest(webEnvironment = WebEnvironment.DEFINED_PORT, properties = {
|
||||
"spring.main.web-application-type=reactive", "server.port=0", "value=123" })
|
||||
@SpringBootTest(webEnvironment = WebEnvironment.DEFINED_PORT,
|
||||
properties = { "spring.main.web-application-type=reactive", "server.port=0", "value=123" })
|
||||
public class SpringBootTestReactiveWebEnvironmentDefinedPortTests
|
||||
extends AbstractSpringBootTestEmbeddedReactiveWebEnvironmentTests {
|
||||
|
||||
|
||||
@@ -42,8 +42,7 @@ public class SpringBootTestReactiveWebEnvironmentUserDefinedTestRestTemplateTest
|
||||
|
||||
@Test
|
||||
public void restTemplateIsUserDefined() {
|
||||
assertThat(getContext().getBean("testRestTemplate"))
|
||||
.isInstanceOf(RestTemplate.class);
|
||||
assertThat(getContext().getBean("testRestTemplate")).isInstanceOf(RestTemplate.class);
|
||||
}
|
||||
|
||||
@Configuration(proxyBeanMethods = false)
|
||||
|
||||
@@ -37,13 +37,11 @@ import static org.assertj.core.api.Assertions.assertThat;
|
||||
*/
|
||||
@DirtiesContext
|
||||
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, properties = { "value=123" })
|
||||
public class SpringBootTestUserDefinedTestRestTemplateTests
|
||||
extends AbstractSpringBootTestWebServerWebEnvironmentTests {
|
||||
public class SpringBootTestUserDefinedTestRestTemplateTests extends AbstractSpringBootTestWebServerWebEnvironmentTests {
|
||||
|
||||
@Test
|
||||
public void restTemplateIsUserDefined() {
|
||||
assertThat(getContext().getBean("testRestTemplate"))
|
||||
.isInstanceOf(RestTemplate.class);
|
||||
assertThat(getContext().getBean("testRestTemplate")).isInstanceOf(RestTemplate.class);
|
||||
}
|
||||
|
||||
// gh-7711
|
||||
|
||||
@@ -42,8 +42,7 @@ import static org.assertj.core.api.Assertions.assertThat;
|
||||
* @author Andy Wilkinson
|
||||
*/
|
||||
@DirtiesContext
|
||||
@SpringBootTest(webEnvironment = WebEnvironment.DEFINED_PORT,
|
||||
properties = { "server.port=0", "value=123" })
|
||||
@SpringBootTest(webEnvironment = WebEnvironment.DEFINED_PORT, properties = { "server.port=0", "value=123" })
|
||||
@ContextHierarchy({ @ContextConfiguration(classes = ParentConfiguration.class),
|
||||
@ContextConfiguration(classes = ChildConfiguration.class) })
|
||||
public class SpringBootTestWebEnvironmentContextHierarchyTests {
|
||||
|
||||
@@ -30,10 +30,8 @@ import org.springframework.web.servlet.config.annotation.EnableWebMvc;
|
||||
* @author Andy Wilkinson
|
||||
*/
|
||||
@DirtiesContext
|
||||
@SpringBootTest(webEnvironment = WebEnvironment.DEFINED_PORT,
|
||||
properties = { "server.port=0", "value=123" })
|
||||
public class SpringBootTestWebEnvironmentDefinedPortTests
|
||||
extends AbstractSpringBootTestWebServerWebEnvironmentTests {
|
||||
@SpringBootTest(webEnvironment = WebEnvironment.DEFINED_PORT, properties = { "server.port=0", "value=123" })
|
||||
public class SpringBootTestWebEnvironmentDefinedPortTests extends AbstractSpringBootTestWebServerWebEnvironmentTests {
|
||||
|
||||
@Configuration(proxyBeanMethods = false)
|
||||
@EnableWebMvc
|
||||
|
||||
@@ -75,8 +75,7 @@ public class SpringBootTestWebEnvironmentMockTests {
|
||||
|
||||
@Test
|
||||
public void resourcePath() {
|
||||
assertThat(this.servletContext).hasFieldOrPropertyWithValue("resourceBasePath",
|
||||
"src/main/webapp");
|
||||
assertThat(this.servletContext).hasFieldOrPropertyWithValue("resourceBasePath", "src/main/webapp");
|
||||
}
|
||||
|
||||
@Configuration(proxyBeanMethods = false)
|
||||
|
||||
@@ -48,8 +48,7 @@ public class SpringBootTestWebEnvironmentMockWithWebAppConfigurationTests {
|
||||
|
||||
@Test
|
||||
public void resourcePath() {
|
||||
assertThat(this.servletContext).hasFieldOrPropertyWithValue("resourceBasePath",
|
||||
"src/mymain/mywebapp");
|
||||
assertThat(this.servletContext).hasFieldOrPropertyWithValue("resourceBasePath", "src/mymain/mywebapp");
|
||||
}
|
||||
|
||||
@Configuration(proxyBeanMethods = false)
|
||||
|
||||
@@ -35,8 +35,7 @@ import static org.assertj.core.api.Assertions.assertThat;
|
||||
* @author Stephane Nicoll
|
||||
*/
|
||||
@DirtiesContext
|
||||
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT,
|
||||
properties = { "server.port=12345" })
|
||||
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, properties = { "server.port=12345" })
|
||||
public class SpringBootTestWebEnvironmentRandomPortCustomPortTests {
|
||||
|
||||
@Autowired
|
||||
|
||||
@@ -38,8 +38,7 @@ import static org.assertj.core.api.Assertions.assertThat;
|
||||
*/
|
||||
@DirtiesContext
|
||||
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, properties = { "value=123" })
|
||||
public class SpringBootTestWebEnvironmentRandomPortTests
|
||||
extends AbstractSpringBootTestWebServerWebEnvironmentTests {
|
||||
public class SpringBootTestWebEnvironmentRandomPortTests extends AbstractSpringBootTestWebServerWebEnvironmentTests {
|
||||
|
||||
@Test
|
||||
public void testRestTemplateShouldUseBuilder() {
|
||||
@@ -54,8 +53,7 @@ public class SpringBootTestWebEnvironmentRandomPortTests
|
||||
|
||||
@Bean
|
||||
public RestTemplateBuilder restTemplateBuilder() {
|
||||
return new RestTemplateBuilder()
|
||||
.additionalMessageConverters(new MyConverter());
|
||||
return new RestTemplateBuilder().additionalMessageConverters(new MyConverter());
|
||||
|
||||
}
|
||||
|
||||
|
||||
@@ -36,8 +36,7 @@ import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
|
||||
*/
|
||||
@DirtiesContext
|
||||
@SpringBootTest
|
||||
@ContextConfiguration(
|
||||
classes = SpringBootTestWithContextConfigurationIntegrationTests.Config.class)
|
||||
@ContextConfiguration(classes = SpringBootTestWithContextConfigurationIntegrationTests.Config.class)
|
||||
public class SpringBootTestWithContextConfigurationIntegrationTests {
|
||||
|
||||
@Autowired
|
||||
|
||||
@@ -37,11 +37,10 @@ import static org.assertj.core.api.Assertions.assertThat;
|
||||
* @author Andy Wilkinson
|
||||
*/
|
||||
@DirtiesContext
|
||||
@SpringBootTest(webEnvironment = WebEnvironment.NONE, properties = {
|
||||
"boot-test-inlined=foo", "b=boot-test-inlined", "c=boot-test-inlined" })
|
||||
@SpringBootTest(webEnvironment = WebEnvironment.NONE,
|
||||
properties = { "boot-test-inlined=foo", "b=boot-test-inlined", "c=boot-test-inlined" })
|
||||
@TestPropertySource(
|
||||
properties = { "property-source-inlined=bar", "a=property-source-inlined",
|
||||
"c=property-source-inlined" },
|
||||
properties = { "property-source-inlined=bar", "a=property-source-inlined", "c=property-source-inlined" },
|
||||
locations = "classpath:/test-property-source-annotation.properties")
|
||||
public class SpringBootTestWithTestPropertySourceTests {
|
||||
|
||||
@@ -71,14 +70,12 @@ public class SpringBootTestWithTestPropertySourceTests {
|
||||
|
||||
@Test
|
||||
public void propertyFromBootTestPropertiesOverridesPropertyFromPropertySourceLocations() {
|
||||
assertThat(this.config.bootTestInlinedOverridesPropertySourceLocation)
|
||||
.isEqualTo("boot-test-inlined");
|
||||
assertThat(this.config.bootTestInlinedOverridesPropertySourceLocation).isEqualTo("boot-test-inlined");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void propertyFromPropertySourcePropertiesOverridesPropertyFromBootTestProperties() {
|
||||
assertThat(this.config.propertySourceInlinedOverridesBootTestInlined)
|
||||
.isEqualTo("property-source-inlined");
|
||||
assertThat(this.config.propertySourceInlinedOverridesBootTestInlined).isEqualTo("property-source-inlined");
|
||||
}
|
||||
|
||||
@Configuration(proxyBeanMethods = false)
|
||||
|
||||
@@ -61,51 +61,44 @@ public class ApplicationContextAssertProviderTests {
|
||||
|
||||
@Test
|
||||
public void getWhenTypeIsNullShouldThrowException() {
|
||||
assertThatIllegalArgumentException()
|
||||
.isThrownBy(() -> ApplicationContextAssertProvider.get(null,
|
||||
ApplicationContext.class, this.mockContextSupplier))
|
||||
assertThatIllegalArgumentException().isThrownBy(
|
||||
() -> ApplicationContextAssertProvider.get(null, ApplicationContext.class, this.mockContextSupplier))
|
||||
.withMessageContaining("Type must not be null");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void getWhenTypeIsClassShouldThrowException() {
|
||||
assertThatIllegalArgumentException()
|
||||
.isThrownBy(() -> ApplicationContextAssertProvider.get(null,
|
||||
ApplicationContext.class, this.mockContextSupplier))
|
||||
assertThatIllegalArgumentException().isThrownBy(
|
||||
() -> ApplicationContextAssertProvider.get(null, ApplicationContext.class, this.mockContextSupplier))
|
||||
.withMessageContaining("Type must not be null");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void getWhenContextTypeIsNullShouldThrowException() {
|
||||
assertThatIllegalArgumentException()
|
||||
.isThrownBy(() -> ApplicationContextAssertProvider.get(
|
||||
TestAssertProviderApplicationContextClass.class,
|
||||
.isThrownBy(() -> ApplicationContextAssertProvider.get(TestAssertProviderApplicationContextClass.class,
|
||||
ApplicationContext.class, this.mockContextSupplier))
|
||||
.withMessageContaining("Type must be an interface");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void getWhenContextTypeIsClassShouldThrowException() {
|
||||
assertThatIllegalArgumentException()
|
||||
.isThrownBy(() -> ApplicationContextAssertProvider.get(
|
||||
TestAssertProviderApplicationContext.class, null,
|
||||
this.mockContextSupplier))
|
||||
assertThatIllegalArgumentException().isThrownBy(() -> ApplicationContextAssertProvider
|
||||
.get(TestAssertProviderApplicationContext.class, null, this.mockContextSupplier))
|
||||
.withMessageContaining("ContextType must not be null");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void getWhenSupplierIsNullShouldThrowException() {
|
||||
assertThatIllegalArgumentException()
|
||||
.isThrownBy(() -> ApplicationContextAssertProvider.get(
|
||||
TestAssertProviderApplicationContext.class,
|
||||
.isThrownBy(() -> ApplicationContextAssertProvider.get(TestAssertProviderApplicationContext.class,
|
||||
StaticApplicationContext.class, this.mockContextSupplier))
|
||||
.withMessageContaining("ContextType must be an interface");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void getWhenContextStartsShouldReturnProxyThatCallsRealMethods() {
|
||||
ApplicationContextAssertProvider<ApplicationContext> context = get(
|
||||
this.mockContextSupplier);
|
||||
ApplicationContextAssertProvider<ApplicationContext> context = get(this.mockContextSupplier);
|
||||
assertThat((Object) context).isNotNull();
|
||||
context.getBean("foo");
|
||||
verify(this.mockContext).getBean("foo");
|
||||
@@ -113,63 +106,54 @@ public class ApplicationContextAssertProviderTests {
|
||||
|
||||
@Test
|
||||
public void getWhenContextFailsShouldReturnProxyThatThrowsExceptions() {
|
||||
ApplicationContextAssertProvider<ApplicationContext> context = get(
|
||||
this.startupFailureSupplier);
|
||||
ApplicationContextAssertProvider<ApplicationContext> context = get(this.startupFailureSupplier);
|
||||
assertThat((Object) context).isNotNull();
|
||||
assertThatIllegalStateException().isThrownBy(() -> context.getBean("foo"))
|
||||
.withCause(this.startupFailure).withMessageContaining("failed to start");
|
||||
assertThatIllegalStateException().isThrownBy(() -> context.getBean("foo")).withCause(this.startupFailure)
|
||||
.withMessageContaining("failed to start");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void getSourceContextWhenContextStartsShouldReturnSourceContext() {
|
||||
ApplicationContextAssertProvider<ApplicationContext> context = get(
|
||||
this.mockContextSupplier);
|
||||
ApplicationContextAssertProvider<ApplicationContext> context = get(this.mockContextSupplier);
|
||||
assertThat(context.getSourceApplicationContext()).isSameAs(this.mockContext);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void getSourceContextWhenContextFailsShouldThrowException() {
|
||||
ApplicationContextAssertProvider<ApplicationContext> context = get(
|
||||
this.startupFailureSupplier);
|
||||
ApplicationContextAssertProvider<ApplicationContext> context = get(this.startupFailureSupplier);
|
||||
assertThatIllegalStateException().isThrownBy(context::getSourceApplicationContext)
|
||||
.withCause(this.startupFailure).withMessageContaining("failed to start");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void getSourceContextOfTypeWhenContextStartsShouldReturnSourceContext() {
|
||||
ApplicationContextAssertProvider<ApplicationContext> context = get(
|
||||
this.mockContextSupplier);
|
||||
assertThat(context.getSourceApplicationContext(ApplicationContext.class))
|
||||
.isSameAs(this.mockContext);
|
||||
ApplicationContextAssertProvider<ApplicationContext> context = get(this.mockContextSupplier);
|
||||
assertThat(context.getSourceApplicationContext(ApplicationContext.class)).isSameAs(this.mockContext);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void getSourceContextOfTypeWhenContextFailsToStartShouldThrowException() {
|
||||
ApplicationContextAssertProvider<ApplicationContext> context = get(
|
||||
this.startupFailureSupplier);
|
||||
assertThatIllegalStateException().isThrownBy(
|
||||
() -> context.getSourceApplicationContext(ApplicationContext.class))
|
||||
ApplicationContextAssertProvider<ApplicationContext> context = get(this.startupFailureSupplier);
|
||||
assertThatIllegalStateException()
|
||||
.isThrownBy(() -> context.getSourceApplicationContext(ApplicationContext.class))
|
||||
.withCause(this.startupFailure).withMessageContaining("failed to start");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void getStartupFailureWhenContextStartsShouldReturnNull() {
|
||||
ApplicationContextAssertProvider<ApplicationContext> context = get(
|
||||
this.mockContextSupplier);
|
||||
ApplicationContextAssertProvider<ApplicationContext> context = get(this.mockContextSupplier);
|
||||
assertThat(context.getStartupFailure()).isNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void getStartupFailureWhenContextFailsToStartShouldReturnException() {
|
||||
ApplicationContextAssertProvider<ApplicationContext> context = get(
|
||||
this.startupFailureSupplier);
|
||||
ApplicationContextAssertProvider<ApplicationContext> context = get(this.startupFailureSupplier);
|
||||
assertThat(context.getStartupFailure()).isEqualTo(this.startupFailure);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void assertThatWhenContextStartsShouldReturnAssertions() {
|
||||
ApplicationContextAssertProvider<ApplicationContext> context = get(
|
||||
this.mockContextSupplier);
|
||||
ApplicationContextAssertProvider<ApplicationContext> context = get(this.mockContextSupplier);
|
||||
ApplicationContextAssert<ApplicationContext> contextAssert = assertThat(context);
|
||||
assertThat(contextAssert.getApplicationContext()).isSameAs(context);
|
||||
assertThat(contextAssert.getStartupFailure()).isNull();
|
||||
@@ -177,8 +161,7 @@ public class ApplicationContextAssertProviderTests {
|
||||
|
||||
@Test
|
||||
public void assertThatWhenContextFailsShouldReturnAssertions() {
|
||||
ApplicationContextAssertProvider<ApplicationContext> context = get(
|
||||
this.startupFailureSupplier);
|
||||
ApplicationContextAssertProvider<ApplicationContext> context = get(this.startupFailureSupplier);
|
||||
ApplicationContextAssert<ApplicationContext> contextAssert = assertThat(context);
|
||||
assertThat(contextAssert.getApplicationContext()).isSameAs(context);
|
||||
assertThat(contextAssert.getStartupFailure()).isSameAs(this.startupFailure);
|
||||
@@ -186,37 +169,28 @@ public class ApplicationContextAssertProviderTests {
|
||||
|
||||
@Test
|
||||
public void toStringWhenContextStartsShouldReturnSimpleString() {
|
||||
ApplicationContextAssertProvider<ApplicationContext> context = get(
|
||||
this.mockContextSupplier);
|
||||
assertThat(context.toString())
|
||||
.startsWith(
|
||||
"Started application [ConfigurableApplicationContext.MockitoMock")
|
||||
.endsWith(
|
||||
"id = [null], applicationName = [null], beanDefinitionCount = 0]");
|
||||
ApplicationContextAssertProvider<ApplicationContext> context = get(this.mockContextSupplier);
|
||||
assertThat(context.toString()).startsWith("Started application [ConfigurableApplicationContext.MockitoMock")
|
||||
.endsWith("id = [null], applicationName = [null], beanDefinitionCount = 0]");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void toStringWhenContextFailsToStartShouldReturnSimpleString() {
|
||||
ApplicationContextAssertProvider<ApplicationContext> context = get(
|
||||
this.startupFailureSupplier);
|
||||
ApplicationContextAssertProvider<ApplicationContext> context = get(this.startupFailureSupplier);
|
||||
assertThat(context.toString()).isEqualTo("Unstarted application context "
|
||||
+ "org.springframework.context.ApplicationContext"
|
||||
+ "[startupFailure=java.lang.RuntimeException]");
|
||||
+ "org.springframework.context.ApplicationContext" + "[startupFailure=java.lang.RuntimeException]");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void closeShouldCloseContext() {
|
||||
ApplicationContextAssertProvider<ApplicationContext> context = get(
|
||||
this.mockContextSupplier);
|
||||
ApplicationContextAssertProvider<ApplicationContext> context = get(this.mockContextSupplier);
|
||||
context.close();
|
||||
verify(this.mockContext).close();
|
||||
}
|
||||
|
||||
private ApplicationContextAssertProvider<ApplicationContext> get(
|
||||
Supplier<ApplicationContext> contextSupplier) {
|
||||
return ApplicationContextAssertProvider.get(
|
||||
TestAssertProviderApplicationContext.class, ApplicationContext.class,
|
||||
contextSupplier);
|
||||
private ApplicationContextAssertProvider<ApplicationContext> get(Supplier<ApplicationContext> contextSupplier) {
|
||||
return ApplicationContextAssertProvider.get(TestAssertProviderApplicationContext.class,
|
||||
ApplicationContext.class, contextSupplier);
|
||||
}
|
||||
|
||||
private interface TestAssertProviderApplicationContext
|
||||
|
||||
@@ -61,15 +61,13 @@ public class ApplicationContextAssertTests {
|
||||
|
||||
@Test
|
||||
public void createWhenApplicationContextIsNullShouldThrowException() {
|
||||
assertThatIllegalArgumentException()
|
||||
.isThrownBy(() -> new ApplicationContextAssert<>(null, null))
|
||||
assertThatIllegalArgumentException().isThrownBy(() -> new ApplicationContextAssert<>(null, null))
|
||||
.withMessageContaining("ApplicationContext must not be null");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void createWhenHasApplicationContextShouldSetActual() {
|
||||
assertThat(getAssert(this.context).getSourceApplicationContext())
|
||||
.isSameAs(this.context);
|
||||
assertThat(getAssert(this.context).getSourceApplicationContext()).isSameAs(this.context);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -94,8 +92,7 @@ public class ApplicationContextAssertTests {
|
||||
public void hasBeanWhenNotStartedShouldFail() {
|
||||
assertThatExceptionOfType(AssertionError.class)
|
||||
.isThrownBy(() -> assertThat(getAssert(this.failure)).hasBean("foo"))
|
||||
.withMessageContaining(String.format(
|
||||
"but context failed to start:%n java.lang.RuntimeException"));
|
||||
.withMessageContaining(String.format("but context failed to start:%n java.lang.RuntimeException"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -106,8 +103,8 @@ public class ApplicationContextAssertTests {
|
||||
|
||||
@Test
|
||||
public void hasSingleBeanWhenHasNoBeansShouldFail() {
|
||||
assertThatExceptionOfType(AssertionError.class).isThrownBy(
|
||||
() -> assertThat(getAssert(this.context)).hasSingleBean(Foo.class))
|
||||
assertThatExceptionOfType(AssertionError.class)
|
||||
.isThrownBy(() -> assertThat(getAssert(this.context)).hasSingleBean(Foo.class))
|
||||
.withMessageContaining("to have a single bean of type");
|
||||
}
|
||||
|
||||
@@ -115,26 +112,25 @@ public class ApplicationContextAssertTests {
|
||||
public void hasSingleBeanWhenHasMultipleShouldFail() {
|
||||
this.context.registerSingleton("foo", Foo.class);
|
||||
this.context.registerSingleton("bar", Foo.class);
|
||||
assertThatExceptionOfType(AssertionError.class).isThrownBy(
|
||||
() -> assertThat(getAssert(this.context)).hasSingleBean(Foo.class))
|
||||
assertThatExceptionOfType(AssertionError.class)
|
||||
.isThrownBy(() -> assertThat(getAssert(this.context)).hasSingleBean(Foo.class))
|
||||
.withMessageContaining("but found:");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void hasSingleBeanWhenFailedToStartShouldFail() {
|
||||
assertThatExceptionOfType(AssertionError.class).isThrownBy(
|
||||
() -> assertThat(getAssert(this.failure)).hasSingleBean(Foo.class))
|
||||
assertThatExceptionOfType(AssertionError.class)
|
||||
.isThrownBy(() -> assertThat(getAssert(this.failure)).hasSingleBean(Foo.class))
|
||||
.withMessageContaining("to have a single bean of type")
|
||||
.withMessageContaining(String.format(
|
||||
"but context failed to start:%n java.lang.RuntimeException"));
|
||||
.withMessageContaining(String.format("but context failed to start:%n java.lang.RuntimeException"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void hasSingleBeanWhenInParentShouldFail() {
|
||||
this.parent.registerSingleton("foo", Foo.class);
|
||||
this.context.registerSingleton("bar", Foo.class);
|
||||
assertThatExceptionOfType(AssertionError.class).isThrownBy(
|
||||
() -> assertThat(getAssert(this.context)).hasSingleBean(Foo.class))
|
||||
assertThatExceptionOfType(AssertionError.class)
|
||||
.isThrownBy(() -> assertThat(getAssert(this.context)).hasSingleBean(Foo.class))
|
||||
.withMessageContaining("but found:");
|
||||
}
|
||||
|
||||
@@ -153,33 +149,31 @@ public class ApplicationContextAssertTests {
|
||||
@Test
|
||||
public void doesNotHaveBeanOfTypeWhenHasBeanOfTypeShouldFail() {
|
||||
this.context.registerSingleton("foo", Foo.class);
|
||||
assertThatExceptionOfType(AssertionError.class).isThrownBy(
|
||||
() -> assertThat(getAssert(this.context)).doesNotHaveBean(Foo.class))
|
||||
assertThatExceptionOfType(AssertionError.class)
|
||||
.isThrownBy(() -> assertThat(getAssert(this.context)).doesNotHaveBean(Foo.class))
|
||||
.withMessageContaining("but found");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void doesNotHaveBeanOfTypeWhenFailedToStartShouldFail() {
|
||||
assertThatExceptionOfType(AssertionError.class).isThrownBy(
|
||||
() -> assertThat(getAssert(this.failure)).doesNotHaveBean(Foo.class))
|
||||
assertThatExceptionOfType(AssertionError.class)
|
||||
.isThrownBy(() -> assertThat(getAssert(this.failure)).doesNotHaveBean(Foo.class))
|
||||
.withMessageContaining("not to have any beans of type")
|
||||
.withMessageContaining(String.format(
|
||||
"but context failed to start:%n java.lang.RuntimeException"));
|
||||
.withMessageContaining(String.format("but context failed to start:%n java.lang.RuntimeException"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void doesNotHaveBeanOfTypeWhenInParentShouldFail() {
|
||||
this.parent.registerSingleton("foo", Foo.class);
|
||||
assertThatExceptionOfType(AssertionError.class).isThrownBy(
|
||||
() -> assertThat(getAssert(this.context)).doesNotHaveBean(Foo.class))
|
||||
assertThatExceptionOfType(AssertionError.class)
|
||||
.isThrownBy(() -> assertThat(getAssert(this.context)).doesNotHaveBean(Foo.class))
|
||||
.withMessageContaining("but found");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void doesNotHaveBeanOfTypeWithLimitedScopeWhenInParentShouldPass() {
|
||||
this.parent.registerSingleton("foo", Foo.class);
|
||||
assertThat(getAssert(this.context)).doesNotHaveBean(Foo.class,
|
||||
Scope.NO_ANCESTORS);
|
||||
assertThat(getAssert(this.context)).doesNotHaveBean(Foo.class, Scope.NO_ANCESTORS);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -191,26 +185,22 @@ public class ApplicationContextAssertTests {
|
||||
public void doesNotHaveBeanOfNameWhenHasBeanOfTypeShouldFail() {
|
||||
this.context.registerSingleton("foo", Foo.class);
|
||||
assertThatExceptionOfType(AssertionError.class)
|
||||
.isThrownBy(
|
||||
() -> assertThat(getAssert(this.context)).doesNotHaveBean("foo"))
|
||||
.isThrownBy(() -> assertThat(getAssert(this.context)).doesNotHaveBean("foo"))
|
||||
.withMessageContaining("but found");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void doesNotHaveBeanOfNameWhenFailedToStartShouldFail() {
|
||||
assertThatExceptionOfType(AssertionError.class)
|
||||
.isThrownBy(
|
||||
() -> assertThat(getAssert(this.failure)).doesNotHaveBean("foo"))
|
||||
.withMessageContaining("not to have any beans of name")
|
||||
.withMessageContaining("failed to start");
|
||||
.isThrownBy(() -> assertThat(getAssert(this.failure)).doesNotHaveBean("foo"))
|
||||
.withMessageContaining("not to have any beans of name").withMessageContaining("failed to start");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void getBeanNamesWhenHasNamesShouldReturnNamesAssert() {
|
||||
this.context.registerSingleton("foo", Foo.class);
|
||||
this.context.registerSingleton("bar", Foo.class);
|
||||
assertThat(getAssert(this.context)).getBeanNames(Foo.class).containsOnly("foo",
|
||||
"bar");
|
||||
assertThat(getAssert(this.context)).getBeanNames(Foo.class).containsOnly("foo", "bar");
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -221,11 +211,9 @@ public class ApplicationContextAssertTests {
|
||||
@Test
|
||||
public void getBeanNamesWhenFailedToStartShouldFail() {
|
||||
assertThatExceptionOfType(AssertionError.class)
|
||||
.isThrownBy(
|
||||
() -> assertThat(getAssert(this.failure)).doesNotHaveBean("foo"))
|
||||
.isThrownBy(() -> assertThat(getAssert(this.failure)).doesNotHaveBean("foo"))
|
||||
.withMessageContaining("not to have any beans of name")
|
||||
.withMessageContaining(String.format(
|
||||
"but context failed to start:%n java.lang.RuntimeException"));
|
||||
.withMessageContaining(String.format("but context failed to start:%n java.lang.RuntimeException"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -250,8 +238,7 @@ public class ApplicationContextAssertTests {
|
||||
|
||||
@Test
|
||||
public void getBeanOfTypeWhenHasPrimaryBeanShouldReturnPrimary() {
|
||||
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(
|
||||
PrimaryFooConfig.class);
|
||||
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(PrimaryFooConfig.class);
|
||||
assertThat(getAssert(context)).getBean(Foo.class).isInstanceOf(Bar.class);
|
||||
context.close();
|
||||
}
|
||||
@@ -261,8 +248,7 @@ public class ApplicationContextAssertTests {
|
||||
assertThatExceptionOfType(AssertionError.class)
|
||||
.isThrownBy(() -> assertThat(getAssert(this.failure)).getBean(Foo.class))
|
||||
.withMessageContaining("to contain bean of type")
|
||||
.withMessageContaining(String.format(
|
||||
"but context failed to start:%n java.lang.RuntimeException"));
|
||||
.withMessageContaining(String.format("but context failed to start:%n java.lang.RuntimeException"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -274,8 +260,7 @@ public class ApplicationContextAssertTests {
|
||||
@Test
|
||||
public void getBeanOfTypeWhenInParentWithLimitedScopeShouldReturnNullAssert() {
|
||||
this.parent.registerSingleton("foo", Foo.class);
|
||||
assertThat(getAssert(this.context)).getBean(Foo.class, Scope.NO_ANCESTORS)
|
||||
.isNull();
|
||||
assertThat(getAssert(this.context)).getBean(Foo.class, Scope.NO_ANCESTORS).isNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -291,8 +276,7 @@ public class ApplicationContextAssertTests {
|
||||
public void getBeanOfTypeWithLimitedScopeWhenHasMultipleBeansIncludingParentShouldReturnBeanAssert() {
|
||||
this.parent.registerSingleton("foo", Foo.class);
|
||||
this.context.registerSingleton("bar", Foo.class);
|
||||
assertThat(getAssert(this.context)).getBean(Foo.class, Scope.NO_ANCESTORS)
|
||||
.isNotNull();
|
||||
assertThat(getAssert(this.context)).getBean(Foo.class, Scope.NO_ANCESTORS).isNotNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -311,8 +295,7 @@ public class ApplicationContextAssertTests {
|
||||
assertThatExceptionOfType(AssertionError.class)
|
||||
.isThrownBy(() -> assertThat(getAssert(this.failure)).getBean("foo"))
|
||||
.withMessageContaining("to contain a bean of name")
|
||||
.withMessageContaining(String.format(
|
||||
"but context failed to start:%n java.lang.RuntimeException"));
|
||||
.withMessageContaining(String.format("but context failed to start:%n java.lang.RuntimeException"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -329,27 +312,24 @@ public class ApplicationContextAssertTests {
|
||||
@Test
|
||||
public void getBeanOfNameAndTypeWhenHasNoBeanOfNameButDifferentTypeShouldFail() {
|
||||
this.context.registerSingleton("foo", Foo.class);
|
||||
assertThatExceptionOfType(AssertionError.class).isThrownBy(
|
||||
() -> assertThat(getAssert(this.context)).getBean("foo", String.class))
|
||||
assertThatExceptionOfType(AssertionError.class)
|
||||
.isThrownBy(() -> assertThat(getAssert(this.context)).getBean("foo", String.class))
|
||||
.withMessageContaining("of type");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void getBeanOfNameAndTypeWhenFailedToStartShouldFail() {
|
||||
assertThatExceptionOfType(AssertionError.class)
|
||||
.isThrownBy(() -> assertThat(getAssert(this.failure)).getBean("foo",
|
||||
Foo.class))
|
||||
.isThrownBy(() -> assertThat(getAssert(this.failure)).getBean("foo", Foo.class))
|
||||
.withMessageContaining("to contain a bean of name")
|
||||
.withMessageContaining(String.format(
|
||||
"but context failed to start:%n java.lang.RuntimeException"));
|
||||
.withMessageContaining(String.format("but context failed to start:%n java.lang.RuntimeException"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void getBeansWhenHasBeansShouldReturnMapAssert() {
|
||||
this.context.registerSingleton("foo", Foo.class);
|
||||
this.context.registerSingleton("bar", Foo.class);
|
||||
assertThat(getAssert(this.context)).getBeans(Foo.class).hasSize(2)
|
||||
.containsKeys("foo", "bar");
|
||||
assertThat(getAssert(this.context)).getBeans(Foo.class).hasSize(2).containsKeys("foo", "bar");
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -362,24 +342,21 @@ public class ApplicationContextAssertTests {
|
||||
assertThatExceptionOfType(AssertionError.class)
|
||||
.isThrownBy(() -> assertThat(getAssert(this.failure)).getBeans(Foo.class))
|
||||
.withMessageContaining("to get beans of type")
|
||||
.withMessageContaining(String.format(
|
||||
"but context failed to start:%n java.lang.RuntimeException"));
|
||||
.withMessageContaining(String.format("but context failed to start:%n java.lang.RuntimeException"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void getBeansShouldIncludeBeansFromParentScope() {
|
||||
this.parent.registerSingleton("foo", Foo.class);
|
||||
this.context.registerSingleton("bar", Foo.class);
|
||||
assertThat(getAssert(this.context)).getBeans(Foo.class).hasSize(2)
|
||||
.containsKeys("foo", "bar");
|
||||
assertThat(getAssert(this.context)).getBeans(Foo.class).hasSize(2).containsKeys("foo", "bar");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void getBeansWithLimitedScopeShouldNotIncludeBeansFromParentScope() {
|
||||
this.parent.registerSingleton("foo", Foo.class);
|
||||
this.context.registerSingleton("bar", Foo.class);
|
||||
assertThat(getAssert(this.context)).getBeans(Foo.class, Scope.NO_ANCESTORS)
|
||||
.hasSize(1).containsKeys("bar");
|
||||
assertThat(getAssert(this.context)).getBeans(Foo.class, Scope.NO_ANCESTORS).hasSize(1).containsKeys("bar");
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -411,8 +388,7 @@ public class ApplicationContextAssertTests {
|
||||
assertThatExceptionOfType(AssertionError.class)
|
||||
.isThrownBy(() -> assertThat(getAssert(this.failure)).hasNotFailed())
|
||||
.withMessageContaining("to have not failed")
|
||||
.withMessageContaining(String.format(
|
||||
"but context failed to start:%n java.lang.RuntimeException"));
|
||||
.withMessageContaining(String.format("but context failed to start:%n java.lang.RuntimeException"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -420,8 +396,7 @@ public class ApplicationContextAssertTests {
|
||||
assertThat(getAssert(this.context)).hasNotFailed();
|
||||
}
|
||||
|
||||
private AssertableApplicationContext getAssert(
|
||||
ConfigurableApplicationContext applicationContext) {
|
||||
private AssertableApplicationContext getAssert(ConfigurableApplicationContext applicationContext) {
|
||||
return AssertableApplicationContext.get(() -> applicationContext);
|
||||
}
|
||||
|
||||
|
||||
@@ -39,12 +39,10 @@ public class SpringBootTestContextBootstrapperTests {
|
||||
@Test
|
||||
public void springBootTestWithANonMockWebEnvironmentAndWebAppConfigurationFailsFast() {
|
||||
assertThatIllegalStateException()
|
||||
.isThrownBy(() -> buildTestContext(
|
||||
SpringBootTestNonMockWebEnvironmentAndWebAppConfiguration.class))
|
||||
.isThrownBy(() -> buildTestContext(SpringBootTestNonMockWebEnvironmentAndWebAppConfiguration.class))
|
||||
.withMessageContaining("@WebAppConfiguration should only be used with "
|
||||
+ "@SpringBootTest when @SpringBootTest is configured with a mock web "
|
||||
+ "environment. Please remove @WebAppConfiguration or reconfigure "
|
||||
+ "@SpringBootTest.");
|
||||
+ "environment. Please remove @WebAppConfiguration or reconfigure " + "@SpringBootTest.");
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -58,10 +56,8 @@ public class SpringBootTestContextBootstrapperTests {
|
||||
BootstrapContext bootstrapContext = mock(BootstrapContext.class);
|
||||
bootstrapper.setBootstrapContext(bootstrapContext);
|
||||
given((Class) bootstrapContext.getTestClass()).willReturn(testClass);
|
||||
CacheAwareContextLoaderDelegate contextLoaderDelegate = mock(
|
||||
CacheAwareContextLoaderDelegate.class);
|
||||
given(bootstrapContext.getCacheAwareContextLoaderDelegate())
|
||||
.willReturn(contextLoaderDelegate);
|
||||
CacheAwareContextLoaderDelegate contextLoaderDelegate = mock(CacheAwareContextLoaderDelegate.class);
|
||||
given(bootstrapContext.getCacheAwareContextLoaderDelegate()).willReturn(contextLoaderDelegate);
|
||||
bootstrapper.buildTestContext();
|
||||
}
|
||||
|
||||
|
||||
@@ -47,15 +47,13 @@ public class SpringBootTestContextBootstrapperWithInitializersTests {
|
||||
|
||||
@Test
|
||||
public void foundConfiguration() {
|
||||
Object bean = this.context
|
||||
.getBean(SpringBootTestContextBootstrapperExampleConfig.class);
|
||||
Object bean = this.context.getBean(SpringBootTestContextBootstrapperExampleConfig.class);
|
||||
assertThat(bean).isNotNull();
|
||||
}
|
||||
|
||||
// gh-8483
|
||||
|
||||
public static class CustomInitializer
|
||||
implements ApplicationContextInitializer<ConfigurableApplicationContext> {
|
||||
public static class CustomInitializer implements ApplicationContextInitializer<ConfigurableApplicationContext> {
|
||||
|
||||
@Override
|
||||
public void initialize(ConfigurableApplicationContext applicationContext) {
|
||||
|
||||
@@ -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.
|
||||
@@ -28,8 +28,7 @@ import org.springframework.test.context.support.AbstractTestExecutionListener;
|
||||
*
|
||||
* @author Phillip Webb
|
||||
*/
|
||||
public class TestDefaultTestExecutionListenersPostProcessor
|
||||
implements DefaultTestExecutionListenersPostProcessor {
|
||||
public class TestDefaultTestExecutionListenersPostProcessor implements DefaultTestExecutionListenersPostProcessor {
|
||||
|
||||
@Override
|
||||
public Set<Class<? extends TestExecutionListener>> postProcessDefaultTestExecutionListeners(
|
||||
|
||||
@@ -41,68 +41,57 @@ public class TestTypeExcludeFilterTests {
|
||||
|
||||
@Test
|
||||
public void matchesJUnit4TestClass() throws Exception {
|
||||
assertThat(this.filter.match(getMetadataReader(TestTypeExcludeFilterTests.class),
|
||||
this.metadataReaderFactory)).isTrue();
|
||||
assertThat(this.filter.match(getMetadataReader(TestTypeExcludeFilterTests.class), this.metadataReaderFactory))
|
||||
.isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void matchesJUnitJupiterTestClass() throws Exception {
|
||||
assertThat(this.filter.match(getMetadataReader(JupiterTestExample.class),
|
||||
this.metadataReaderFactory)).isTrue();
|
||||
assertThat(this.filter.match(getMetadataReader(JupiterTestExample.class), this.metadataReaderFactory)).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void matchesJUnitJupiterRepeatedTestClass() throws Exception {
|
||||
assertThat(this.filter.match(getMetadataReader(JupiterRepeatedTestExample.class),
|
||||
this.metadataReaderFactory)).isTrue();
|
||||
assertThat(this.filter.match(getMetadataReader(JupiterRepeatedTestExample.class), this.metadataReaderFactory))
|
||||
.isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void matchesJUnitJupiterTestFactoryClass() throws Exception {
|
||||
assertThat(this.filter.match(getMetadataReader(JupiterTestFactoryExample.class),
|
||||
this.metadataReaderFactory)).isTrue();
|
||||
assertThat(this.filter.match(getMetadataReader(JupiterTestFactoryExample.class), this.metadataReaderFactory))
|
||||
.isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void matchesNestedConfiguration() throws Exception {
|
||||
assertThat(this.filter.match(getMetadataReader(NestedConfig.class),
|
||||
assertThat(this.filter.match(getMetadataReader(NestedConfig.class), this.metadataReaderFactory)).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void matchesNestedConfigurationClassWithoutTestMethodsIfItHasRunWith() throws Exception {
|
||||
assertThat(this.filter.match(getMetadataReader(AbstractTestWithConfigAndRunWith.Config.class),
|
||||
this.metadataReaderFactory)).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void matchesNestedConfigurationClassWithoutTestMethodsIfItHasRunWith()
|
||||
throws Exception {
|
||||
assertThat(this.filter.match(
|
||||
getMetadataReader(AbstractTestWithConfigAndRunWith.Config.class),
|
||||
this.metadataReaderFactory)).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void matchesNestedConfigurationClassWithoutTestMethodsIfItHasExtendWith()
|
||||
throws Exception {
|
||||
assertThat(this.filter.match(
|
||||
getMetadataReader(
|
||||
AbstractJupiterTestWithConfigAndExtendWith.Config.class),
|
||||
public void matchesNestedConfigurationClassWithoutTestMethodsIfItHasExtendWith() throws Exception {
|
||||
assertThat(this.filter.match(getMetadataReader(AbstractJupiterTestWithConfigAndExtendWith.Config.class),
|
||||
this.metadataReaderFactory)).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void matchesTestConfiguration() throws Exception {
|
||||
assertThat(this.filter.match(getMetadataReader(SampleTestConfig.class),
|
||||
this.metadataReaderFactory)).isTrue();
|
||||
assertThat(this.filter.match(getMetadataReader(SampleTestConfig.class), this.metadataReaderFactory)).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void doesNotMatchRegularConfiguration() throws Exception {
|
||||
assertThat(this.filter.match(getMetadataReader(SampleConfig.class),
|
||||
this.metadataReaderFactory)).isFalse();
|
||||
assertThat(this.filter.match(getMetadataReader(SampleConfig.class), this.metadataReaderFactory)).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void matchesNestedConfigurationClassWithoutTestNgAnnotation()
|
||||
throws Exception {
|
||||
assertThat(this.filter.match(
|
||||
getMetadataReader(AbstractTestNgTestWithConfig.Config.class),
|
||||
public void matchesNestedConfigurationClassWithoutTestNgAnnotation() throws Exception {
|
||||
assertThat(this.filter.match(getMetadataReader(AbstractTestNgTestWithConfig.Config.class),
|
||||
this.metadataReaderFactory)).isTrue();
|
||||
}
|
||||
|
||||
|
||||
@@ -64,8 +64,7 @@ public abstract class AbstractApplicationContextRunnerTests<T extends AbstractAp
|
||||
String key = "test." + UUID.randomUUID();
|
||||
assertThat(System.getProperties().containsKey(key)).isFalse();
|
||||
get().withSystemProperties(key + "=value")
|
||||
.run((context) -> assertThat(System.getProperties()).containsEntry(key,
|
||||
"value"));
|
||||
.run((context) -> assertThat(System.getProperties()).containsEntry(key, "value"));
|
||||
assertThat(System.getProperties().containsKey(key)).isFalse();
|
||||
}
|
||||
|
||||
@@ -73,8 +72,7 @@ public abstract class AbstractApplicationContextRunnerTests<T extends AbstractAp
|
||||
public void runWithSystemPropertiesWhenContextFailsShouldRemoveProperties() {
|
||||
String key = "test." + UUID.randomUUID();
|
||||
assertThat(System.getProperties().containsKey(key)).isFalse();
|
||||
get().withSystemProperties(key + "=value")
|
||||
.withUserConfiguration(FailingConfig.class)
|
||||
get().withSystemProperties(key + "=value").withUserConfiguration(FailingConfig.class)
|
||||
.run((context) -> assertThat(context).hasFailed());
|
||||
assertThat(System.getProperties().containsKey(key)).isFalse();
|
||||
}
|
||||
@@ -86,8 +84,7 @@ public abstract class AbstractApplicationContextRunnerTests<T extends AbstractAp
|
||||
try {
|
||||
assertThat(System.getProperties().getProperty(key)).isEqualTo("value");
|
||||
get().withSystemProperties(key + "=newValue")
|
||||
.run((context) -> assertThat(System.getProperties())
|
||||
.containsEntry(key, "newValue"));
|
||||
.run((context) -> assertThat(System.getProperties()).containsEntry(key, "newValue"));
|
||||
assertThat(System.getProperties().getProperty(key)).isEqualTo("value");
|
||||
}
|
||||
finally {
|
||||
@@ -102,8 +99,7 @@ public abstract class AbstractApplicationContextRunnerTests<T extends AbstractAp
|
||||
try {
|
||||
assertThat(System.getProperties().getProperty(key)).isEqualTo("value");
|
||||
get().withSystemProperties(key + "=")
|
||||
.run((context) -> assertThat(System.getProperties())
|
||||
.doesNotContainKey(key));
|
||||
.run((context) -> assertThat(System.getProperties()).doesNotContainKey(key));
|
||||
assertThat(System.getProperties().getProperty(key)).isEqualTo("value");
|
||||
}
|
||||
finally {
|
||||
@@ -113,39 +109,34 @@ public abstract class AbstractApplicationContextRunnerTests<T extends AbstractAp
|
||||
|
||||
@Test
|
||||
public void runWithMultiplePropertyValuesShouldAllAllValues() {
|
||||
get().withPropertyValues("test.foo=1").withPropertyValues("test.bar=2")
|
||||
.run((context) -> {
|
||||
Environment environment = context.getEnvironment();
|
||||
assertThat(environment.getProperty("test.foo")).isEqualTo("1");
|
||||
assertThat(environment.getProperty("test.bar")).isEqualTo("2");
|
||||
});
|
||||
get().withPropertyValues("test.foo=1").withPropertyValues("test.bar=2").run((context) -> {
|
||||
Environment environment = context.getEnvironment();
|
||||
assertThat(environment.getProperty("test.foo")).isEqualTo("1");
|
||||
assertThat(environment.getProperty("test.bar")).isEqualTo("2");
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
public void runWithPropertyValuesWhenHasExistingShouldReplaceValue() {
|
||||
get().withPropertyValues("test.foo=1").withPropertyValues("test.foo=2")
|
||||
.run((context) -> {
|
||||
Environment environment = context.getEnvironment();
|
||||
assertThat(environment.getProperty("test.foo")).isEqualTo("2");
|
||||
});
|
||||
get().withPropertyValues("test.foo=1").withPropertyValues("test.foo=2").run((context) -> {
|
||||
Environment environment = context.getEnvironment();
|
||||
assertThat(environment.getProperty("test.foo")).isEqualTo("2");
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
public void runWithConfigurationsShouldRegisterConfigurations() {
|
||||
get().withUserConfiguration(FooConfig.class)
|
||||
.run((context) -> assertThat(context).hasBean("foo"));
|
||||
get().withUserConfiguration(FooConfig.class).run((context) -> assertThat(context).hasBean("foo"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void runWithUserNamedBeanShouldRegisterBean() {
|
||||
get().withBean("foo", String.class, () -> "foo")
|
||||
.run((context) -> assertThat(context).hasBean("foo"));
|
||||
get().withBean("foo", String.class, () -> "foo").run((context) -> assertThat(context).hasBean("foo"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void runWithUserBeanShouldRegisterBeanWithDefaultName() {
|
||||
get().withBean(String.class, () -> "foo")
|
||||
.run((context) -> assertThat(context).hasBean("string"));
|
||||
get().withBean(String.class, () -> "foo").run((context) -> assertThat(context).hasBean("string"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -159,8 +150,8 @@ public abstract class AbstractApplicationContextRunnerTests<T extends AbstractAp
|
||||
|
||||
@Test
|
||||
public void runWithConfigurationsAndUserBeanShouldRegisterUserBeanLast() {
|
||||
get().withUserConfiguration(FooConfig.class)
|
||||
.withBean("foo", String.class, () -> "overridden").run((context) -> {
|
||||
get().withUserConfiguration(FooConfig.class).withBean("foo", String.class, () -> "overridden")
|
||||
.run((context) -> {
|
||||
assertThat(context).hasBean("foo");
|
||||
assertThat(context.getBean("foo")).isEqualTo("overridden");
|
||||
});
|
||||
@@ -168,37 +159,32 @@ public abstract class AbstractApplicationContextRunnerTests<T extends AbstractAp
|
||||
|
||||
@Test
|
||||
public void runWithMultipleConfigurationsShouldRegisterAllConfigurations() {
|
||||
get().withUserConfiguration(FooConfig.class)
|
||||
.withConfiguration(UserConfigurations.of(BarConfig.class))
|
||||
get().withUserConfiguration(FooConfig.class).withConfiguration(UserConfigurations.of(BarConfig.class))
|
||||
.run((context) -> assertThat(context).hasBean("foo").hasBean("bar"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void runWithFailedContextShouldReturnFailedAssertableContext() {
|
||||
get().withUserConfiguration(FailingConfig.class)
|
||||
.run((context) -> assertThat(context).hasFailed());
|
||||
get().withUserConfiguration(FailingConfig.class).run((context) -> assertThat(context).hasFailed());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void runWithClassLoaderShouldSetClassLoaderOnContext() {
|
||||
get().withClassLoader(new FilteredClassLoader(Gson.class.getPackage().getName()))
|
||||
.run((context) -> assertThatExceptionOfType(ClassNotFoundException.class)
|
||||
.isThrownBy(() -> ClassUtils.forName(Gson.class.getName(),
|
||||
context.getClassLoader())));
|
||||
.isThrownBy(() -> ClassUtils.forName(Gson.class.getName(), context.getClassLoader())));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void runWithClassLoaderShouldSetClassLoaderOnConditionContext() {
|
||||
get().withClassLoader(new FilteredClassLoader(Gson.class.getPackage().getName()))
|
||||
.withUserConfiguration(ConditionalConfig.class)
|
||||
.run((context) -> assertThat(context)
|
||||
.hasSingleBean(ConditionalConfig.class));
|
||||
.run((context) -> assertThat(context).hasSingleBean(ConditionalConfig.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void thrownRuleWorksWithCheckedException() {
|
||||
get().run((context) -> assertThatIOException()
|
||||
.isThrownBy(() -> throwCheckedException("Expected message"))
|
||||
get().run((context) -> assertThatIOException().isThrownBy(() -> throwCheckedException("Expected message"))
|
||||
.withMessageContaining("Expected message"));
|
||||
}
|
||||
|
||||
|
||||
@@ -35,8 +35,7 @@ public class WebApplicationContextRunnerTests extends
|
||||
|
||||
@Test
|
||||
public void contextShouldHaveMockServletContext() {
|
||||
get().run((context) -> assertThat(context.getServletContext())
|
||||
.isInstanceOf(MockServletContext.class));
|
||||
get().run((context) -> assertThat(context.getServletContext()).isInstanceOf(MockServletContext.class));
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
@@ -55,8 +55,7 @@ public abstract class AbstractJsonMarshalTesterTests {
|
||||
|
||||
private static final ExampleObject OBJECT = createExampleObject("Spring", 123);
|
||||
|
||||
private static final ResolvableType TYPE = ResolvableType
|
||||
.forClass(ExampleObject.class);
|
||||
private static final ResolvableType TYPE = ResolvableType.forClass(ExampleObject.class);
|
||||
|
||||
@Test
|
||||
public void writeShouldReturnJsonContent() throws Exception {
|
||||
@@ -91,15 +90,14 @@ public abstract class AbstractJsonMarshalTesterTests {
|
||||
|
||||
@Test
|
||||
public void createWhenResourceLoadClassIsNullShouldThrowException() {
|
||||
assertThatIllegalArgumentException().isThrownBy(
|
||||
() -> createTester(null, ResolvableType.forClass(ExampleObject.class)))
|
||||
assertThatIllegalArgumentException()
|
||||
.isThrownBy(() -> createTester(null, ResolvableType.forClass(ExampleObject.class)))
|
||||
.withMessageContaining("ResourceLoadClass must not be null");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void createWhenTypeIsNullShouldThrowException() {
|
||||
assertThatIllegalArgumentException()
|
||||
.isThrownBy(() -> createTester(getClass(), null))
|
||||
assertThatIllegalArgumentException().isThrownBy(() -> createTester(getClass(), null))
|
||||
.withMessageContaining("Type must not be null");
|
||||
}
|
||||
|
||||
@@ -182,8 +180,7 @@ public abstract class AbstractJsonMarshalTesterTests {
|
||||
return createTester(AbstractJsonMarshalTesterTests.class, type);
|
||||
}
|
||||
|
||||
protected abstract AbstractJsonMarshalTester<Object> createTester(
|
||||
Class<?> resourceLoadClass, ResolvableType type);
|
||||
protected abstract AbstractJsonMarshalTester<Object> createTester(Class<?> resourceLoadClass, ResolvableType type);
|
||||
|
||||
/**
|
||||
* Access to field backed by {@link ResolvableType}.
|
||||
|
||||
@@ -40,10 +40,10 @@ public class DuplicateJsonObjectContextCustomizerFactoryTests {
|
||||
|
||||
@Test
|
||||
public void warningForMultipleVersions() {
|
||||
new DuplicateJsonObjectContextCustomizerFactory()
|
||||
.createContextCustomizer(null, null).customizeContext(null, null);
|
||||
assertThat(this.output.toString()).contains(
|
||||
"Found multiple occurrences of org.json.JSONObject on the class path:");
|
||||
new DuplicateJsonObjectContextCustomizerFactory().createContextCustomizer(null, null).customizeContext(null,
|
||||
null);
|
||||
assertThat(this.output.toString())
|
||||
.contains("Found multiple occurrences of org.json.JSONObject on the class path:");
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -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,8 +49,7 @@ public class ExampleObject {
|
||||
return false;
|
||||
}
|
||||
ExampleObject other = (ExampleObject) obj;
|
||||
return ObjectUtils.nullSafeEquals(this.name, other.name)
|
||||
&& ObjectUtils.nullSafeEquals(this.age, other.age);
|
||||
return ObjectUtils.nullSafeEquals(this.name, other.name) && ObjectUtils.nullSafeEquals(this.age, other.age);
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
@@ -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,8 +54,7 @@ public class ExampleObjectWithView {
|
||||
return false;
|
||||
}
|
||||
ExampleObjectWithView other = (ExampleObjectWithView) obj;
|
||||
return ObjectUtils.nullSafeEquals(this.name, other.name)
|
||||
&& ObjectUtils.nullSafeEquals(this.age, other.age);
|
||||
return ObjectUtils.nullSafeEquals(this.name, other.name) && ObjectUtils.nullSafeEquals(this.age, other.age);
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
@@ -55,16 +55,14 @@ public class GsonTesterIntegrationTests {
|
||||
@Test
|
||||
public void typicalTest() throws Exception {
|
||||
String example = JSON;
|
||||
assertThat(this.simpleJson.parse(example).getObject().getName())
|
||||
.isEqualTo("Spring");
|
||||
assertThat(this.simpleJson.parse(example).getObject().getName()).isEqualTo("Spring");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void typicalListTest() throws Exception {
|
||||
String example = "[" + JSON + "]";
|
||||
assertThat(this.listJson.parse(example)).asList().hasSize(1);
|
||||
assertThat(this.listJson.parse(example).getObject().get(0).getName())
|
||||
.isEqualTo("Spring");
|
||||
assertThat(this.listJson.parse(example).getObject().get(0).getName()).isEqualTo("Spring");
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -72,15 +70,13 @@ public class GsonTesterIntegrationTests {
|
||||
Map<String, Integer> map = new LinkedHashMap<>();
|
||||
map.put("a", 1);
|
||||
map.put("b", 2);
|
||||
assertThat(this.mapJson.write(map)).extractingJsonPathNumberValue("@.a")
|
||||
.isEqualTo(1);
|
||||
assertThat(this.mapJson.write(map)).extractingJsonPathNumberValue("@.a").isEqualTo(1);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void stringLiteral() throws Exception {
|
||||
String stringWithSpecialCharacters = "myString";
|
||||
assertThat(this.stringJson.write(stringWithSpecialCharacters))
|
||||
.extractingJsonPathStringValue("@")
|
||||
assertThat(this.stringJson.write(stringWithSpecialCharacters)).extractingJsonPathStringValue("@")
|
||||
.isEqualTo(stringWithSpecialCharacters);
|
||||
}
|
||||
|
||||
|
||||
@@ -36,15 +36,14 @@ public class GsonTesterTests extends AbstractJsonMarshalTesterTests {
|
||||
|
||||
@Test
|
||||
public void initFieldsWhenTestIsNullShouldThrowException() {
|
||||
assertThatIllegalArgumentException()
|
||||
.isThrownBy(() -> GsonTester.initFields(null, new GsonBuilder().create()))
|
||||
assertThatIllegalArgumentException().isThrownBy(() -> GsonTester.initFields(null, new GsonBuilder().create()))
|
||||
.withMessageContaining("TestInstance must not be null");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void initFieldsWhenMarshallerIsNullShouldThrowException() {
|
||||
assertThatIllegalArgumentException().isThrownBy(
|
||||
() -> GsonTester.initFields(new InitFieldsTestClass(), (Gson) null))
|
||||
assertThatIllegalArgumentException()
|
||||
.isThrownBy(() -> GsonTester.initFields(new InitFieldsTestClass(), (Gson) null))
|
||||
.withMessageContaining("Marshaller must not be null");
|
||||
}
|
||||
|
||||
@@ -61,8 +60,7 @@ public class GsonTesterTests extends AbstractJsonMarshalTesterTests {
|
||||
}
|
||||
|
||||
@Override
|
||||
protected AbstractJsonMarshalTester<Object> createTester(Class<?> resourceLoadClass,
|
||||
ResolvableType type) {
|
||||
protected AbstractJsonMarshalTester<Object> createTester(Class<?> resourceLoadClass, ResolvableType type) {
|
||||
return new GsonTester<>(resourceLoadClass, type, new GsonBuilder().create());
|
||||
}
|
||||
|
||||
@@ -70,9 +68,8 @@ public class GsonTesterTests extends AbstractJsonMarshalTesterTests {
|
||||
|
||||
public GsonTester<ExampleObject> base;
|
||||
|
||||
public GsonTester<ExampleObject> baseSet = new GsonTester<>(
|
||||
InitFieldsBaseClass.class, ResolvableType.forClass(ExampleObject.class),
|
||||
new GsonBuilder().create());
|
||||
public GsonTester<ExampleObject> baseSet = new GsonTester<>(InitFieldsBaseClass.class,
|
||||
ResolvableType.forClass(ExampleObject.class), new GsonBuilder().create());
|
||||
|
||||
}
|
||||
|
||||
@@ -80,9 +77,8 @@ public class GsonTesterTests extends AbstractJsonMarshalTesterTests {
|
||||
|
||||
public GsonTester<List<ExampleObject>> test;
|
||||
|
||||
public GsonTester<ExampleObject> testSet = new GsonTester<>(
|
||||
InitFieldsBaseClass.class, ResolvableType.forClass(ExampleObject.class),
|
||||
new GsonBuilder().create());
|
||||
public GsonTester<ExampleObject> testSet = new GsonTester<>(InitFieldsBaseClass.class,
|
||||
ResolvableType.forClass(ExampleObject.class), new GsonBuilder().create());
|
||||
|
||||
}
|
||||
|
||||
|
||||
@@ -63,16 +63,14 @@ public class JacksonTesterIntegrationTests {
|
||||
@Test
|
||||
public void typicalTest() throws Exception {
|
||||
String example = JSON;
|
||||
assertThat(this.simpleJson.parse(example).getObject().getName())
|
||||
.isEqualTo("Spring");
|
||||
assertThat(this.simpleJson.parse(example).getObject().getName()).isEqualTo("Spring");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void typicalListTest() throws Exception {
|
||||
String example = "[" + JSON + "]";
|
||||
assertThat(this.listJson.parse(example)).asList().hasSize(1);
|
||||
assertThat(this.listJson.parse(example).getObject().get(0).getName())
|
||||
.isEqualTo("Spring");
|
||||
assertThat(this.listJson.parse(example).getObject().get(0).getName()).isEqualTo("Spring");
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -80,15 +78,13 @@ public class JacksonTesterIntegrationTests {
|
||||
Map<String, Integer> map = new LinkedHashMap<>();
|
||||
map.put("a", 1);
|
||||
map.put("b", 2);
|
||||
assertThat(this.mapJson.write(map)).extractingJsonPathNumberValue("@.a")
|
||||
.isEqualTo(1);
|
||||
assertThat(this.mapJson.write(map)).extractingJsonPathNumberValue("@.a").isEqualTo(1);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void stringLiteral() throws Exception {
|
||||
String stringWithSpecialCharacters = "myString";
|
||||
assertThat(this.stringJson.write(stringWithSpecialCharacters))
|
||||
.extractingJsonPathStringValue("@")
|
||||
assertThat(this.stringJson.write(stringWithSpecialCharacters)).extractingJsonPathStringValue("@")
|
||||
.isEqualTo(stringWithSpecialCharacters);
|
||||
}
|
||||
|
||||
@@ -101,8 +97,7 @@ public class JacksonTesterIntegrationTests {
|
||||
// configures json-path to use Jackson for evaluating the path expressions and
|
||||
// restores the symmetry. See gh-15727
|
||||
String stringWithSpecialCharacters = "\u0006\u007F";
|
||||
assertThat(this.stringJson.write(stringWithSpecialCharacters))
|
||||
.extractingJsonPathStringValue("@")
|
||||
assertThat(this.stringJson.write(stringWithSpecialCharacters)).extractingJsonPathStringValue("@")
|
||||
.isEqualTo(stringWithSpecialCharacters);
|
||||
}
|
||||
|
||||
@@ -112,8 +107,8 @@ public class JacksonTesterIntegrationTests {
|
||||
ExampleObjectWithView object = new ExampleObjectWithView();
|
||||
object.setName("Spring");
|
||||
object.setAge(123);
|
||||
JsonContent<ExampleObjectWithView> content = this.jsonWithView
|
||||
.forView(ExampleObjectWithView.TestView.class).write(object);
|
||||
JsonContent<ExampleObjectWithView> content = this.jsonWithView.forView(ExampleObjectWithView.TestView.class)
|
||||
.write(object);
|
||||
assertThat(content).extractingJsonPathStringValue("@.name").isEqualTo("Spring");
|
||||
assertThat(content).doesNotHaveJsonPathValue("age");
|
||||
}
|
||||
@@ -122,8 +117,8 @@ public class JacksonTesterIntegrationTests {
|
||||
public void readWithResourceAndView() throws Exception {
|
||||
this.objectMapper.disable(MapperFeature.DEFAULT_VIEW_INCLUSION);
|
||||
ByteArrayResource resource = new ByteArrayResource(JSON.getBytes());
|
||||
ObjectContent<ExampleObjectWithView> content = this.jsonWithView
|
||||
.forView(ExampleObjectWithView.TestView.class).read(resource);
|
||||
ObjectContent<ExampleObjectWithView> content = this.jsonWithView.forView(ExampleObjectWithView.TestView.class)
|
||||
.read(resource);
|
||||
assertThat(content.getObject().getName()).isEqualTo("Spring");
|
||||
assertThat(content.getObject().getAge()).isEqualTo(0);
|
||||
}
|
||||
@@ -132,8 +127,8 @@ public class JacksonTesterIntegrationTests {
|
||||
public void readWithReaderAndView() throws Exception {
|
||||
this.objectMapper.disable(MapperFeature.DEFAULT_VIEW_INCLUSION);
|
||||
Reader reader = new StringReader(JSON);
|
||||
ObjectContent<ExampleObjectWithView> content = this.jsonWithView
|
||||
.forView(ExampleObjectWithView.TestView.class).read(reader);
|
||||
ObjectContent<ExampleObjectWithView> content = this.jsonWithView.forView(ExampleObjectWithView.TestView.class)
|
||||
.read(reader);
|
||||
assertThat(content.getObject().getName()).isEqualTo("Spring");
|
||||
assertThat(content.getObject().getAge()).isEqualTo(0);
|
||||
}
|
||||
|
||||
@@ -35,16 +35,14 @@ public class JacksonTesterTests extends AbstractJsonMarshalTesterTests {
|
||||
|
||||
@Test
|
||||
public void initFieldsWhenTestIsNullShouldThrowException() {
|
||||
assertThatIllegalArgumentException()
|
||||
.isThrownBy(() -> JacksonTester.initFields(null, new ObjectMapper()))
|
||||
assertThatIllegalArgumentException().isThrownBy(() -> JacksonTester.initFields(null, new ObjectMapper()))
|
||||
.withMessageContaining("TestInstance must not be null");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void initFieldsWhenMarshallerIsNullShouldThrowException() {
|
||||
assertThatIllegalArgumentException()
|
||||
.isThrownBy(() -> JacksonTester.initFields(new InitFieldsTestClass(),
|
||||
(ObjectMapper) null))
|
||||
.isThrownBy(() -> JacksonTester.initFields(new InitFieldsTestClass(), (ObjectMapper) null))
|
||||
.withMessageContaining("Marshaller must not be null");
|
||||
}
|
||||
|
||||
@@ -61,8 +59,7 @@ public class JacksonTesterTests extends AbstractJsonMarshalTesterTests {
|
||||
}
|
||||
|
||||
@Override
|
||||
protected AbstractJsonMarshalTester<Object> createTester(Class<?> resourceLoadClass,
|
||||
ResolvableType type) {
|
||||
protected AbstractJsonMarshalTester<Object> createTester(Class<?> resourceLoadClass, ResolvableType type) {
|
||||
return new JacksonTester<>(resourceLoadClass, type, new ObjectMapper());
|
||||
}
|
||||
|
||||
@@ -70,9 +67,8 @@ public class JacksonTesterTests extends AbstractJsonMarshalTesterTests {
|
||||
|
||||
public JacksonTester<ExampleObject> base;
|
||||
|
||||
public JacksonTester<ExampleObject> baseSet = new JacksonTester<>(
|
||||
InitFieldsBaseClass.class, ResolvableType.forClass(ExampleObject.class),
|
||||
new ObjectMapper());
|
||||
public JacksonTester<ExampleObject> baseSet = new JacksonTester<>(InitFieldsBaseClass.class,
|
||||
ResolvableType.forClass(ExampleObject.class), new ObjectMapper());
|
||||
|
||||
}
|
||||
|
||||
@@ -80,9 +76,8 @@ public class JacksonTesterTests extends AbstractJsonMarshalTesterTests {
|
||||
|
||||
public JacksonTester<List<ExampleObject>> test;
|
||||
|
||||
public JacksonTester<ExampleObject> testSet = new JacksonTester<>(
|
||||
InitFieldsBaseClass.class, ResolvableType.forClass(ExampleObject.class),
|
||||
new ObjectMapper());
|
||||
public JacksonTester<ExampleObject> testSet = new JacksonTester<>(InitFieldsBaseClass.class,
|
||||
ResolvableType.forClass(ExampleObject.class), new ObjectMapper());
|
||||
|
||||
}
|
||||
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -33,29 +33,27 @@ public class JsonContentTests {
|
||||
|
||||
private static final String JSON = "{\"name\":\"spring\", \"age\":100}";
|
||||
|
||||
private static final ResolvableType TYPE = ResolvableType
|
||||
.forClass(ExampleObject.class);
|
||||
private static final ResolvableType TYPE = ResolvableType.forClass(ExampleObject.class);
|
||||
|
||||
@Test
|
||||
public void createWhenResourceLoadClassIsNullShouldThrowException() {
|
||||
assertThatIllegalArgumentException()
|
||||
.isThrownBy(() -> new JsonContent<ExampleObject>(null, TYPE, JSON,
|
||||
Configuration.defaultConfiguration()))
|
||||
.isThrownBy(
|
||||
() -> new JsonContent<ExampleObject>(null, TYPE, JSON, Configuration.defaultConfiguration()))
|
||||
.withMessageContaining("ResourceLoadClass must not be null");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void createWhenJsonIsNullShouldThrowException() {
|
||||
assertThatIllegalArgumentException()
|
||||
.isThrownBy(() -> new JsonContent<ExampleObject>(getClass(), TYPE, null,
|
||||
Configuration.defaultConfiguration()))
|
||||
assertThatIllegalArgumentException().isThrownBy(
|
||||
() -> new JsonContent<ExampleObject>(getClass(), TYPE, null, Configuration.defaultConfiguration()))
|
||||
.withMessageContaining("JSON must not be null");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void createWhenConfigurationIsNullShouldThrowException() {
|
||||
assertThatIllegalArgumentException().isThrownBy(
|
||||
() -> new JsonContent<ExampleObject>(getClass(), TYPE, JSON, null))
|
||||
assertThatIllegalArgumentException()
|
||||
.isThrownBy(() -> new JsonContent<ExampleObject>(getClass(), TYPE, JSON, null))
|
||||
.withMessageContaining("Configuration must not be null");
|
||||
}
|
||||
|
||||
@@ -86,8 +84,7 @@ public class JsonContentTests {
|
||||
public void toStringWhenHasTypeShouldReturnString() {
|
||||
JsonContent<ExampleObject> content = new JsonContent<>(getClass(), TYPE, JSON,
|
||||
Configuration.defaultConfiguration());
|
||||
assertThat(content.toString())
|
||||
.isEqualTo("JsonContent " + JSON + " created from " + TYPE);
|
||||
assertThat(content.toString()).isEqualTo("JsonContent " + JSON + " created from " + TYPE);
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
@@ -37,15 +37,14 @@ public class JsonbTesterTests extends AbstractJsonMarshalTesterTests {
|
||||
|
||||
@Test
|
||||
public void initFieldsWhenTestIsNullShouldThrowException() {
|
||||
assertThatIllegalArgumentException()
|
||||
.isThrownBy(() -> JsonbTester.initFields(null, JsonbBuilder.create()))
|
||||
assertThatIllegalArgumentException().isThrownBy(() -> JsonbTester.initFields(null, JsonbBuilder.create()))
|
||||
.withMessageContaining("TestInstance must not be null");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void initFieldsWhenMarshallerIsNullShouldThrowException() {
|
||||
assertThatIllegalArgumentException().isThrownBy(
|
||||
() -> JsonbTester.initFields(new InitFieldsTestClass(), (Jsonb) null))
|
||||
assertThatIllegalArgumentException()
|
||||
.isThrownBy(() -> JsonbTester.initFields(new InitFieldsTestClass(), (Jsonb) null))
|
||||
.withMessageContaining("Marshaller must not be null");
|
||||
}
|
||||
|
||||
@@ -62,8 +61,7 @@ public class JsonbTesterTests extends AbstractJsonMarshalTesterTests {
|
||||
}
|
||||
|
||||
@Override
|
||||
protected AbstractJsonMarshalTester<Object> createTester(Class<?> resourceLoadClass,
|
||||
ResolvableType type) {
|
||||
protected AbstractJsonMarshalTester<Object> createTester(Class<?> resourceLoadClass, ResolvableType type) {
|
||||
return new JsonbTester<>(resourceLoadClass, type, JsonbBuilder.create());
|
||||
}
|
||||
|
||||
@@ -71,9 +69,8 @@ public class JsonbTesterTests extends AbstractJsonMarshalTesterTests {
|
||||
|
||||
public JsonbTester<ExampleObject> base;
|
||||
|
||||
public JsonbTester<ExampleObject> baseSet = new JsonbTester<>(
|
||||
InitFieldsBaseClass.class, ResolvableType.forClass(ExampleObject.class),
|
||||
JsonbBuilder.create());
|
||||
public JsonbTester<ExampleObject> baseSet = new JsonbTester<>(InitFieldsBaseClass.class,
|
||||
ResolvableType.forClass(ExampleObject.class), JsonbBuilder.create());
|
||||
|
||||
}
|
||||
|
||||
@@ -81,9 +78,8 @@ public class JsonbTesterTests extends AbstractJsonMarshalTesterTests {
|
||||
|
||||
public JsonbTester<List<ExampleObject>> test;
|
||||
|
||||
public JsonbTester<ExampleObject> testSet = new JsonbTester<>(
|
||||
InitFieldsBaseClass.class, ResolvableType.forClass(ExampleObject.class),
|
||||
JsonbBuilder.create());
|
||||
public JsonbTester<ExampleObject> testSet = new JsonbTester<>(InitFieldsBaseClass.class,
|
||||
ResolvableType.forClass(ExampleObject.class), JsonbBuilder.create());
|
||||
|
||||
}
|
||||
|
||||
|
||||
@@ -60,8 +60,7 @@ public class ObjectContentAssertTests {
|
||||
|
||||
@Test
|
||||
public void asArrayForNonArrayShouldFail() {
|
||||
assertThatExceptionOfType(AssertionError.class)
|
||||
.isThrownBy(() -> assertThat(forObject(SOURCE)).asArray());
|
||||
assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> assertThat(forObject(SOURCE)).asArray());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -72,8 +71,7 @@ public class ObjectContentAssertTests {
|
||||
|
||||
@Test
|
||||
public void asMapForNonMapShouldFail() {
|
||||
assertThatExceptionOfType(AssertionError.class)
|
||||
.isThrownBy(() -> assertThat(forObject(SOURCE)).asMap());
|
||||
assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> assertThat(forObject(SOURCE)).asMap());
|
||||
}
|
||||
|
||||
private AssertProvider<ObjectContentAssert<Object>> forObject(Object source) {
|
||||
|
||||
@@ -32,13 +32,11 @@ public class ObjectContentTests {
|
||||
|
||||
private static final ExampleObject OBJECT = new ExampleObject();
|
||||
|
||||
private static final ResolvableType TYPE = ResolvableType
|
||||
.forClass(ExampleObject.class);
|
||||
private static final ResolvableType TYPE = ResolvableType.forClass(ExampleObject.class);
|
||||
|
||||
@Test
|
||||
public void createWhenObjectIsNullShouldThrowException() {
|
||||
assertThatIllegalArgumentException()
|
||||
.isThrownBy(() -> new ObjectContent<ExampleObject>(TYPE, null))
|
||||
assertThatIllegalArgumentException().isThrownBy(() -> new ObjectContent<ExampleObject>(TYPE, null))
|
||||
.withMessageContaining("Object must not be null");
|
||||
}
|
||||
|
||||
@@ -63,8 +61,7 @@ public class ObjectContentTests {
|
||||
@Test
|
||||
public void toStringWhenHasTypeShouldReturnString() {
|
||||
ObjectContent<ExampleObject> content = new ObjectContent<>(TYPE, OBJECT);
|
||||
assertThat(content.toString())
|
||||
.isEqualTo("ObjectContent " + OBJECT + " created from " + TYPE);
|
||||
assertThat(content.toString()).isEqualTo("ObjectContent " + OBJECT + " created from " + TYPE);
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
@@ -45,18 +45,15 @@ public class DefinitionsParserTests {
|
||||
public void parseSingleMockBean() {
|
||||
this.parser.parse(SingleMockBean.class);
|
||||
assertThat(getDefinitions()).hasSize(1);
|
||||
assertThat(getMockDefinition(0).getTypeToMock().resolve())
|
||||
.isEqualTo(ExampleService.class);
|
||||
assertThat(getMockDefinition(0).getTypeToMock().resolve()).isEqualTo(ExampleService.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void parseRepeatMockBean() {
|
||||
this.parser.parse(RepeatMockBean.class);
|
||||
assertThat(getDefinitions()).hasSize(2);
|
||||
assertThat(getMockDefinition(0).getTypeToMock().resolve())
|
||||
.isEqualTo(ExampleService.class);
|
||||
assertThat(getMockDefinition(1).getTypeToMock().resolve())
|
||||
.isEqualTo(ExampleServiceCaller.class);
|
||||
assertThat(getMockDefinition(0).getTypeToMock().resolve()).isEqualTo(ExampleService.class);
|
||||
assertThat(getMockDefinition(1).getTypeToMock().resolve()).isEqualTo(ExampleServiceCaller.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -66,8 +63,7 @@ public class DefinitionsParserTests {
|
||||
MockDefinition definition = getMockDefinition(0);
|
||||
assertThat(definition.getName()).isEqualTo("Name");
|
||||
assertThat(definition.getTypeToMock().resolve()).isEqualTo(ExampleService.class);
|
||||
assertThat(definition.getExtraInterfaces())
|
||||
.containsExactly(ExampleExtraInterface.class);
|
||||
assertThat(definition.getExtraInterfaces()).containsExactly(ExampleExtraInterface.class);
|
||||
assertThat(definition.getAnswer()).isEqualTo(Answers.RETURNS_SMART_NULLS);
|
||||
assertThat(definition.isSerializable()).isTrue();
|
||||
assertThat(definition.getReset()).isEqualTo(MockReset.NONE);
|
||||
@@ -79,14 +75,12 @@ public class DefinitionsParserTests {
|
||||
this.parser.parse(MockBeanOnClassAndField.class);
|
||||
assertThat(getDefinitions()).hasSize(2);
|
||||
MockDefinition classDefinition = getMockDefinition(0);
|
||||
assertThat(classDefinition.getTypeToMock().resolve())
|
||||
.isEqualTo(ExampleService.class);
|
||||
assertThat(classDefinition.getTypeToMock().resolve()).isEqualTo(ExampleService.class);
|
||||
assertThat(classDefinition.getQualifier()).isNull();
|
||||
MockDefinition fieldDefinition = getMockDefinition(1);
|
||||
assertThat(fieldDefinition.getTypeToMock().resolve())
|
||||
.isEqualTo(ExampleServiceCaller.class);
|
||||
QualifierDefinition qualifier = QualifierDefinition.forElement(
|
||||
ReflectionUtils.findField(MockBeanOnClassAndField.class, "caller"));
|
||||
assertThat(fieldDefinition.getTypeToMock().resolve()).isEqualTo(ExampleServiceCaller.class);
|
||||
QualifierDefinition qualifier = QualifierDefinition
|
||||
.forElement(ReflectionUtils.findField(MockBeanOnClassAndField.class, "caller"));
|
||||
assertThat(fieldDefinition.getQualifier()).isNotNull().isEqualTo(qualifier);
|
||||
}
|
||||
|
||||
@@ -94,14 +88,12 @@ public class DefinitionsParserTests {
|
||||
public void parseMockBeanInferClassToMock() {
|
||||
this.parser.parse(MockBeanInferClassToMock.class);
|
||||
assertThat(getDefinitions()).hasSize(1);
|
||||
assertThat(getMockDefinition(0).getTypeToMock().resolve())
|
||||
.isEqualTo(ExampleService.class);
|
||||
assertThat(getMockDefinition(0).getTypeToMock().resolve()).isEqualTo(ExampleService.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void parseMockBeanMissingClassToMock() {
|
||||
assertThatIllegalStateException()
|
||||
.isThrownBy(() -> this.parser.parse(MockBeanMissingClassToMock.class))
|
||||
assertThatIllegalStateException().isThrownBy(() -> this.parser.parse(MockBeanMissingClassToMock.class))
|
||||
.withMessageContaining("Unable to deduce type to mock");
|
||||
}
|
||||
|
||||
@@ -109,37 +101,29 @@ public class DefinitionsParserTests {
|
||||
public void parseMockBeanMultipleClasses() {
|
||||
this.parser.parse(MockBeanMultipleClasses.class);
|
||||
assertThat(getDefinitions()).hasSize(2);
|
||||
assertThat(getMockDefinition(0).getTypeToMock().resolve())
|
||||
.isEqualTo(ExampleService.class);
|
||||
assertThat(getMockDefinition(1).getTypeToMock().resolve())
|
||||
.isEqualTo(ExampleServiceCaller.class);
|
||||
assertThat(getMockDefinition(0).getTypeToMock().resolve()).isEqualTo(ExampleService.class);
|
||||
assertThat(getMockDefinition(1).getTypeToMock().resolve()).isEqualTo(ExampleServiceCaller.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void parseMockBeanMultipleClassesWithName() {
|
||||
assertThatIllegalStateException()
|
||||
.isThrownBy(
|
||||
() -> this.parser.parse(MockBeanMultipleClassesWithName.class))
|
||||
.withMessageContaining(
|
||||
"The name attribute can only be used when mocking a single class");
|
||||
assertThatIllegalStateException().isThrownBy(() -> this.parser.parse(MockBeanMultipleClassesWithName.class))
|
||||
.withMessageContaining("The name attribute can only be used when mocking a single class");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void parseSingleSpyBean() {
|
||||
this.parser.parse(SingleSpyBean.class);
|
||||
assertThat(getDefinitions()).hasSize(1);
|
||||
assertThat(getSpyDefinition(0).getTypeToSpy().resolve())
|
||||
.isEqualTo(RealExampleService.class);
|
||||
assertThat(getSpyDefinition(0).getTypeToSpy().resolve()).isEqualTo(RealExampleService.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void parseRepeatSpyBean() {
|
||||
this.parser.parse(RepeatSpyBean.class);
|
||||
assertThat(getDefinitions()).hasSize(2);
|
||||
assertThat(getSpyDefinition(0).getTypeToSpy().resolve())
|
||||
.isEqualTo(RealExampleService.class);
|
||||
assertThat(getSpyDefinition(1).getTypeToSpy().resolve())
|
||||
.isEqualTo(ExampleServiceCaller.class);
|
||||
assertThat(getSpyDefinition(0).getTypeToSpy().resolve()).isEqualTo(RealExampleService.class);
|
||||
assertThat(getSpyDefinition(1).getTypeToSpy().resolve()).isEqualTo(ExampleServiceCaller.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -148,8 +132,7 @@ public class DefinitionsParserTests {
|
||||
assertThat(getDefinitions()).hasSize(1);
|
||||
SpyDefinition definition = getSpyDefinition(0);
|
||||
assertThat(definition.getName()).isEqualTo("Name");
|
||||
assertThat(definition.getTypeToSpy().resolve())
|
||||
.isEqualTo(RealExampleService.class);
|
||||
assertThat(definition.getTypeToSpy().resolve()).isEqualTo(RealExampleService.class);
|
||||
assertThat(definition.getReset()).isEqualTo(MockReset.NONE);
|
||||
assertThat(definition.getQualifier()).isNull();
|
||||
}
|
||||
@@ -160,28 +143,24 @@ public class DefinitionsParserTests {
|
||||
assertThat(getDefinitions()).hasSize(2);
|
||||
SpyDefinition classDefinition = getSpyDefinition(0);
|
||||
assertThat(classDefinition.getQualifier()).isNull();
|
||||
assertThat(classDefinition.getTypeToSpy().resolve())
|
||||
.isEqualTo(RealExampleService.class);
|
||||
assertThat(classDefinition.getTypeToSpy().resolve()).isEqualTo(RealExampleService.class);
|
||||
SpyDefinition fieldDefinition = getSpyDefinition(1);
|
||||
QualifierDefinition qualifier = QualifierDefinition.forElement(
|
||||
ReflectionUtils.findField(SpyBeanOnClassAndField.class, "caller"));
|
||||
QualifierDefinition qualifier = QualifierDefinition
|
||||
.forElement(ReflectionUtils.findField(SpyBeanOnClassAndField.class, "caller"));
|
||||
assertThat(fieldDefinition.getQualifier()).isNotNull().isEqualTo(qualifier);
|
||||
assertThat(fieldDefinition.getTypeToSpy().resolve())
|
||||
.isEqualTo(ExampleServiceCaller.class);
|
||||
assertThat(fieldDefinition.getTypeToSpy().resolve()).isEqualTo(ExampleServiceCaller.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void parseSpyBeanInferClassToMock() {
|
||||
this.parser.parse(SpyBeanInferClassToMock.class);
|
||||
assertThat(getDefinitions()).hasSize(1);
|
||||
assertThat(getSpyDefinition(0).getTypeToSpy().resolve())
|
||||
.isEqualTo(RealExampleService.class);
|
||||
assertThat(getSpyDefinition(0).getTypeToSpy().resolve()).isEqualTo(RealExampleService.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void parseSpyBeanMissingClassToMock() {
|
||||
assertThatIllegalStateException()
|
||||
.isThrownBy(() -> this.parser.parse(SpyBeanMissingClassToMock.class))
|
||||
assertThatIllegalStateException().isThrownBy(() -> this.parser.parse(SpyBeanMissingClassToMock.class))
|
||||
.withMessageContaining("Unable to deduce type to spy");
|
||||
}
|
||||
|
||||
@@ -189,18 +168,14 @@ public class DefinitionsParserTests {
|
||||
public void parseSpyBeanMultipleClasses() {
|
||||
this.parser.parse(SpyBeanMultipleClasses.class);
|
||||
assertThat(getDefinitions()).hasSize(2);
|
||||
assertThat(getSpyDefinition(0).getTypeToSpy().resolve())
|
||||
.isEqualTo(RealExampleService.class);
|
||||
assertThat(getSpyDefinition(1).getTypeToSpy().resolve())
|
||||
.isEqualTo(ExampleServiceCaller.class);
|
||||
assertThat(getSpyDefinition(0).getTypeToSpy().resolve()).isEqualTo(RealExampleService.class);
|
||||
assertThat(getSpyDefinition(1).getTypeToSpy().resolve()).isEqualTo(ExampleServiceCaller.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void parseSpyBeanMultipleClassesWithName() {
|
||||
assertThatIllegalStateException()
|
||||
.isThrownBy(() -> this.parser.parse(SpyBeanMultipleClassesWithName.class))
|
||||
.withMessageContaining(
|
||||
"The name attribute can only be used when spying a single class");
|
||||
assertThatIllegalStateException().isThrownBy(() -> this.parser.parse(SpyBeanMultipleClassesWithName.class))
|
||||
.withMessageContaining("The name attribute can only be used when spying a single class");
|
||||
}
|
||||
|
||||
private MockDefinition getMockDefinition(int index) {
|
||||
@@ -225,10 +200,8 @@ public class DefinitionsParserTests {
|
||||
|
||||
}
|
||||
|
||||
@MockBean(name = "Name", classes = ExampleService.class,
|
||||
extraInterfaces = ExampleExtraInterface.class,
|
||||
answer = Answers.RETURNS_SMART_NULLS, serializable = true,
|
||||
reset = MockReset.NONE)
|
||||
@MockBean(name = "Name", classes = ExampleService.class, extraInterfaces = ExampleExtraInterface.class,
|
||||
answer = Answers.RETURNS_SMART_NULLS, serializable = true, reset = MockReset.NONE)
|
||||
static class MockBeanAttributes {
|
||||
|
||||
}
|
||||
@@ -247,8 +220,7 @@ public class DefinitionsParserTests {
|
||||
|
||||
}
|
||||
|
||||
@MockBean(name = "name",
|
||||
classes = { ExampleService.class, ExampleServiceCaller.class })
|
||||
@MockBean(name = "name", classes = { ExampleService.class, ExampleServiceCaller.class })
|
||||
static class MockBeanMultipleClassesWithName {
|
||||
|
||||
}
|
||||
@@ -270,8 +242,7 @@ public class DefinitionsParserTests {
|
||||
|
||||
}
|
||||
|
||||
@SpyBeans({ @SpyBean(RealExampleService.class),
|
||||
@SpyBean(ExampleServiceCaller.class) })
|
||||
@SpyBeans({ @SpyBean(RealExampleService.class), @SpyBean(ExampleServiceCaller.class) })
|
||||
static class RepeatSpyBean {
|
||||
|
||||
}
|
||||
@@ -295,8 +266,7 @@ public class DefinitionsParserTests {
|
||||
|
||||
}
|
||||
|
||||
@SpyBean(name = "name",
|
||||
classes = { RealExampleService.class, ExampleServiceCaller.class })
|
||||
@SpyBean(name = "name", classes = { RealExampleService.class, ExampleServiceCaller.class })
|
||||
static class SpyBeanMultipleClassesWithName {
|
||||
|
||||
}
|
||||
|
||||
@@ -53,8 +53,7 @@ public class MockBeanOnContextHierarchyIntegrationTests {
|
||||
ApplicationContext context = this.childConfig.getContext();
|
||||
ApplicationContext parentContext = context.getParent();
|
||||
assertThat(parentContext.getBeanNamesForType(ExampleService.class)).hasSize(1);
|
||||
assertThat(parentContext.getBeanNamesForType(ExampleServiceCaller.class))
|
||||
.hasSize(0);
|
||||
assertThat(parentContext.getBeanNamesForType(ExampleServiceCaller.class)).hasSize(0);
|
||||
assertThat(context.getBeanNamesForType(ExampleService.class)).hasSize(0);
|
||||
assertThat(context.getBeanNamesForType(ExampleServiceCaller.class)).hasSize(1);
|
||||
assertThat(context.getBean(ExampleService.class)).isNotNull();
|
||||
@@ -74,8 +73,7 @@ public class MockBeanOnContextHierarchyIntegrationTests {
|
||||
private ApplicationContext context;
|
||||
|
||||
@Override
|
||||
public void setApplicationContext(ApplicationContext applicationContext)
|
||||
throws BeansException {
|
||||
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
|
||||
this.context = applicationContext;
|
||||
}
|
||||
|
||||
|
||||
@@ -62,8 +62,7 @@ public class MockBeanOnTestFieldForExistingBeanWithQualifierIntegrationTests {
|
||||
@Test
|
||||
public void onlyQualifiedBeanIsReplaced() {
|
||||
assertThat(this.applicationContext.getBean("service")).isSameAs(this.service);
|
||||
ExampleService anotherService = this.applicationContext.getBean("anotherService",
|
||||
ExampleService.class);
|
||||
ExampleService anotherService = this.applicationContext.getBean("anotherService", ExampleService.class);
|
||||
assertThat(anotherService.greeting()).isEqualTo("Another");
|
||||
}
|
||||
|
||||
|
||||
@@ -36,20 +36,18 @@ import static org.mockito.Mockito.mock;
|
||||
*/
|
||||
public class MockDefinitionTests {
|
||||
|
||||
private static final ResolvableType EXAMPLE_SERVICE_TYPE = ResolvableType
|
||||
.forClass(ExampleService.class);
|
||||
private static final ResolvableType EXAMPLE_SERVICE_TYPE = ResolvableType.forClass(ExampleService.class);
|
||||
|
||||
@Test
|
||||
public void classToMockMustNotBeNull() {
|
||||
assertThatIllegalArgumentException().isThrownBy(
|
||||
() -> new MockDefinition(null, null, null, null, false, null, null))
|
||||
assertThatIllegalArgumentException()
|
||||
.isThrownBy(() -> new MockDefinition(null, null, null, null, false, null, null))
|
||||
.withMessageContaining("TypeToMock must not be null");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void createWithDefaults() {
|
||||
MockDefinition definition = new MockDefinition(null, EXAMPLE_SERVICE_TYPE, null,
|
||||
null, false, null, null);
|
||||
MockDefinition definition = new MockDefinition(null, EXAMPLE_SERVICE_TYPE, null, null, false, null, null);
|
||||
assertThat(definition.getName()).isNull();
|
||||
assertThat(definition.getTypeToMock()).isEqualTo(EXAMPLE_SERVICE_TYPE);
|
||||
assertThat(definition.getExtraInterfaces()).isEmpty();
|
||||
@@ -63,12 +61,11 @@ public class MockDefinitionTests {
|
||||
public void createExplicit() {
|
||||
QualifierDefinition qualifier = mock(QualifierDefinition.class);
|
||||
MockDefinition definition = new MockDefinition("name", EXAMPLE_SERVICE_TYPE,
|
||||
new Class<?>[] { ExampleExtraInterface.class },
|
||||
Answers.RETURNS_SMART_NULLS, true, MockReset.BEFORE, qualifier);
|
||||
new Class<?>[] { ExampleExtraInterface.class }, Answers.RETURNS_SMART_NULLS, true, MockReset.BEFORE,
|
||||
qualifier);
|
||||
assertThat(definition.getName()).isEqualTo("name");
|
||||
assertThat(definition.getTypeToMock()).isEqualTo(EXAMPLE_SERVICE_TYPE);
|
||||
assertThat(definition.getExtraInterfaces())
|
||||
.containsExactly(ExampleExtraInterface.class);
|
||||
assertThat(definition.getExtraInterfaces()).containsExactly(ExampleExtraInterface.class);
|
||||
assertThat(definition.getAnswer()).isEqualTo(Answers.RETURNS_SMART_NULLS);
|
||||
assertThat(definition.isSerializable()).isTrue();
|
||||
assertThat(definition.getReset()).isEqualTo(MockReset.BEFORE);
|
||||
@@ -79,11 +76,10 @@ public class MockDefinitionTests {
|
||||
@Test
|
||||
public void createMock() {
|
||||
MockDefinition definition = new MockDefinition("name", EXAMPLE_SERVICE_TYPE,
|
||||
new Class<?>[] { ExampleExtraInterface.class },
|
||||
Answers.RETURNS_SMART_NULLS, true, MockReset.BEFORE, null);
|
||||
new Class<?>[] { ExampleExtraInterface.class }, Answers.RETURNS_SMART_NULLS, true, MockReset.BEFORE,
|
||||
null);
|
||||
ExampleService mock = definition.createMock();
|
||||
MockCreationSettings<?> settings = Mockito.mockingDetails(mock)
|
||||
.getMockCreationSettings();
|
||||
MockCreationSettings<?> settings = Mockito.mockingDetails(mock).getMockCreationSettings();
|
||||
assertThat(mock).isInstanceOf(ExampleService.class);
|
||||
assertThat(mock).isInstanceOf(ExampleExtraInterface.class);
|
||||
assertThat(settings.getMockName().toString()).isEqualTo("name");
|
||||
|
||||
@@ -39,8 +39,7 @@ public class MockResetTests {
|
||||
|
||||
@Test
|
||||
public void withSettingsOfNoneAttachesReset() {
|
||||
ExampleService mock = mock(ExampleService.class,
|
||||
MockReset.withSettings(MockReset.NONE));
|
||||
ExampleService mock = mock(ExampleService.class, MockReset.withSettings(MockReset.NONE));
|
||||
assertThat(MockReset.get(mock)).isEqualTo(MockReset.NONE);
|
||||
}
|
||||
|
||||
@@ -58,15 +57,13 @@ public class MockResetTests {
|
||||
|
||||
@Test
|
||||
public void withSettingsAttachesReset() {
|
||||
ExampleService mock = mock(ExampleService.class,
|
||||
MockReset.withSettings(MockReset.BEFORE));
|
||||
ExampleService mock = mock(ExampleService.class, MockReset.withSettings(MockReset.BEFORE));
|
||||
assertThat(MockReset.get(mock)).isEqualTo(MockReset.BEFORE);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void apply() {
|
||||
ExampleService mock = mock(ExampleService.class,
|
||||
MockReset.apply(MockReset.AFTER, withSettings()));
|
||||
ExampleService mock = mock(ExampleService.class, MockReset.apply(MockReset.AFTER, withSettings()));
|
||||
assertThat(MockReset.get(mock)).isEqualTo(MockReset.AFTER);
|
||||
}
|
||||
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user