Merge branch '2.0.x' into 2.1.x
Closes gh-17078
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;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2012-2018 the original author or authors.
|
||||
* Copyright 2012-2019 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -76,24 +76,20 @@ class ImportsContextCustomizer implements ContextCustomizer {
|
||||
public void customizeContext(ConfigurableApplicationContext context,
|
||||
MergedContextConfiguration mergedContextConfiguration) {
|
||||
BeanDefinitionRegistry registry = getBeanDefinitionRegistry(context);
|
||||
AnnotatedBeanDefinitionReader reader = new AnnotatedBeanDefinitionReader(
|
||||
registry);
|
||||
AnnotatedBeanDefinitionReader reader = new AnnotatedBeanDefinitionReader(registry);
|
||||
registerCleanupPostProcessor(registry, reader);
|
||||
registerImportsConfiguration(registry, reader);
|
||||
}
|
||||
|
||||
private void registerCleanupPostProcessor(BeanDefinitionRegistry registry,
|
||||
AnnotatedBeanDefinitionReader reader) {
|
||||
BeanDefinition definition = registerBean(registry, reader,
|
||||
ImportsCleanupPostProcessor.BEAN_NAME, ImportsCleanupPostProcessor.class);
|
||||
definition.getConstructorArgumentValues().addIndexedArgumentValue(0,
|
||||
this.testClass);
|
||||
private void registerCleanupPostProcessor(BeanDefinitionRegistry registry, AnnotatedBeanDefinitionReader reader) {
|
||||
BeanDefinition definition = registerBean(registry, reader, ImportsCleanupPostProcessor.BEAN_NAME,
|
||||
ImportsCleanupPostProcessor.class);
|
||||
definition.getConstructorArgumentValues().addIndexedArgumentValue(0, this.testClass);
|
||||
}
|
||||
|
||||
private void registerImportsConfiguration(BeanDefinitionRegistry registry,
|
||||
AnnotatedBeanDefinitionReader reader) {
|
||||
BeanDefinition definition = registerBean(registry, reader,
|
||||
ImportsConfiguration.BEAN_NAME, ImportsConfiguration.class);
|
||||
private void registerImportsConfiguration(BeanDefinitionRegistry registry, AnnotatedBeanDefinitionReader reader) {
|
||||
BeanDefinition definition = registerBean(registry, reader, ImportsConfiguration.BEAN_NAME,
|
||||
ImportsConfiguration.class);
|
||||
definition.setAttribute(TEST_CLASS_ATTRIBUTE, this.testClass);
|
||||
}
|
||||
|
||||
@@ -102,15 +98,14 @@ class ImportsContextCustomizer implements ContextCustomizer {
|
||||
return (BeanDefinitionRegistry) context;
|
||||
}
|
||||
if (context instanceof AbstractApplicationContext) {
|
||||
return (BeanDefinitionRegistry) ((AbstractApplicationContext) context)
|
||||
.getBeanFactory();
|
||||
return (BeanDefinitionRegistry) ((AbstractApplicationContext) context).getBeanFactory();
|
||||
}
|
||||
throw new IllegalStateException("Could not locate BeanDefinitionRegistry");
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
private BeanDefinition registerBean(BeanDefinitionRegistry registry,
|
||||
AnnotatedBeanDefinitionReader reader, String beanName, Class<?> type) {
|
||||
private BeanDefinition registerBean(BeanDefinitionRegistry registry, AnnotatedBeanDefinitionReader reader,
|
||||
String beanName, Class<?> type) {
|
||||
reader.registerBean(type, beanName);
|
||||
return registry.getBeanDefinition(beanName);
|
||||
}
|
||||
@@ -166,12 +161,9 @@ class ImportsContextCustomizer implements ContextCustomizer {
|
||||
|
||||
@Override
|
||||
public String[] selectImports(AnnotationMetadata importingClassMetadata) {
|
||||
BeanDefinition definition = this.beanFactory
|
||||
.getBeanDefinition(ImportsConfiguration.BEAN_NAME);
|
||||
Object testClass = (definition != null)
|
||||
? definition.getAttribute(TEST_CLASS_ATTRIBUTE) : null;
|
||||
return (testClass != null) ? new String[] { ((Class<?>) testClass).getName() }
|
||||
: NO_IMPORTS;
|
||||
BeanDefinition definition = this.beanFactory.getBeanDefinition(ImportsConfiguration.BEAN_NAME);
|
||||
Object testClass = (definition != null) ? definition.getAttribute(TEST_CLASS_ATTRIBUTE) : null;
|
||||
return (testClass != null) ? new String[] { ((Class<?>) testClass).getName() } : NO_IMPORTS;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -181,8 +173,7 @@ class ImportsContextCustomizer implements ContextCustomizer {
|
||||
* added to load imports.
|
||||
*/
|
||||
@Order(Ordered.LOWEST_PRECEDENCE)
|
||||
static class ImportsCleanupPostProcessor
|
||||
implements BeanDefinitionRegistryPostProcessor {
|
||||
static class ImportsCleanupPostProcessor implements BeanDefinitionRegistryPostProcessor {
|
||||
|
||||
static final String BEAN_NAME = ImportsCleanupPostProcessor.class.getName();
|
||||
|
||||
@@ -193,13 +184,11 @@ class ImportsContextCustomizer implements ContextCustomizer {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory)
|
||||
throws BeansException {
|
||||
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry)
|
||||
throws BeansException {
|
||||
public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {
|
||||
try {
|
||||
String[] names = registry.getBeanDefinitionNames();
|
||||
for (String name : names) {
|
||||
@@ -244,12 +233,10 @@ class ImportsContextCustomizer implements ContextCustomizer {
|
||||
Set<Class<?>> seen = new HashSet<>();
|
||||
collectClassAnnotations(testClass, annotations, seen);
|
||||
Set<Object> determinedImports = determineImports(annotations, testClass);
|
||||
this.key = Collections.unmodifiableSet(
|
||||
(determinedImports != null) ? determinedImports : annotations);
|
||||
this.key = Collections.unmodifiableSet((determinedImports != null) ? determinedImports : annotations);
|
||||
}
|
||||
|
||||
private void collectClassAnnotations(Class<?> classType,
|
||||
Set<Annotation> annotations, Set<Class<?>> seen) {
|
||||
private void collectClassAnnotations(Class<?> classType, Set<Annotation> annotations, Set<Class<?>> seen) {
|
||||
if (seen.add(classType)) {
|
||||
collectElementAnnotations(classType, annotations, seen);
|
||||
for (Class<?> interfaceType : classType.getInterfaces()) {
|
||||
@@ -261,13 +248,12 @@ class ImportsContextCustomizer implements ContextCustomizer {
|
||||
}
|
||||
}
|
||||
|
||||
private void collectElementAnnotations(AnnotatedElement element,
|
||||
Set<Annotation> annotations, Set<Class<?>> seen) {
|
||||
private void collectElementAnnotations(AnnotatedElement element, Set<Annotation> annotations,
|
||||
Set<Class<?>> seen) {
|
||||
for (Annotation annotation : element.getDeclaredAnnotations()) {
|
||||
if (!isIgnoredAnnotation(annotation)) {
|
||||
annotations.add(annotation);
|
||||
collectClassAnnotations(annotation.annotationType(), annotations,
|
||||
seen);
|
||||
collectClassAnnotations(annotation.annotationType(), annotations, seen);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -281,15 +267,12 @@ class ImportsContextCustomizer implements ContextCustomizer {
|
||||
return false;
|
||||
}
|
||||
|
||||
private Set<Object> determineImports(Set<Annotation> annotations,
|
||||
Class<?> testClass) {
|
||||
private Set<Object> determineImports(Set<Annotation> annotations, Class<?> testClass) {
|
||||
Set<Object> determinedImports = new LinkedHashSet<>();
|
||||
AnnotationMetadata testClassMetadata = new StandardAnnotationMetadata(
|
||||
testClass);
|
||||
AnnotationMetadata testClassMetadata = new StandardAnnotationMetadata(testClass);
|
||||
for (Annotation annotation : annotations) {
|
||||
for (Class<?> source : getImports(annotation)) {
|
||||
Set<Object> determinedSourceImports = determineImports(source,
|
||||
testClassMetadata);
|
||||
Set<Object> determinedSourceImports = determineImports(source, testClassMetadata);
|
||||
if (determinedSourceImports == null) {
|
||||
return null;
|
||||
}
|
||||
@@ -306,12 +289,10 @@ class ImportsContextCustomizer implements ContextCustomizer {
|
||||
return NO_IMPORTS;
|
||||
}
|
||||
|
||||
private Set<Object> determineImports(Class<?> source,
|
||||
AnnotationMetadata metadata) {
|
||||
private Set<Object> determineImports(Class<?> source, AnnotationMetadata metadata) {
|
||||
if (DeterminableImports.class.isAssignableFrom(source)) {
|
||||
// We can determine the imports
|
||||
return ((DeterminableImports) instantiate(source))
|
||||
.determineImports(metadata);
|
||||
return ((DeterminableImports) instantiate(source)).determineImports(metadata);
|
||||
}
|
||||
if (ImportSelector.class.isAssignableFrom(source)
|
||||
|| ImportBeanDefinitionRegistrar.class.isAssignableFrom(source)) {
|
||||
@@ -331,17 +312,14 @@ class ImportsContextCustomizer implements ContextCustomizer {
|
||||
return (T) constructor.newInstance();
|
||||
}
|
||||
catch (Throwable ex) {
|
||||
throw new IllegalStateException(
|
||||
"Unable to instantiate DeterminableImportSelector "
|
||||
+ source.getName(),
|
||||
throw new IllegalStateException("Unable to instantiate DeterminableImportSelector " + source.getName(),
|
||||
ex);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object obj) {
|
||||
return (obj != null && getClass() == obj.getClass()
|
||||
&& this.key.equals(((ContextCustomizerKey) obj).key));
|
||||
return (obj != null && getClass() == obj.getClass() && this.key.equals(((ContextCustomizerKey) obj).key));
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2012-2018 the original author or authors.
|
||||
* Copyright 2012-2019 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -78,18 +78,13 @@ import org.springframework.web.context.support.GenericWebApplicationContext;
|
||||
public class SpringBootContextLoader extends AbstractContextLoader {
|
||||
|
||||
@Override
|
||||
public ApplicationContext loadContext(MergedContextConfiguration config)
|
||||
throws Exception {
|
||||
public ApplicationContext loadContext(MergedContextConfiguration config) throws Exception {
|
||||
Class<?>[] configClasses = config.getClasses();
|
||||
String[] configLocations = config.getLocations();
|
||||
Assert.state(
|
||||
!ObjectUtils.isEmpty(configClasses)
|
||||
|| !ObjectUtils.isEmpty(configLocations),
|
||||
() -> "No configuration classes "
|
||||
+ "or locations found in @SpringApplicationConfiguration. "
|
||||
+ "For default configuration detection to work you need "
|
||||
+ "Spring 4.0.3 or better (found " + SpringVersion.getVersion()
|
||||
+ ").");
|
||||
Assert.state(!ObjectUtils.isEmpty(configClasses) || !ObjectUtils.isEmpty(configLocations),
|
||||
() -> "No configuration classes " + "or locations found in @SpringApplicationConfiguration. "
|
||||
+ "For default configuration detection to work you need " + "Spring 4.0.3 or better (found "
|
||||
+ SpringVersion.getVersion() + ").");
|
||||
SpringApplication application = getSpringApplication();
|
||||
application.setMainApplicationClass(config.getTestClass());
|
||||
application.addPrimarySources(Arrays.asList(configClasses));
|
||||
@@ -98,16 +93,13 @@ public class SpringBootContextLoader extends AbstractContextLoader {
|
||||
if (!ObjectUtils.isEmpty(config.getActiveProfiles())) {
|
||||
setActiveProfiles(environment, config.getActiveProfiles());
|
||||
}
|
||||
ResourceLoader resourceLoader = (application.getResourceLoader() != null)
|
||||
? application.getResourceLoader()
|
||||
ResourceLoader resourceLoader = (application.getResourceLoader() != null) ? application.getResourceLoader()
|
||||
: new DefaultResourceLoader(getClass().getClassLoader());
|
||||
TestPropertySourceUtils.addPropertiesFilesToEnvironment(environment,
|
||||
resourceLoader, config.getPropertySourceLocations());
|
||||
TestPropertySourceUtils.addInlinedPropertiesToEnvironment(environment,
|
||||
getInlinedProperties(config));
|
||||
TestPropertySourceUtils.addPropertiesFilesToEnvironment(environment, resourceLoader,
|
||||
config.getPropertySourceLocations());
|
||||
TestPropertySourceUtils.addInlinedPropertiesToEnvironment(environment, getInlinedProperties(config));
|
||||
application.setEnvironment(environment);
|
||||
List<ApplicationContextInitializer<?>> initializers = getInitializers(config,
|
||||
application);
|
||||
List<ApplicationContextInitializer<?>> initializers = getInitializers(config, application);
|
||||
if (config instanceof WebMergedContextConfiguration) {
|
||||
application.setWebApplicationType(WebApplicationType.SERVLET);
|
||||
if (!isEmbeddedWebEnvironment(config)) {
|
||||
@@ -145,11 +137,8 @@ public class SpringBootContextLoader extends AbstractContextLoader {
|
||||
return new StandardEnvironment();
|
||||
}
|
||||
|
||||
private void setActiveProfiles(ConfigurableEnvironment environment,
|
||||
String[] profiles) {
|
||||
TestPropertyValues
|
||||
.of("spring.profiles.active="
|
||||
+ StringUtils.arrayToCommaDelimitedString(profiles))
|
||||
private void setActiveProfiles(ConfigurableEnvironment environment, String[] profiles) {
|
||||
TestPropertyValues.of("spring.profiles.active=" + StringUtils.arrayToCommaDelimitedString(profiles))
|
||||
.applyTo(environment);
|
||||
}
|
||||
|
||||
@@ -173,10 +162,9 @@ public class SpringBootContextLoader extends AbstractContextLoader {
|
||||
return binder.bind("server.port", Bindable.of(String.class)).isBound();
|
||||
}
|
||||
|
||||
private ConfigurationPropertySource convertToConfigurationPropertySource(
|
||||
List<String> properties) {
|
||||
return new MapConfigurationPropertySource(TestPropertySourceUtils
|
||||
.convertInlinedPropertiesToMap(StringUtils.toStringArray(properties)));
|
||||
private ConfigurationPropertySource convertToConfigurationPropertySource(List<String> properties) {
|
||||
return new MapConfigurationPropertySource(
|
||||
TestPropertySourceUtils.convertInlinedPropertiesToMap(StringUtils.toStringArray(properties)));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -191,8 +179,8 @@ public class SpringBootContextLoader extends AbstractContextLoader {
|
||||
* @return the initializers to apply
|
||||
* @since 2.0.0
|
||||
*/
|
||||
protected List<ApplicationContextInitializer<?>> getInitializers(
|
||||
MergedContextConfiguration config, SpringApplication application) {
|
||||
protected List<ApplicationContextInitializer<?>> getInitializers(MergedContextConfiguration config,
|
||||
SpringApplication application) {
|
||||
List<ApplicationContextInitializer<?>> initializers = new ArrayList<>();
|
||||
for (ContextCustomizer contextCustomizer : config.getContextCustomizers()) {
|
||||
initializers.add(new ContextCustomizerAdapter(contextCustomizer, config));
|
||||
@@ -203,15 +191,14 @@ public class SpringBootContextLoader extends AbstractContextLoader {
|
||||
initializers.add(BeanUtils.instantiateClass(initializerClass));
|
||||
}
|
||||
if (config.getParent() != null) {
|
||||
initializers.add(new ParentContextApplicationContextInitializer(
|
||||
config.getParentApplicationContext()));
|
||||
initializers.add(new ParentContextApplicationContextInitializer(config.getParentApplicationContext()));
|
||||
}
|
||||
return initializers;
|
||||
}
|
||||
|
||||
private boolean isEmbeddedWebEnvironment(MergedContextConfiguration config) {
|
||||
SpringBootTest annotation = AnnotatedElementUtils
|
||||
.findMergedAnnotation(config.getTestClass(), SpringBootTest.class);
|
||||
SpringBootTest annotation = AnnotatedElementUtils.findMergedAnnotation(config.getTestClass(),
|
||||
SpringBootTest.class);
|
||||
if (annotation != null && annotation.webEnvironment().isEmbedded()) {
|
||||
return true;
|
||||
}
|
||||
@@ -219,12 +206,10 @@ public class SpringBootContextLoader extends AbstractContextLoader {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void processContextConfiguration(
|
||||
ContextConfigurationAttributes configAttributes) {
|
||||
public void processContextConfiguration(ContextConfigurationAttributes configAttributes) {
|
||||
super.processContextConfiguration(configAttributes);
|
||||
if (!configAttributes.hasResources()) {
|
||||
Class<?>[] defaultConfigClasses = detectDefaultConfigurationClasses(
|
||||
configAttributes.getDeclaringClass());
|
||||
Class<?>[] defaultConfigClasses = detectDefaultConfigurationClasses(configAttributes.getDeclaringClass());
|
||||
configAttributes.setClasses(defaultConfigClasses);
|
||||
}
|
||||
}
|
||||
@@ -239,14 +224,13 @@ public class SpringBootContextLoader extends AbstractContextLoader {
|
||||
* @see AnnotationConfigContextLoaderUtils
|
||||
*/
|
||||
protected Class<?>[] detectDefaultConfigurationClasses(Class<?> declaringClass) {
|
||||
return AnnotationConfigContextLoaderUtils
|
||||
.detectDefaultConfigurationClasses(declaringClass);
|
||||
return AnnotationConfigContextLoaderUtils.detectDefaultConfigurationClasses(declaringClass);
|
||||
}
|
||||
|
||||
@Override
|
||||
public ApplicationContext loadContext(String... locations) throws Exception {
|
||||
throw new UnsupportedOperationException("SpringApplicationContextLoader "
|
||||
+ "does not support the loadContext(String...) method");
|
||||
throw new UnsupportedOperationException(
|
||||
"SpringApplicationContextLoader " + "does not support the loadContext(String...) method");
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -266,21 +250,18 @@ public class SpringBootContextLoader extends AbstractContextLoader {
|
||||
|
||||
private static final Class<GenericWebApplicationContext> WEB_CONTEXT_CLASS = GenericWebApplicationContext.class;
|
||||
|
||||
void configure(MergedContextConfiguration configuration,
|
||||
SpringApplication application,
|
||||
void configure(MergedContextConfiguration configuration, SpringApplication application,
|
||||
List<ApplicationContextInitializer<?>> initializers) {
|
||||
WebMergedContextConfiguration webConfiguration = (WebMergedContextConfiguration) configuration;
|
||||
addMockServletContext(initializers, webConfiguration);
|
||||
application.setApplicationContextClass(WEB_CONTEXT_CLASS);
|
||||
}
|
||||
|
||||
private void addMockServletContext(
|
||||
List<ApplicationContextInitializer<?>> initializers,
|
||||
private void addMockServletContext(List<ApplicationContextInitializer<?>> initializers,
|
||||
WebMergedContextConfiguration webConfiguration) {
|
||||
SpringBootMockServletContext servletContext = new SpringBootMockServletContext(
|
||||
webConfiguration.getResourceBasePath());
|
||||
initializers.add(0, new ServletContextApplicationContextInitializer(
|
||||
servletContext, true));
|
||||
initializers.add(0, new ServletContextApplicationContextInitializer(servletContext, true));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -309,8 +290,7 @@ public class SpringBootContextLoader extends AbstractContextLoader {
|
||||
|
||||
private final MergedContextConfiguration config;
|
||||
|
||||
ContextCustomizerAdapter(ContextCustomizer contextCustomizer,
|
||||
MergedContextConfiguration config) {
|
||||
ContextCustomizerAdapter(ContextCustomizer contextCustomizer, MergedContextConfiguration config) {
|
||||
this.contextCustomizer = contextCustomizer;
|
||||
this.config = config;
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2012-2018 the original author or authors.
|
||||
* Copyright 2012-2019 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -83,24 +83,21 @@ public class SpringBootTestContextBootstrapper extends DefaultTestContextBootstr
|
||||
private static final String REACTIVE_WEB_ENVIRONMENT_CLASS = "org.springframework."
|
||||
+ "web.reactive.DispatcherHandler";
|
||||
|
||||
private static final String MVC_WEB_ENVIRONMENT_CLASS = "org.springframework."
|
||||
+ "web.servlet.DispatcherServlet";
|
||||
private static final String MVC_WEB_ENVIRONMENT_CLASS = "org.springframework." + "web.servlet.DispatcherServlet";
|
||||
|
||||
private static final String JERSEY_WEB_ENVIRONMENT_CLASS = "org.glassfish.jersey.server.ResourceConfig";
|
||||
|
||||
private static final String ACTIVATE_SERVLET_LISTENER = "org.springframework.test."
|
||||
+ "context.web.ServletTestExecutionListener.activateListener";
|
||||
|
||||
private static final Log logger = LogFactory
|
||||
.getLog(SpringBootTestContextBootstrapper.class);
|
||||
private static final Log logger = LogFactory.getLog(SpringBootTestContextBootstrapper.class);
|
||||
|
||||
@Override
|
||||
public TestContext buildTestContext() {
|
||||
TestContext context = super.buildTestContext();
|
||||
verifyConfiguration(context.getTestClass());
|
||||
WebEnvironment webEnvironment = getWebEnvironment(context.getTestClass());
|
||||
if (webEnvironment == WebEnvironment.MOCK
|
||||
&& deduceWebApplicationType() == WebApplicationType.SERVLET) {
|
||||
if (webEnvironment == WebEnvironment.MOCK && deduceWebApplicationType() == WebApplicationType.SERVLET) {
|
||||
context.setAttribute(ACTIVATE_SERVLET_LISTENER, true);
|
||||
}
|
||||
else if (webEnvironment != null && webEnvironment.isEmbedded()) {
|
||||
@@ -113,8 +110,7 @@ public class SpringBootTestContextBootstrapper extends DefaultTestContextBootstr
|
||||
protected Set<Class<? extends TestExecutionListener>> getDefaultTestExecutionListenerClasses() {
|
||||
Set<Class<? extends TestExecutionListener>> listeners = super.getDefaultTestExecutionListenerClasses();
|
||||
List<DefaultTestExecutionListenersPostProcessor> postProcessors = SpringFactoriesLoader
|
||||
.loadFactories(DefaultTestExecutionListenersPostProcessor.class,
|
||||
getClass().getClassLoader());
|
||||
.loadFactories(DefaultTestExecutionListenersPostProcessor.class, getClass().getClassLoader());
|
||||
for (DefaultTestExecutionListenersPostProcessor postProcessor : postProcessors) {
|
||||
listeners = postProcessor.postProcessDefaultTestExecutionListeners(listeners);
|
||||
}
|
||||
@@ -133,8 +129,7 @@ public class SpringBootTestContextBootstrapper extends DefaultTestContextBootstr
|
||||
return super.resolveContextLoader(testClass, configAttributesList);
|
||||
}
|
||||
|
||||
private void addConfigAttributesClasses(
|
||||
ContextConfigurationAttributes configAttributes, Class<?>[] classes) {
|
||||
private void addConfigAttributesClasses(ContextConfigurationAttributes configAttributes, Class<?>[] classes) {
|
||||
List<Class<?>> combined = new ArrayList<>();
|
||||
combined.addAll(Arrays.asList(classes));
|
||||
if (configAttributes.getClasses() != null) {
|
||||
@@ -144,51 +139,39 @@ public class SpringBootTestContextBootstrapper extends DefaultTestContextBootstr
|
||||
}
|
||||
|
||||
@Override
|
||||
protected Class<? extends ContextLoader> getDefaultContextLoaderClass(
|
||||
Class<?> testClass) {
|
||||
protected Class<? extends ContextLoader> getDefaultContextLoaderClass(Class<?> testClass) {
|
||||
return SpringBootContextLoader.class;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected MergedContextConfiguration processMergedContextConfiguration(
|
||||
MergedContextConfiguration mergedConfig) {
|
||||
protected MergedContextConfiguration processMergedContextConfiguration(MergedContextConfiguration mergedConfig) {
|
||||
Class<?>[] classes = getOrFindConfigurationClasses(mergedConfig);
|
||||
List<String> propertySourceProperties = getAndProcessPropertySourceProperties(
|
||||
mergedConfig);
|
||||
mergedConfig = createModifiedConfig(mergedConfig, classes,
|
||||
StringUtils.toStringArray(propertySourceProperties));
|
||||
List<String> propertySourceProperties = getAndProcessPropertySourceProperties(mergedConfig);
|
||||
mergedConfig = createModifiedConfig(mergedConfig, classes, StringUtils.toStringArray(propertySourceProperties));
|
||||
WebEnvironment webEnvironment = getWebEnvironment(mergedConfig.getTestClass());
|
||||
if (webEnvironment != null && isWebEnvironmentSupported(mergedConfig)) {
|
||||
WebApplicationType webApplicationType = getWebApplicationType(mergedConfig);
|
||||
if (webApplicationType == WebApplicationType.SERVLET
|
||||
&& (webEnvironment.isEmbedded()
|
||||
|| webEnvironment == WebEnvironment.MOCK)) {
|
||||
&& (webEnvironment.isEmbedded() || webEnvironment == WebEnvironment.MOCK)) {
|
||||
WebAppConfiguration webAppConfiguration = AnnotatedElementUtils
|
||||
.findMergedAnnotation(mergedConfig.getTestClass(),
|
||||
WebAppConfiguration.class);
|
||||
String resourceBasePath = (webAppConfiguration != null)
|
||||
? webAppConfiguration.value() : "src/main/webapp";
|
||||
mergedConfig = new WebMergedContextConfiguration(mergedConfig,
|
||||
resourceBasePath);
|
||||
.findMergedAnnotation(mergedConfig.getTestClass(), WebAppConfiguration.class);
|
||||
String resourceBasePath = (webAppConfiguration != null) ? webAppConfiguration.value()
|
||||
: "src/main/webapp";
|
||||
mergedConfig = new WebMergedContextConfiguration(mergedConfig, resourceBasePath);
|
||||
}
|
||||
else if (webApplicationType == WebApplicationType.REACTIVE
|
||||
&& (webEnvironment.isEmbedded()
|
||||
|| webEnvironment == WebEnvironment.MOCK)) {
|
||||
&& (webEnvironment.isEmbedded() || webEnvironment == WebEnvironment.MOCK)) {
|
||||
return new ReactiveWebMergedContextConfiguration(mergedConfig);
|
||||
}
|
||||
}
|
||||
return mergedConfig;
|
||||
}
|
||||
|
||||
private WebApplicationType getWebApplicationType(
|
||||
MergedContextConfiguration configuration) {
|
||||
private WebApplicationType getWebApplicationType(MergedContextConfiguration configuration) {
|
||||
ConfigurationPropertySource source = new MapConfigurationPropertySource(
|
||||
TestPropertySourceUtils.convertInlinedPropertiesToMap(
|
||||
configuration.getPropertySourceProperties()));
|
||||
TestPropertySourceUtils.convertInlinedPropertiesToMap(configuration.getPropertySourceProperties()));
|
||||
Binder binder = new Binder(source);
|
||||
return binder
|
||||
.bind("spring.main.web-application-type",
|
||||
Bindable.of(WebApplicationType.class))
|
||||
return binder.bind("spring.main.web-application-type", Bindable.of(WebApplicationType.class))
|
||||
.orElseGet(this::deduceWebApplicationType);
|
||||
}
|
||||
|
||||
@@ -208,22 +191,19 @@ public class SpringBootTestContextBootstrapper extends DefaultTestContextBootstr
|
||||
|
||||
private boolean isWebEnvironmentSupported(MergedContextConfiguration mergedConfig) {
|
||||
Class<?> testClass = mergedConfig.getTestClass();
|
||||
ContextHierarchy hierarchy = AnnotationUtils.getAnnotation(testClass,
|
||||
ContextHierarchy.class);
|
||||
ContextHierarchy hierarchy = AnnotationUtils.getAnnotation(testClass, ContextHierarchy.class);
|
||||
if (hierarchy == null || hierarchy.value().length == 0) {
|
||||
return true;
|
||||
}
|
||||
ContextConfiguration[] configurations = hierarchy.value();
|
||||
return isFromConfiguration(mergedConfig,
|
||||
configurations[configurations.length - 1]);
|
||||
return isFromConfiguration(mergedConfig, configurations[configurations.length - 1]);
|
||||
}
|
||||
|
||||
private boolean isFromConfiguration(MergedContextConfiguration candidateConfig,
|
||||
ContextConfiguration configuration) {
|
||||
ContextConfigurationAttributes attributes = new ContextConfigurationAttributes(
|
||||
candidateConfig.getTestClass(), configuration);
|
||||
Set<Class<?>> configurationClasses = new HashSet<>(
|
||||
Arrays.asList(attributes.getClasses()));
|
||||
ContextConfigurationAttributes attributes = new ContextConfigurationAttributes(candidateConfig.getTestClass(),
|
||||
configuration);
|
||||
Set<Class<?>> configurationClasses = new HashSet<>(Arrays.asList(attributes.getClasses()));
|
||||
for (Class<?> candidate : candidateConfig.getClasses()) {
|
||||
if (configurationClasses.contains(candidate)) {
|
||||
return true;
|
||||
@@ -232,20 +212,16 @@ public class SpringBootTestContextBootstrapper extends DefaultTestContextBootstr
|
||||
return false;
|
||||
}
|
||||
|
||||
protected Class<?>[] getOrFindConfigurationClasses(
|
||||
MergedContextConfiguration mergedConfig) {
|
||||
protected Class<?>[] getOrFindConfigurationClasses(MergedContextConfiguration mergedConfig) {
|
||||
Class<?>[] classes = mergedConfig.getClasses();
|
||||
if (containsNonTestComponent(classes) || mergedConfig.hasLocations()) {
|
||||
return classes;
|
||||
}
|
||||
Class<?> found = new AnnotatedClassFinder(SpringBootConfiguration.class)
|
||||
.findFromClass(mergedConfig.getTestClass());
|
||||
Assert.state(found != null,
|
||||
"Unable to find a @SpringBootConfiguration, you need to use "
|
||||
+ "@ContextConfiguration or @SpringBootTest(classes=...) "
|
||||
+ "with your test");
|
||||
logger.info("Found @SpringBootConfiguration " + found.getName() + " for test "
|
||||
+ mergedConfig.getTestClass());
|
||||
Assert.state(found != null, "Unable to find a @SpringBootConfiguration, you need to use "
|
||||
+ "@ContextConfiguration or @SpringBootTest(classes=...) " + "with your test");
|
||||
logger.info("Found @SpringBootConfiguration " + found.getName() + " for test " + mergedConfig.getTestClass());
|
||||
return merge(found, classes);
|
||||
}
|
||||
|
||||
@@ -265,8 +241,7 @@ public class SpringBootTestContextBootstrapper extends DefaultTestContextBootstr
|
||||
return result;
|
||||
}
|
||||
|
||||
private List<String> getAndProcessPropertySourceProperties(
|
||||
MergedContextConfiguration mergedConfig) {
|
||||
private List<String> getAndProcessPropertySourceProperties(MergedContextConfiguration mergedConfig) {
|
||||
List<String> propertySourceProperties = new ArrayList<>(
|
||||
Arrays.asList(mergedConfig.getPropertySourceProperties()));
|
||||
String differentiator = getDifferentiatorPropertySourceProperty();
|
||||
@@ -294,8 +269,7 @@ public class SpringBootTestContextBootstrapper extends DefaultTestContextBootstr
|
||||
* @param mergedConfig the merged context configuration
|
||||
* @param propertySourceProperties the property source properties to process
|
||||
*/
|
||||
protected void processPropertySourceProperties(
|
||||
MergedContextConfiguration mergedConfig,
|
||||
protected void processPropertySourceProperties(MergedContextConfiguration mergedConfig,
|
||||
List<String> propertySourceProperties) {
|
||||
Class<?> testClass = mergedConfig.getTestClass();
|
||||
String[] properties = getProperties(testClass);
|
||||
@@ -341,13 +315,11 @@ public class SpringBootTestContextBootstrapper extends DefaultTestContextBootstr
|
||||
&& getAnnotation(WebAppConfiguration.class, testClass) != null) {
|
||||
throw new IllegalStateException("@WebAppConfiguration should only be used "
|
||||
+ "with @SpringBootTest when @SpringBootTest is configured with a "
|
||||
+ "mock web environment. Please remove @WebAppConfiguration or "
|
||||
+ "reconfigure @SpringBootTest.");
|
||||
+ "mock web environment. Please remove @WebAppConfiguration or " + "reconfigure @SpringBootTest.");
|
||||
}
|
||||
}
|
||||
|
||||
private <T extends Annotation> T getAnnotation(Class<T> annotationType,
|
||||
Class<?> testClass) {
|
||||
private <T extends Annotation> T getAnnotation(Class<T> annotationType, Class<?> testClass) {
|
||||
return AnnotatedElementUtils.getMergedAnnotation(testClass, annotationType);
|
||||
}
|
||||
|
||||
@@ -357,10 +329,9 @@ public class SpringBootTestContextBootstrapper extends DefaultTestContextBootstr
|
||||
* @param classes the replacement classes
|
||||
* @return a new {@link MergedContextConfiguration}
|
||||
*/
|
||||
protected final MergedContextConfiguration createModifiedConfig(
|
||||
MergedContextConfiguration mergedConfig, Class<?>[] classes) {
|
||||
return createModifiedConfig(mergedConfig, classes,
|
||||
mergedConfig.getPropertySourceProperties());
|
||||
protected final MergedContextConfiguration createModifiedConfig(MergedContextConfiguration mergedConfig,
|
||||
Class<?>[] classes) {
|
||||
return createModifiedConfig(mergedConfig, classes, mergedConfig.getPropertySourceProperties());
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -371,13 +342,10 @@ public class SpringBootTestContextBootstrapper extends DefaultTestContextBootstr
|
||||
* @param propertySourceProperties the replacement properties
|
||||
* @return a new {@link MergedContextConfiguration}
|
||||
*/
|
||||
protected final MergedContextConfiguration createModifiedConfig(
|
||||
MergedContextConfiguration mergedConfig, Class<?>[] classes,
|
||||
String[] propertySourceProperties) {
|
||||
return new MergedContextConfiguration(mergedConfig.getTestClass(),
|
||||
mergedConfig.getLocations(), classes,
|
||||
mergedConfig.getContextInitializerClasses(),
|
||||
mergedConfig.getActiveProfiles(),
|
||||
protected final MergedContextConfiguration createModifiedConfig(MergedContextConfiguration mergedConfig,
|
||||
Class<?>[] classes, String[] propertySourceProperties) {
|
||||
return new MergedContextConfiguration(mergedConfig.getTestClass(), mergedConfig.getLocations(), classes,
|
||||
mergedConfig.getContextInitializerClasses(), mergedConfig.getActiveProfiles(),
|
||||
mergedConfig.getPropertySourceLocations(), propertySourceProperties,
|
||||
mergedConfig.getContextCustomizers(), mergedConfig.getContextLoader(),
|
||||
getCacheAwareContextLoaderDelegate(), mergedConfig.getParent());
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2012-2018 the original author or authors.
|
||||
* Copyright 2012-2019 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -48,8 +48,8 @@ import org.springframework.util.Assert;
|
||||
* @see AssertableReactiveWebApplicationContext
|
||||
* @see ApplicationContextAssert
|
||||
*/
|
||||
public interface ApplicationContextAssertProvider<C extends ApplicationContext> extends
|
||||
ApplicationContext, AssertProvider<ApplicationContextAssert<C>>, Closeable {
|
||||
public interface ApplicationContextAssertProvider<C extends ApplicationContext>
|
||||
extends ApplicationContext, AssertProvider<ApplicationContextAssert<C>>, Closeable {
|
||||
|
||||
/**
|
||||
* Return an assert for AspectJ.
|
||||
@@ -100,17 +100,15 @@ public interface ApplicationContextAssertProvider<C extends ApplicationContext>
|
||||
* @return a {@link ApplicationContextAssertProvider} instance
|
||||
*/
|
||||
@SuppressWarnings("unchecked")
|
||||
static <T extends ApplicationContextAssertProvider<C>, C extends ApplicationContext> T get(
|
||||
Class<T> type, Class<? extends C> contextType,
|
||||
Supplier<? extends C> contextSupplier) {
|
||||
static <T extends ApplicationContextAssertProvider<C>, C extends ApplicationContext> T get(Class<T> type,
|
||||
Class<? extends C> contextType, Supplier<? extends C> contextSupplier) {
|
||||
Assert.notNull(type, "Type must not be null");
|
||||
Assert.isTrue(type.isInterface(), "Type must be an interface");
|
||||
Assert.notNull(contextType, "ContextType must not be null");
|
||||
Assert.isTrue(contextType.isInterface(), "ContextType must be an interface");
|
||||
Class<?>[] interfaces = { type, contextType };
|
||||
return (T) Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(),
|
||||
interfaces, new AssertProviderApplicationContextInvocationHandler(
|
||||
contextType, contextSupplier));
|
||||
return (T) Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), interfaces,
|
||||
new AssertProviderApplicationContextInvocationHandler(contextType, contextSupplier));
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2012-2018 the original author or authors.
|
||||
* Copyright 2012-2019 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -39,8 +39,8 @@ class TestTypeExcludeFilter extends TypeExcludeFilter {
|
||||
"org.junit.platform.commons.annotation.Testable" };
|
||||
|
||||
@Override
|
||||
public boolean match(MetadataReader metadataReader,
|
||||
MetadataReaderFactory metadataReaderFactory) throws IOException {
|
||||
public boolean match(MetadataReader metadataReader, MetadataReaderFactory metadataReaderFactory)
|
||||
throws IOException {
|
||||
if (isTestConfiguration(metadataReader)) {
|
||||
return true;
|
||||
}
|
||||
@@ -50,8 +50,7 @@ class TestTypeExcludeFilter extends TypeExcludeFilter {
|
||||
String enclosing = metadataReader.getClassMetadata().getEnclosingClassName();
|
||||
if (enclosing != null) {
|
||||
try {
|
||||
if (match(metadataReaderFactory.getMetadataReader(enclosing),
|
||||
metadataReaderFactory)) {
|
||||
if (match(metadataReaderFactory.getMetadataReader(enclosing), metadataReaderFactory)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -63,8 +62,7 @@ class TestTypeExcludeFilter extends TypeExcludeFilter {
|
||||
}
|
||||
|
||||
private boolean isTestConfiguration(MetadataReader metadataReader) {
|
||||
return (metadataReader.getAnnotationMetadata()
|
||||
.isAnnotated(TestComponent.class.getName()));
|
||||
return (metadataReader.getAnnotationMetadata().isAnnotated(TestComponent.class.getName()));
|
||||
}
|
||||
|
||||
private boolean isTestClass(MetadataReader metadataReader) {
|
||||
|
||||
@@ -117,8 +117,8 @@ public abstract class AbstractApplicationContextRunner<SELF extends AbstractAppl
|
||||
* @param contextFactory the factory used to create the actual context
|
||||
*/
|
||||
protected AbstractApplicationContextRunner(Supplier<C> contextFactory) {
|
||||
this(contextFactory, Collections.emptyList(), TestPropertyValues.empty(),
|
||||
TestPropertyValues.empty(), null, null, Collections.emptyList());
|
||||
this(contextFactory, Collections.emptyList(), TestPropertyValues.empty(), TestPropertyValues.empty(), null,
|
||||
null, Collections.emptyList());
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -132,9 +132,8 @@ public abstract class AbstractApplicationContextRunner<SELF extends AbstractAppl
|
||||
* @param configurations the configuration
|
||||
*/
|
||||
protected AbstractApplicationContextRunner(Supplier<C> contextFactory,
|
||||
List<ApplicationContextInitializer<? super C>> initializers,
|
||||
TestPropertyValues environmentProperties, TestPropertyValues systemProperties,
|
||||
ClassLoader classLoader, ApplicationContext parent,
|
||||
List<ApplicationContextInitializer<? super C>> initializers, TestPropertyValues environmentProperties,
|
||||
TestPropertyValues systemProperties, ClassLoader classLoader, ApplicationContext parent,
|
||||
List<Configurations> configurations) {
|
||||
Assert.notNull(contextFactory, "ContextFactory must not be null");
|
||||
Assert.notNull(environmentProperties, "EnvironmentProperties must not be null");
|
||||
@@ -156,12 +155,10 @@ public abstract class AbstractApplicationContextRunner<SELF extends AbstractAppl
|
||||
* @param initializer the initializer to add
|
||||
* @return a new instance with the updated initializers
|
||||
*/
|
||||
public SELF withInitializer(
|
||||
ApplicationContextInitializer<? super ConfigurableApplicationContext> initializer) {
|
||||
public SELF withInitializer(ApplicationContextInitializer<? super ConfigurableApplicationContext> initializer) {
|
||||
Assert.notNull(initializer, "Initializer must not be null");
|
||||
return newInstance(this.contextFactory, add(this.initializers, initializer),
|
||||
this.environmentProperties, this.systemProperties, this.classLoader,
|
||||
this.parent, this.configurations);
|
||||
return newInstance(this.contextFactory, add(this.initializers, initializer), this.environmentProperties,
|
||||
this.systemProperties, this.classLoader, this.parent, this.configurations);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -175,9 +172,8 @@ public abstract class AbstractApplicationContextRunner<SELF extends AbstractAppl
|
||||
* @see #withSystemProperties(String...)
|
||||
*/
|
||||
public SELF withPropertyValues(String... pairs) {
|
||||
return newInstance(this.contextFactory, this.initializers,
|
||||
this.environmentProperties.and(pairs), this.systemProperties,
|
||||
this.classLoader, this.parent, this.configurations);
|
||||
return newInstance(this.contextFactory, this.initializers, this.environmentProperties.and(pairs),
|
||||
this.systemProperties, this.classLoader, this.parent, this.configurations);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -191,9 +187,8 @@ public abstract class AbstractApplicationContextRunner<SELF extends AbstractAppl
|
||||
* @see #withSystemProperties(String...)
|
||||
*/
|
||||
public SELF withSystemProperties(String... pairs) {
|
||||
return newInstance(this.contextFactory, this.initializers,
|
||||
this.environmentProperties, this.systemProperties.and(pairs),
|
||||
this.classLoader, this.parent, this.configurations);
|
||||
return newInstance(this.contextFactory, this.initializers, this.environmentProperties,
|
||||
this.systemProperties.and(pairs), this.classLoader, this.parent, this.configurations);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -204,9 +199,8 @@ public abstract class AbstractApplicationContextRunner<SELF extends AbstractAppl
|
||||
* @see FilteredClassLoader
|
||||
*/
|
||||
public SELF withClassLoader(ClassLoader classLoader) {
|
||||
return newInstance(this.contextFactory, this.initializers,
|
||||
this.environmentProperties, this.systemProperties, classLoader,
|
||||
this.parent, this.configurations);
|
||||
return newInstance(this.contextFactory, this.initializers, this.environmentProperties, this.systemProperties,
|
||||
classLoader, this.parent, this.configurations);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -216,9 +210,8 @@ public abstract class AbstractApplicationContextRunner<SELF extends AbstractAppl
|
||||
* @return a new instance with the updated parent
|
||||
*/
|
||||
public SELF withParent(ApplicationContext parent) {
|
||||
return newInstance(this.contextFactory, this.initializers,
|
||||
this.environmentProperties, this.systemProperties, this.classLoader,
|
||||
parent, this.configurations);
|
||||
return newInstance(this.contextFactory, this.initializers, this.environmentProperties, this.systemProperties,
|
||||
this.classLoader, parent, this.configurations);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -238,9 +231,8 @@ public abstract class AbstractApplicationContextRunner<SELF extends AbstractAppl
|
||||
*/
|
||||
public SELF withConfiguration(Configurations configurations) {
|
||||
Assert.notNull(configurations, "Configurations must not be null");
|
||||
return newInstance(this.contextFactory, this.initializers,
|
||||
this.environmentProperties, this.systemProperties, this.classLoader,
|
||||
this.parent, add(this.configurations, configurations));
|
||||
return newInstance(this.contextFactory, this.initializers, this.environmentProperties, this.systemProperties,
|
||||
this.classLoader, this.parent, add(this.configurations, configurations));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -260,9 +252,8 @@ public abstract class AbstractApplicationContextRunner<SELF extends AbstractAppl
|
||||
}
|
||||
|
||||
protected abstract SELF newInstance(Supplier<C> contextFactory,
|
||||
List<ApplicationContextInitializer<? super C>> initializers,
|
||||
TestPropertyValues environmentProperties, TestPropertyValues systemProperties,
|
||||
ClassLoader classLoader, ApplicationContext parent,
|
||||
List<ApplicationContextInitializer<? super C>> initializers, TestPropertyValues environmentProperties,
|
||||
TestPropertyValues systemProperties, ClassLoader classLoader, ApplicationContext parent,
|
||||
List<Configurations> configurations);
|
||||
|
||||
/**
|
||||
@@ -304,12 +295,10 @@ public abstract class AbstractApplicationContextRunner<SELF extends AbstractAppl
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
private A createAssertableContext() {
|
||||
ResolvableType resolvableType = ResolvableType
|
||||
.forClass(AbstractApplicationContextRunner.class, getClass());
|
||||
ResolvableType resolvableType = ResolvableType.forClass(AbstractApplicationContextRunner.class, getClass());
|
||||
Class<A> assertType = (Class<A>) resolvableType.resolveGeneric(1);
|
||||
Class<C> contextType = (Class<C>) resolvableType.resolveGeneric(2);
|
||||
return ApplicationContextAssertProvider.get(assertType, contextType,
|
||||
this::createAndLoadContext);
|
||||
return ApplicationContextAssertProvider.get(assertType, contextType, this::createAndLoadContext);
|
||||
}
|
||||
|
||||
private C createAndLoadContext() {
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2012-2018 the original author or authors.
|
||||
* Copyright 2012-2019 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -54,31 +54,25 @@ public class ApplicationContextRunner extends
|
||||
* {@code contextFactory} as the underlying source.
|
||||
* @param contextFactory a supplier that returns a new instance on each call
|
||||
*/
|
||||
public ApplicationContextRunner(
|
||||
Supplier<ConfigurableApplicationContext> contextFactory) {
|
||||
public ApplicationContextRunner(Supplier<ConfigurableApplicationContext> contextFactory) {
|
||||
super(contextFactory);
|
||||
}
|
||||
|
||||
private ApplicationContextRunner(
|
||||
Supplier<ConfigurableApplicationContext> contextFactory,
|
||||
private ApplicationContextRunner(Supplier<ConfigurableApplicationContext> contextFactory,
|
||||
List<ApplicationContextInitializer<? super ConfigurableApplicationContext>> initializers,
|
||||
TestPropertyValues environmentProperties, TestPropertyValues systemProperties,
|
||||
ClassLoader classLoader, ApplicationContext parent,
|
||||
List<Configurations> configurations) {
|
||||
super(contextFactory, initializers, environmentProperties, systemProperties,
|
||||
classLoader, parent, configurations);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected ApplicationContextRunner newInstance(
|
||||
Supplier<ConfigurableApplicationContext> contextFactory,
|
||||
List<ApplicationContextInitializer<? super ConfigurableApplicationContext>> initializers,
|
||||
TestPropertyValues environmentProperties, TestPropertyValues systemProperties,
|
||||
ClassLoader classLoader, ApplicationContext parent,
|
||||
List<Configurations> configurations) {
|
||||
return new ApplicationContextRunner(contextFactory, initializers,
|
||||
environmentProperties, systemProperties, classLoader, parent,
|
||||
TestPropertyValues environmentProperties, TestPropertyValues systemProperties, ClassLoader classLoader,
|
||||
ApplicationContext parent, List<Configurations> configurations) {
|
||||
super(contextFactory, initializers, environmentProperties, systemProperties, classLoader, parent,
|
||||
configurations);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected ApplicationContextRunner newInstance(Supplier<ConfigurableApplicationContext> contextFactory,
|
||||
List<ApplicationContextInitializer<? super ConfigurableApplicationContext>> initializers,
|
||||
TestPropertyValues environmentProperties, TestPropertyValues systemProperties, ClassLoader classLoader,
|
||||
ApplicationContext parent, List<Configurations> configurations) {
|
||||
return new ApplicationContextRunner(contextFactory, initializers, environmentProperties, systemProperties,
|
||||
classLoader, parent, configurations);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2012-2018 the original author or authors.
|
||||
* Copyright 2012-2019 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -54,31 +54,26 @@ public final class ReactiveWebApplicationContextRunner extends
|
||||
* {@code contextFactory} as the underlying source.
|
||||
* @param contextFactory a supplier that returns a new instance on each call
|
||||
*/
|
||||
public ReactiveWebApplicationContextRunner(
|
||||
Supplier<ConfigurableReactiveWebApplicationContext> contextFactory) {
|
||||
public ReactiveWebApplicationContextRunner(Supplier<ConfigurableReactiveWebApplicationContext> contextFactory) {
|
||||
super(contextFactory);
|
||||
}
|
||||
|
||||
private ReactiveWebApplicationContextRunner(
|
||||
Supplier<ConfigurableReactiveWebApplicationContext> contextFactory,
|
||||
private ReactiveWebApplicationContextRunner(Supplier<ConfigurableReactiveWebApplicationContext> contextFactory,
|
||||
List<ApplicationContextInitializer<? super ConfigurableReactiveWebApplicationContext>> initializers,
|
||||
TestPropertyValues environmentProperties, TestPropertyValues systemProperties,
|
||||
ClassLoader classLoader, ApplicationContext parent,
|
||||
List<Configurations> configurations) {
|
||||
super(contextFactory, initializers, environmentProperties, systemProperties,
|
||||
classLoader, parent, configurations);
|
||||
TestPropertyValues environmentProperties, TestPropertyValues systemProperties, ClassLoader classLoader,
|
||||
ApplicationContext parent, List<Configurations> configurations) {
|
||||
super(contextFactory, initializers, environmentProperties, systemProperties, classLoader, parent,
|
||||
configurations);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected ReactiveWebApplicationContextRunner newInstance(
|
||||
Supplier<ConfigurableReactiveWebApplicationContext> contextFactory,
|
||||
List<ApplicationContextInitializer<? super ConfigurableReactiveWebApplicationContext>> initializers,
|
||||
TestPropertyValues environmentProperties, TestPropertyValues systemProperties,
|
||||
ClassLoader classLoader, ApplicationContext parent,
|
||||
List<Configurations> configurations) {
|
||||
return new ReactiveWebApplicationContextRunner(contextFactory, initializers,
|
||||
environmentProperties, systemProperties, classLoader, parent,
|
||||
configurations);
|
||||
TestPropertyValues environmentProperties, TestPropertyValues systemProperties, ClassLoader classLoader,
|
||||
ApplicationContext parent, List<Configurations> configurations) {
|
||||
return new ReactiveWebApplicationContextRunner(contextFactory, initializers, environmentProperties,
|
||||
systemProperties, classLoader, parent, configurations);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2012-2018 the original author or authors.
|
||||
* Copyright 2012-2019 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -58,31 +58,25 @@ public final class WebApplicationContextRunner extends
|
||||
* {@code contextFactory} as the underlying source.
|
||||
* @param contextFactory a supplier that returns a new instance on each call
|
||||
*/
|
||||
public WebApplicationContextRunner(
|
||||
Supplier<ConfigurableWebApplicationContext> contextFactory) {
|
||||
public WebApplicationContextRunner(Supplier<ConfigurableWebApplicationContext> contextFactory) {
|
||||
super(contextFactory);
|
||||
}
|
||||
|
||||
private WebApplicationContextRunner(
|
||||
Supplier<ConfigurableWebApplicationContext> contextFactory,
|
||||
private WebApplicationContextRunner(Supplier<ConfigurableWebApplicationContext> contextFactory,
|
||||
List<ApplicationContextInitializer<? super ConfigurableWebApplicationContext>> initializers,
|
||||
TestPropertyValues environmentProperties, TestPropertyValues systemProperties,
|
||||
ClassLoader classLoader, ApplicationContext parent,
|
||||
List<Configurations> configurations) {
|
||||
super(contextFactory, initializers, environmentProperties, systemProperties,
|
||||
classLoader, parent, configurations);
|
||||
TestPropertyValues environmentProperties, TestPropertyValues systemProperties, ClassLoader classLoader,
|
||||
ApplicationContext parent, List<Configurations> configurations) {
|
||||
super(contextFactory, initializers, environmentProperties, systemProperties, classLoader, parent,
|
||||
configurations);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected WebApplicationContextRunner newInstance(
|
||||
Supplier<ConfigurableWebApplicationContext> contextFactory,
|
||||
protected WebApplicationContextRunner newInstance(Supplier<ConfigurableWebApplicationContext> contextFactory,
|
||||
List<ApplicationContextInitializer<? super ConfigurableWebApplicationContext>> initializers,
|
||||
TestPropertyValues environmentProperties, TestPropertyValues systemProperties,
|
||||
ClassLoader classLoader, ApplicationContext parent,
|
||||
List<Configurations> configurations) {
|
||||
return new WebApplicationContextRunner(contextFactory, initializers,
|
||||
environmentProperties, systemProperties, classLoader, parent,
|
||||
configurations);
|
||||
TestPropertyValues environmentProperties, TestPropertyValues systemProperties, ClassLoader classLoader,
|
||||
ApplicationContext parent, List<Configurations> configurations) {
|
||||
return new WebApplicationContextRunner(contextFactory, initializers, environmentProperties, systemProperties,
|
||||
classLoader, parent, configurations);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -72,8 +72,7 @@ public class JsonContentAssert extends AbstractAssert<JsonContentAssert, CharSeq
|
||||
* @param json the actual JSON content
|
||||
* @since 1.4.1
|
||||
*/
|
||||
public JsonContentAssert(Class<?> resourceLoadClass, Charset charset,
|
||||
CharSequence json) {
|
||||
public JsonContentAssert(Class<?> resourceLoadClass, Charset charset, CharSequence json) {
|
||||
this(resourceLoadClass, charset, json, Configuration.defaultConfiguration());
|
||||
}
|
||||
|
||||
@@ -85,8 +84,7 @@ public class JsonContentAssert extends AbstractAssert<JsonContentAssert, CharSeq
|
||||
* @param json the actual JSON content
|
||||
* @param configuration the json-path configuration
|
||||
*/
|
||||
JsonContentAssert(Class<?> resourceLoadClass, Charset charset, CharSequence json,
|
||||
Configuration configuration) {
|
||||
JsonContentAssert(Class<?> resourceLoadClass, Charset charset, CharSequence json, Configuration configuration) {
|
||||
super(json, JsonContentAssert.class);
|
||||
this.configuration = configuration;
|
||||
this.loader = new JsonLoader(resourceLoadClass, charset);
|
||||
@@ -114,8 +112,7 @@ public class JsonContentAssert extends AbstractAssert<JsonContentAssert, CharSeq
|
||||
if (expected instanceof Resource) {
|
||||
return isEqualToJson((Resource) expected);
|
||||
}
|
||||
throw new AssertionError(
|
||||
"Unsupported type for JSON assert " + expected.getClass());
|
||||
throw new AssertionError("Unsupported type for JSON assert " + expected.getClass());
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -217,8 +214,7 @@ public class JsonContentAssert extends AbstractAssert<JsonContentAssert, CharSeq
|
||||
* @return {@code this} assertion object
|
||||
* @throws AssertionError if the actual JSON value is not equal to the given one
|
||||
*/
|
||||
public JsonContentAssert isStrictlyEqualToJson(String path,
|
||||
Class<?> resourceLoadClass) {
|
||||
public JsonContentAssert isStrictlyEqualToJson(String path, Class<?> resourceLoadClass) {
|
||||
String expectedJson = this.loader.getJson(path, resourceLoadClass);
|
||||
return assertNotFailed(compare(expectedJson, JSONCompareMode.STRICT));
|
||||
}
|
||||
@@ -231,8 +227,7 @@ public class JsonContentAssert extends AbstractAssert<JsonContentAssert, CharSeq
|
||||
* @throws AssertionError if the actual JSON value is not equal to the given one
|
||||
*/
|
||||
public JsonContentAssert isStrictlyEqualToJson(byte[] expected) {
|
||||
return assertNotFailed(
|
||||
compare(this.loader.getJson(expected), JSONCompareMode.STRICT));
|
||||
return assertNotFailed(compare(this.loader.getJson(expected), JSONCompareMode.STRICT));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -281,8 +276,7 @@ public class JsonContentAssert extends AbstractAssert<JsonContentAssert, CharSeq
|
||||
* @return {@code this} assertion object
|
||||
* @throws AssertionError if the actual JSON value is not equal to the given one
|
||||
*/
|
||||
public JsonContentAssert isEqualToJson(CharSequence expected,
|
||||
JSONCompareMode compareMode) {
|
||||
public JsonContentAssert isEqualToJson(CharSequence expected, JSONCompareMode compareMode) {
|
||||
String expectedJson = this.loader.getJson(expected);
|
||||
return assertNotFailed(compare(expectedJson, compareMode));
|
||||
}
|
||||
@@ -295,8 +289,7 @@ public class JsonContentAssert extends AbstractAssert<JsonContentAssert, CharSeq
|
||||
* @return {@code this} assertion object
|
||||
* @throws AssertionError if the actual JSON value is not equal to the given one
|
||||
*/
|
||||
public JsonContentAssert isEqualToJson(String path, Class<?> resourceLoadClass,
|
||||
JSONCompareMode compareMode) {
|
||||
public JsonContentAssert isEqualToJson(String path, Class<?> resourceLoadClass, JSONCompareMode compareMode) {
|
||||
String expectedJson = this.loader.getJson(path, resourceLoadClass);
|
||||
return assertNotFailed(compare(expectedJson, compareMode));
|
||||
}
|
||||
@@ -332,8 +325,7 @@ public class JsonContentAssert extends AbstractAssert<JsonContentAssert, CharSeq
|
||||
* @return {@code this} assertion object
|
||||
* @throws AssertionError if the actual JSON value is not equal to the given one
|
||||
*/
|
||||
public JsonContentAssert isEqualToJson(InputStream expected,
|
||||
JSONCompareMode compareMode) {
|
||||
public JsonContentAssert isEqualToJson(InputStream expected, JSONCompareMode compareMode) {
|
||||
return assertNotFailed(compare(this.loader.getJson(expected), compareMode));
|
||||
}
|
||||
|
||||
@@ -344,8 +336,7 @@ public class JsonContentAssert extends AbstractAssert<JsonContentAssert, CharSeq
|
||||
* @return {@code this} assertion object
|
||||
* @throws AssertionError if the actual JSON value is not equal to the given one
|
||||
*/
|
||||
public JsonContentAssert isEqualToJson(Resource expected,
|
||||
JSONCompareMode compareMode) {
|
||||
public JsonContentAssert isEqualToJson(Resource expected, JSONCompareMode compareMode) {
|
||||
String expectedJson = this.loader.getJson(expected);
|
||||
return assertNotFailed(compare(expectedJson, compareMode));
|
||||
}
|
||||
@@ -360,8 +351,7 @@ public class JsonContentAssert extends AbstractAssert<JsonContentAssert, CharSeq
|
||||
* @return {@code this} assertion object
|
||||
* @throws AssertionError if the actual JSON value is not equal to the given one
|
||||
*/
|
||||
public JsonContentAssert isEqualToJson(CharSequence expected,
|
||||
JSONComparator comparator) {
|
||||
public JsonContentAssert isEqualToJson(CharSequence expected, JSONComparator comparator) {
|
||||
String expectedJson = this.loader.getJson(expected);
|
||||
return assertNotFailed(compare(expectedJson, comparator));
|
||||
}
|
||||
@@ -374,8 +364,7 @@ public class JsonContentAssert extends AbstractAssert<JsonContentAssert, CharSeq
|
||||
* @return {@code this} assertion object
|
||||
* @throws AssertionError if the actual JSON value is not equal to the given one
|
||||
*/
|
||||
public JsonContentAssert isEqualToJson(String path, Class<?> resourceLoadClass,
|
||||
JSONComparator comparator) {
|
||||
public JsonContentAssert isEqualToJson(String path, Class<?> resourceLoadClass, JSONComparator comparator) {
|
||||
String expectedJson = this.loader.getJson(path, resourceLoadClass);
|
||||
return assertNotFailed(compare(expectedJson, comparator));
|
||||
}
|
||||
@@ -411,8 +400,7 @@ public class JsonContentAssert extends AbstractAssert<JsonContentAssert, CharSeq
|
||||
* @return {@code this} assertion object
|
||||
* @throws AssertionError if the actual JSON value is not equal to the given one
|
||||
*/
|
||||
public JsonContentAssert isEqualToJson(InputStream expected,
|
||||
JSONComparator comparator) {
|
||||
public JsonContentAssert isEqualToJson(InputStream expected, JSONComparator comparator) {
|
||||
String expectedJson = this.loader.getJson(expected);
|
||||
return assertNotFailed(compare(expectedJson, comparator));
|
||||
}
|
||||
@@ -451,8 +439,7 @@ public class JsonContentAssert extends AbstractAssert<JsonContentAssert, CharSeq
|
||||
if (expected instanceof Resource) {
|
||||
return isNotEqualToJson((Resource) expected);
|
||||
}
|
||||
throw new AssertionError(
|
||||
"Unsupported type for JSON assert " + expected.getClass());
|
||||
throw new AssertionError("Unsupported type for JSON assert " + expected.getClass());
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -527,8 +514,7 @@ public class JsonContentAssert extends AbstractAssert<JsonContentAssert, CharSeq
|
||||
* @throws AssertionError if the actual JSON value is equal to the given one
|
||||
*/
|
||||
public JsonContentAssert isNotEqualToJson(Resource expected) {
|
||||
return assertNotPassed(
|
||||
compare(this.loader.getJson(expected), JSONCompareMode.LENIENT));
|
||||
return assertNotPassed(compare(this.loader.getJson(expected), JSONCompareMode.LENIENT));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -554,8 +540,7 @@ public class JsonContentAssert extends AbstractAssert<JsonContentAssert, CharSeq
|
||||
* @return {@code this} assertion object
|
||||
* @throws AssertionError if the actual JSON value is equal to the given one
|
||||
*/
|
||||
public JsonContentAssert isNotStrictlyEqualToJson(String path,
|
||||
Class<?> resourceLoadClass) {
|
||||
public JsonContentAssert isNotStrictlyEqualToJson(String path, Class<?> resourceLoadClass) {
|
||||
String expectedJson = this.loader.getJson(path, resourceLoadClass);
|
||||
return assertNotPassed(compare(expectedJson, JSONCompareMode.STRICT));
|
||||
}
|
||||
@@ -618,8 +603,7 @@ public class JsonContentAssert extends AbstractAssert<JsonContentAssert, CharSeq
|
||||
* @return {@code this} assertion object
|
||||
* @throws AssertionError if the actual JSON value is equal to the given one
|
||||
*/
|
||||
public JsonContentAssert isNotEqualToJson(CharSequence expected,
|
||||
JSONCompareMode compareMode) {
|
||||
public JsonContentAssert isNotEqualToJson(CharSequence expected, JSONCompareMode compareMode) {
|
||||
String expectedJson = this.loader.getJson(expected);
|
||||
return assertNotPassed(compare(expectedJson, compareMode));
|
||||
}
|
||||
@@ -632,8 +616,7 @@ public class JsonContentAssert extends AbstractAssert<JsonContentAssert, CharSeq
|
||||
* @return {@code this} assertion object
|
||||
* @throws AssertionError if the actual JSON value is equal to the given one
|
||||
*/
|
||||
public JsonContentAssert isNotEqualToJson(String path, Class<?> resourceLoadClass,
|
||||
JSONCompareMode compareMode) {
|
||||
public JsonContentAssert isNotEqualToJson(String path, Class<?> resourceLoadClass, JSONCompareMode compareMode) {
|
||||
String expectedJson = this.loader.getJson(path, resourceLoadClass);
|
||||
return assertNotPassed(compare(expectedJson, compareMode));
|
||||
}
|
||||
@@ -645,8 +628,7 @@ public class JsonContentAssert extends AbstractAssert<JsonContentAssert, CharSeq
|
||||
* @return {@code this} assertion object
|
||||
* @throws AssertionError if the actual JSON value is equal to the given one
|
||||
*/
|
||||
public JsonContentAssert isNotEqualToJson(byte[] expected,
|
||||
JSONCompareMode compareMode) {
|
||||
public JsonContentAssert isNotEqualToJson(byte[] expected, JSONCompareMode compareMode) {
|
||||
String expectedJson = this.loader.getJson(expected);
|
||||
return assertNotPassed(compare(expectedJson, compareMode));
|
||||
}
|
||||
@@ -658,8 +640,7 @@ public class JsonContentAssert extends AbstractAssert<JsonContentAssert, CharSeq
|
||||
* @return {@code this} assertion object
|
||||
* @throws AssertionError if the actual JSON value is equal to the given one
|
||||
*/
|
||||
public JsonContentAssert isNotEqualToJson(File expected,
|
||||
JSONCompareMode compareMode) {
|
||||
public JsonContentAssert isNotEqualToJson(File expected, JSONCompareMode compareMode) {
|
||||
String expectedJson = this.loader.getJson(expected);
|
||||
return assertNotPassed(compare(expectedJson, compareMode));
|
||||
}
|
||||
@@ -671,8 +652,7 @@ public class JsonContentAssert extends AbstractAssert<JsonContentAssert, CharSeq
|
||||
* @return {@code this} assertion object
|
||||
* @throws AssertionError if the actual JSON value is equal to the given one
|
||||
*/
|
||||
public JsonContentAssert isNotEqualToJson(InputStream expected,
|
||||
JSONCompareMode compareMode) {
|
||||
public JsonContentAssert isNotEqualToJson(InputStream expected, JSONCompareMode compareMode) {
|
||||
String expectedJson = this.loader.getJson(expected);
|
||||
return assertNotPassed(compare(expectedJson, compareMode));
|
||||
}
|
||||
@@ -684,8 +664,7 @@ public class JsonContentAssert extends AbstractAssert<JsonContentAssert, CharSeq
|
||||
* @return {@code this} assertion object
|
||||
* @throws AssertionError if the actual JSON value is equal to the given one
|
||||
*/
|
||||
public JsonContentAssert isNotEqualToJson(Resource expected,
|
||||
JSONCompareMode compareMode) {
|
||||
public JsonContentAssert isNotEqualToJson(Resource expected, JSONCompareMode compareMode) {
|
||||
String expectedJson = this.loader.getJson(expected);
|
||||
return assertNotPassed(compare(expectedJson, compareMode));
|
||||
}
|
||||
@@ -700,8 +679,7 @@ public class JsonContentAssert extends AbstractAssert<JsonContentAssert, CharSeq
|
||||
* @return {@code this} assertion object
|
||||
* @throws AssertionError if the actual JSON value is equal to the given one
|
||||
*/
|
||||
public JsonContentAssert isNotEqualToJson(CharSequence expected,
|
||||
JSONComparator comparator) {
|
||||
public JsonContentAssert isNotEqualToJson(CharSequence expected, JSONComparator comparator) {
|
||||
String expectedJson = this.loader.getJson(expected);
|
||||
return assertNotPassed(compare(expectedJson, comparator));
|
||||
}
|
||||
@@ -714,8 +692,7 @@ public class JsonContentAssert extends AbstractAssert<JsonContentAssert, CharSeq
|
||||
* @return {@code this} assertion object
|
||||
* @throws AssertionError if the actual JSON value is equal to the given one
|
||||
*/
|
||||
public JsonContentAssert isNotEqualToJson(String path, Class<?> resourceLoadClass,
|
||||
JSONComparator comparator) {
|
||||
public JsonContentAssert isNotEqualToJson(String path, Class<?> resourceLoadClass, JSONComparator comparator) {
|
||||
String expectedJson = this.loader.getJson(path, resourceLoadClass);
|
||||
return assertNotPassed(compare(expectedJson, comparator));
|
||||
}
|
||||
@@ -727,8 +704,7 @@ public class JsonContentAssert extends AbstractAssert<JsonContentAssert, CharSeq
|
||||
* @return {@code this} assertion object
|
||||
* @throws AssertionError if the actual JSON value is equal to the given one
|
||||
*/
|
||||
public JsonContentAssert isNotEqualToJson(byte[] expected,
|
||||
JSONComparator comparator) {
|
||||
public JsonContentAssert isNotEqualToJson(byte[] expected, JSONComparator comparator) {
|
||||
String expectedJson = this.loader.getJson(expected);
|
||||
return assertNotPassed(compare(expectedJson, comparator));
|
||||
}
|
||||
@@ -752,8 +728,7 @@ public class JsonContentAssert extends AbstractAssert<JsonContentAssert, CharSeq
|
||||
* @return {@code this} assertion object
|
||||
* @throws AssertionError if the actual JSON value is equal to the given one
|
||||
*/
|
||||
public JsonContentAssert isNotEqualToJson(InputStream expected,
|
||||
JSONComparator comparator) {
|
||||
public JsonContentAssert isNotEqualToJson(InputStream expected, JSONComparator comparator) {
|
||||
String expectedJson = this.loader.getJson(expected);
|
||||
return assertNotPassed(compare(expectedJson, comparator));
|
||||
}
|
||||
@@ -765,8 +740,7 @@ public class JsonContentAssert extends AbstractAssert<JsonContentAssert, CharSeq
|
||||
* @return {@code this} assertion object
|
||||
* @throws AssertionError if the actual JSON value is equal to the given one
|
||||
*/
|
||||
public JsonContentAssert isNotEqualToJson(Resource expected,
|
||||
JSONComparator comparator) {
|
||||
public JsonContentAssert isNotEqualToJson(Resource expected, JSONComparator comparator) {
|
||||
String expectedJson = this.loader.getJson(expected);
|
||||
return assertNotPassed(compare(expectedJson, comparator));
|
||||
}
|
||||
@@ -795,8 +769,7 @@ public class JsonContentAssert extends AbstractAssert<JsonContentAssert, CharSeq
|
||||
* @return {@code this} assertion object
|
||||
* @throws AssertionError if the value at the given path is missing or not a string
|
||||
*/
|
||||
public JsonContentAssert hasJsonPathStringValue(CharSequence expression,
|
||||
Object... args) {
|
||||
public JsonContentAssert hasJsonPathStringValue(CharSequence expression, Object... args) {
|
||||
new JsonPathValue(expression, args).assertHasValue(String.class, "a string");
|
||||
return this;
|
||||
}
|
||||
@@ -810,8 +783,7 @@ public class JsonContentAssert extends AbstractAssert<JsonContentAssert, CharSeq
|
||||
* @return {@code this} assertion object
|
||||
* @throws AssertionError if the value at the given path is missing or not a number
|
||||
*/
|
||||
public JsonContentAssert hasJsonPathNumberValue(CharSequence expression,
|
||||
Object... args) {
|
||||
public JsonContentAssert hasJsonPathNumberValue(CharSequence expression, Object... args) {
|
||||
new JsonPathValue(expression, args).assertHasValue(Number.class, "a number");
|
||||
return this;
|
||||
}
|
||||
@@ -825,8 +797,7 @@ public class JsonContentAssert extends AbstractAssert<JsonContentAssert, CharSeq
|
||||
* @return {@code this} assertion object
|
||||
* @throws AssertionError if the value at the given path is missing or not a boolean
|
||||
*/
|
||||
public JsonContentAssert hasJsonPathBooleanValue(CharSequence expression,
|
||||
Object... args) {
|
||||
public JsonContentAssert hasJsonPathBooleanValue(CharSequence expression, Object... args) {
|
||||
new JsonPathValue(expression, args).assertHasValue(Boolean.class, "a boolean");
|
||||
return this;
|
||||
}
|
||||
@@ -840,8 +811,7 @@ public class JsonContentAssert extends AbstractAssert<JsonContentAssert, CharSeq
|
||||
* @return {@code this} assertion object
|
||||
* @throws AssertionError if the value at the given path is missing or not an array
|
||||
*/
|
||||
public JsonContentAssert hasJsonPathArrayValue(CharSequence expression,
|
||||
Object... args) {
|
||||
public JsonContentAssert hasJsonPathArrayValue(CharSequence expression, Object... args) {
|
||||
new JsonPathValue(expression, args).assertHasValue(List.class, "an array");
|
||||
return this;
|
||||
}
|
||||
@@ -854,8 +824,7 @@ public class JsonContentAssert extends AbstractAssert<JsonContentAssert, CharSeq
|
||||
* @return {@code this} assertion object
|
||||
* @throws AssertionError if the value at the given path is missing or not a map
|
||||
*/
|
||||
public JsonContentAssert hasJsonPathMapValue(CharSequence expression,
|
||||
Object... args) {
|
||||
public JsonContentAssert hasJsonPathMapValue(CharSequence expression, Object... args) {
|
||||
new JsonPathValue(expression, args).assertHasValue(Map.class, "a map");
|
||||
return this;
|
||||
}
|
||||
@@ -869,8 +838,7 @@ public class JsonContentAssert extends AbstractAssert<JsonContentAssert, CharSeq
|
||||
* @return {@code this} assertion object
|
||||
* @throws AssertionError if the value at the given path is not empty
|
||||
*/
|
||||
public JsonContentAssert hasEmptyJsonPathValue(CharSequence expression,
|
||||
Object... args) {
|
||||
public JsonContentAssert hasEmptyJsonPathValue(CharSequence expression, Object... args) {
|
||||
new JsonPathValue(expression, args).assertHasEmptyValue();
|
||||
return this;
|
||||
}
|
||||
@@ -885,8 +853,7 @@ public class JsonContentAssert extends AbstractAssert<JsonContentAssert, CharSeq
|
||||
* @return {@code this} assertion object
|
||||
* @throws AssertionError if the value at the given path is not missing
|
||||
*/
|
||||
public JsonContentAssert doesNotHaveJsonPathValue(CharSequence expression,
|
||||
Object... args) {
|
||||
public JsonContentAssert doesNotHaveJsonPathValue(CharSequence expression, Object... args) {
|
||||
new JsonPathValue(expression, args).assertDoesNotHaveValue();
|
||||
return this;
|
||||
}
|
||||
@@ -900,8 +867,7 @@ public class JsonContentAssert extends AbstractAssert<JsonContentAssert, CharSeq
|
||||
* @return {@code this} assertion object
|
||||
* @throws AssertionError if the value at the given path is empty
|
||||
*/
|
||||
public JsonContentAssert doesNotHaveEmptyJsonPathValue(CharSequence expression,
|
||||
Object... args) {
|
||||
public JsonContentAssert doesNotHaveEmptyJsonPathValue(CharSequence expression, Object... args) {
|
||||
new JsonPathValue(expression, args).assertDoesNotHaveEmptyValue();
|
||||
return this;
|
||||
}
|
||||
@@ -914,8 +880,7 @@ public class JsonContentAssert extends AbstractAssert<JsonContentAssert, CharSeq
|
||||
* @return a new assertion object whose object under test is the extracted item
|
||||
* @throws AssertionError if the path is not valid
|
||||
*/
|
||||
public AbstractObjectAssert<?, Object> extractingJsonPathValue(
|
||||
CharSequence expression, Object... args) {
|
||||
public AbstractObjectAssert<?, Object> extractingJsonPathValue(CharSequence expression, Object... args) {
|
||||
return Assertions.assertThat(new JsonPathValue(expression, args).getValue(false));
|
||||
}
|
||||
|
||||
@@ -927,10 +892,9 @@ public class JsonContentAssert extends AbstractAssert<JsonContentAssert, CharSeq
|
||||
* @return a new assertion object whose object under test is the extracted item
|
||||
* @throws AssertionError if the path is not valid or does not result in a string
|
||||
*/
|
||||
public AbstractCharSequenceAssert<?, String> extractingJsonPathStringValue(
|
||||
CharSequence expression, Object... args) {
|
||||
return Assertions.assertThat(
|
||||
extractingJsonPathValue(expression, args, String.class, "a string"));
|
||||
public AbstractCharSequenceAssert<?, String> extractingJsonPathStringValue(CharSequence expression,
|
||||
Object... args) {
|
||||
return Assertions.assertThat(extractingJsonPathValue(expression, args, String.class, "a string"));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -941,10 +905,8 @@ public class JsonContentAssert extends AbstractAssert<JsonContentAssert, CharSeq
|
||||
* @return a new assertion object whose object under test is the extracted item
|
||||
* @throws AssertionError if the path is not valid or does not result in a number
|
||||
*/
|
||||
public AbstractObjectAssert<?, Number> extractingJsonPathNumberValue(
|
||||
CharSequence expression, Object... args) {
|
||||
return Assertions.assertThat(
|
||||
extractingJsonPathValue(expression, args, Number.class, "a number"));
|
||||
public AbstractObjectAssert<?, Number> extractingJsonPathNumberValue(CharSequence expression, Object... args) {
|
||||
return Assertions.assertThat(extractingJsonPathValue(expression, args, Number.class, "a number"));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -955,10 +917,8 @@ public class JsonContentAssert extends AbstractAssert<JsonContentAssert, CharSeq
|
||||
* @return a new assertion object whose object under test is the extracted item
|
||||
* @throws AssertionError if the path is not valid or does not result in a boolean
|
||||
*/
|
||||
public AbstractBooleanAssert<?> extractingJsonPathBooleanValue(
|
||||
CharSequence expression, Object... args) {
|
||||
return Assertions.assertThat(
|
||||
extractingJsonPathValue(expression, args, Boolean.class, "a boolean"));
|
||||
public AbstractBooleanAssert<?> extractingJsonPathBooleanValue(CharSequence expression, Object... args) {
|
||||
return Assertions.assertThat(extractingJsonPathValue(expression, args, Boolean.class, "a boolean"));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -971,10 +931,8 @@ public class JsonContentAssert extends AbstractAssert<JsonContentAssert, CharSeq
|
||||
* @throws AssertionError if the path is not valid or does not result in an array
|
||||
*/
|
||||
@SuppressWarnings("unchecked")
|
||||
public <E> ListAssert<E> extractingJsonPathArrayValue(CharSequence expression,
|
||||
Object... args) {
|
||||
return Assertions.assertThat(
|
||||
extractingJsonPathValue(expression, args, List.class, "an array"));
|
||||
public <E> ListAssert<E> extractingJsonPathArrayValue(CharSequence expression, Object... args) {
|
||||
return Assertions.assertThat(extractingJsonPathValue(expression, args, List.class, "an array"));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -988,15 +946,13 @@ public class JsonContentAssert extends AbstractAssert<JsonContentAssert, CharSeq
|
||||
* @throws AssertionError if the path is not valid or does not result in a map
|
||||
*/
|
||||
@SuppressWarnings("unchecked")
|
||||
public <K, V> MapAssert<K, V> extractingJsonPathMapValue(CharSequence expression,
|
||||
Object... args) {
|
||||
return Assertions.assertThat(
|
||||
extractingJsonPathValue(expression, args, Map.class, "a map"));
|
||||
public <K, V> MapAssert<K, V> extractingJsonPathMapValue(CharSequence expression, Object... args) {
|
||||
return Assertions.assertThat(extractingJsonPathValue(expression, args, Map.class, "a map"));
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
private <T> T extractingJsonPathValue(CharSequence expression, Object[] args,
|
||||
Class<T> type, String expectedDescription) {
|
||||
private <T> T extractingJsonPathValue(CharSequence expression, Object[] args, Class<T> type,
|
||||
String expectedDescription) {
|
||||
JsonPathValue value = new JsonPathValue(expression, args);
|
||||
if (value.getValue(false) != null) {
|
||||
value.assertHasValue(type, expectedDescription);
|
||||
@@ -1004,14 +960,12 @@ public class JsonContentAssert extends AbstractAssert<JsonContentAssert, CharSeq
|
||||
return (T) value.getValue(false);
|
||||
}
|
||||
|
||||
private JSONCompareResult compare(CharSequence expectedJson,
|
||||
JSONCompareMode compareMode) {
|
||||
private JSONCompareResult compare(CharSequence expectedJson, JSONCompareMode compareMode) {
|
||||
if (this.actual == null) {
|
||||
return compareForNull(expectedJson);
|
||||
}
|
||||
try {
|
||||
return JSONCompare.compareJSON(
|
||||
(expectedJson != null) ? expectedJson.toString() : null,
|
||||
return JSONCompare.compareJSON((expectedJson != null) ? expectedJson.toString() : null,
|
||||
this.actual.toString(), compareMode);
|
||||
}
|
||||
catch (Exception ex) {
|
||||
@@ -1022,14 +976,12 @@ public class JsonContentAssert extends AbstractAssert<JsonContentAssert, CharSeq
|
||||
}
|
||||
}
|
||||
|
||||
private JSONCompareResult compare(CharSequence expectedJson,
|
||||
JSONComparator comparator) {
|
||||
private JSONCompareResult compare(CharSequence expectedJson, JSONComparator comparator) {
|
||||
if (this.actual == null) {
|
||||
return compareForNull(expectedJson);
|
||||
}
|
||||
try {
|
||||
return JSONCompare.compareJSON(
|
||||
(expectedJson != null) ? expectedJson.toString() : null,
|
||||
return JSONCompare.compareJSON((expectedJson != null) ? expectedJson.toString() : null,
|
||||
this.actual.toString(), comparator);
|
||||
}
|
||||
catch (Exception ex) {
|
||||
@@ -1073,8 +1025,7 @@ public class JsonContentAssert extends AbstractAssert<JsonContentAssert, CharSeq
|
||||
private final JsonPath jsonPath;
|
||||
|
||||
JsonPathValue(CharSequence expression, Object... args) {
|
||||
org.springframework.util.Assert.hasText(
|
||||
(expression != null) ? expression.toString() : null,
|
||||
org.springframework.util.Assert.hasText((expression != null) ? expression.toString() : null,
|
||||
"expression must not be null or empty");
|
||||
this.expression = String.format(expression.toString(), args);
|
||||
this.jsonPath = JsonPath.compile(this.expression);
|
||||
@@ -1143,9 +1094,8 @@ public class JsonContentAssert extends AbstractAssert<JsonContentAssert, CharSeq
|
||||
}
|
||||
|
||||
private String getExpectedValueMessage(String expectedDescription) {
|
||||
return String.format("Expected %s at JSON path \"%s\" but found: %s",
|
||||
expectedDescription, this.expression, ObjectUtils.nullSafeToString(
|
||||
StringUtils.quoteIfString(getValue(false))));
|
||||
return String.format("Expected %s at JSON path \"%s\" but found: %s", expectedDescription, this.expression,
|
||||
ObjectUtils.nullSafeToString(StringUtils.quoteIfString(getValue(false))));
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2012-2017 the original author or authors.
|
||||
* Copyright 2012-2019 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -63,28 +63,23 @@ class DefinitionsParser {
|
||||
}
|
||||
|
||||
private void parseElement(AnnotatedElement element) {
|
||||
for (MockBean annotation : AnnotationUtils.getRepeatableAnnotations(element,
|
||||
MockBean.class, MockBeans.class)) {
|
||||
for (MockBean annotation : AnnotationUtils.getRepeatableAnnotations(element, MockBean.class, MockBeans.class)) {
|
||||
parseMockBeanAnnotation(annotation, element);
|
||||
}
|
||||
for (SpyBean annotation : AnnotationUtils.getRepeatableAnnotations(element,
|
||||
SpyBean.class, SpyBeans.class)) {
|
||||
for (SpyBean annotation : AnnotationUtils.getRepeatableAnnotations(element, SpyBean.class, SpyBeans.class)) {
|
||||
parseSpyBeanAnnotation(annotation, element);
|
||||
}
|
||||
}
|
||||
|
||||
private void parseMockBeanAnnotation(MockBean annotation, AnnotatedElement element) {
|
||||
Set<ResolvableType> typesToMock = getOrDeduceTypes(element, annotation.value());
|
||||
Assert.state(!typesToMock.isEmpty(),
|
||||
() -> "Unable to deduce type to mock from " + element);
|
||||
Assert.state(!typesToMock.isEmpty(), () -> "Unable to deduce type to mock from " + element);
|
||||
if (StringUtils.hasLength(annotation.name())) {
|
||||
Assert.state(typesToMock.size() == 1,
|
||||
"The name attribute can only be used when mocking a single class");
|
||||
Assert.state(typesToMock.size() == 1, "The name attribute can only be used when mocking a single class");
|
||||
}
|
||||
for (ResolvableType typeToMock : typesToMock) {
|
||||
MockDefinition definition = new MockDefinition(annotation.name(), typeToMock,
|
||||
annotation.extraInterfaces(), annotation.answer(),
|
||||
annotation.serializable(), annotation.reset(),
|
||||
MockDefinition definition = new MockDefinition(annotation.name(), typeToMock, annotation.extraInterfaces(),
|
||||
annotation.answer(), annotation.serializable(), annotation.reset(),
|
||||
QualifierDefinition.forElement(element));
|
||||
addDefinition(element, definition, "mock");
|
||||
}
|
||||
@@ -92,33 +87,27 @@ class DefinitionsParser {
|
||||
|
||||
private void parseSpyBeanAnnotation(SpyBean annotation, AnnotatedElement element) {
|
||||
Set<ResolvableType> typesToSpy = getOrDeduceTypes(element, annotation.value());
|
||||
Assert.state(!typesToSpy.isEmpty(),
|
||||
() -> "Unable to deduce type to spy from " + element);
|
||||
Assert.state(!typesToSpy.isEmpty(), () -> "Unable to deduce type to spy from " + element);
|
||||
if (StringUtils.hasLength(annotation.name())) {
|
||||
Assert.state(typesToSpy.size() == 1,
|
||||
"The name attribute can only be used when spying a single class");
|
||||
Assert.state(typesToSpy.size() == 1, "The name attribute can only be used when spying a single class");
|
||||
}
|
||||
for (ResolvableType typeToSpy : typesToSpy) {
|
||||
SpyDefinition definition = new SpyDefinition(annotation.name(), typeToSpy,
|
||||
annotation.reset(), annotation.proxyTargetAware(),
|
||||
QualifierDefinition.forElement(element));
|
||||
SpyDefinition definition = new SpyDefinition(annotation.name(), typeToSpy, annotation.reset(),
|
||||
annotation.proxyTargetAware(), QualifierDefinition.forElement(element));
|
||||
addDefinition(element, definition, "spy");
|
||||
}
|
||||
}
|
||||
|
||||
private void addDefinition(AnnotatedElement element, Definition definition,
|
||||
String type) {
|
||||
private void addDefinition(AnnotatedElement element, Definition definition, String type) {
|
||||
boolean isNewDefinition = this.definitions.add(definition);
|
||||
Assert.state(isNewDefinition,
|
||||
() -> "Duplicate " + type + " definition " + definition);
|
||||
Assert.state(isNewDefinition, () -> "Duplicate " + type + " definition " + definition);
|
||||
if (element instanceof Field) {
|
||||
Field field = (Field) element;
|
||||
this.definitionFields.put(definition, field);
|
||||
}
|
||||
}
|
||||
|
||||
private Set<ResolvableType> getOrDeduceTypes(AnnotatedElement element,
|
||||
Class<?>[] value) {
|
||||
private Set<ResolvableType> getOrDeduceTypes(AnnotatedElement element, Class<?>[] value) {
|
||||
Set<ResolvableType> types = new LinkedHashSet<>();
|
||||
for (Class<?> clazz : value) {
|
||||
types.add(ResolvableType.forClass(clazz));
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2012-2018 the original author or authors.
|
||||
* Copyright 2012-2019 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -76,16 +76,14 @@ import org.springframework.util.StringUtils;
|
||||
* @since 1.4.0
|
||||
*/
|
||||
public class MockitoPostProcessor extends InstantiationAwareBeanPostProcessorAdapter
|
||||
implements BeanClassLoaderAware, BeanFactoryAware, BeanFactoryPostProcessor,
|
||||
Ordered {
|
||||
implements BeanClassLoaderAware, BeanFactoryAware, BeanFactoryPostProcessor, Ordered {
|
||||
|
||||
private static final String FACTORY_BEAN_OBJECT_TYPE = "factoryBeanObjectType";
|
||||
|
||||
private static final String BEAN_NAME = MockitoPostProcessor.class.getName();
|
||||
|
||||
private static final String CONFIGURATION_CLASS_ATTRIBUTE = Conventions
|
||||
.getQualifiedAttributeName(ConfigurationClassPostProcessor.class,
|
||||
"configurationClass");
|
||||
.getQualifiedAttributeName(ConfigurationClassPostProcessor.class, "configurationClass");
|
||||
|
||||
private static final BeanNameGenerator beanNameGenerator = new DefaultBeanNameGenerator();
|
||||
|
||||
@@ -125,16 +123,13 @@ public class MockitoPostProcessor extends InstantiationAwareBeanPostProcessorAda
|
||||
}
|
||||
|
||||
@Override
|
||||
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory)
|
||||
throws BeansException {
|
||||
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
|
||||
Assert.isInstanceOf(BeanDefinitionRegistry.class, beanFactory,
|
||||
"@MockBean can only be used on bean factories that "
|
||||
+ "implement BeanDefinitionRegistry");
|
||||
"@MockBean can only be used on bean factories that " + "implement BeanDefinitionRegistry");
|
||||
postProcessBeanFactory(beanFactory, (BeanDefinitionRegistry) beanFactory);
|
||||
}
|
||||
|
||||
private void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory,
|
||||
BeanDefinitionRegistry registry) {
|
||||
private void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory, BeanDefinitionRegistry registry) {
|
||||
beanFactory.registerSingleton(MockitoBeans.class.getName(), this.mockitoBeans);
|
||||
DefinitionsParser parser = new DefinitionsParser(this.definitions);
|
||||
for (Class<?> configurationClass : getConfigurationClasses(beanFactory)) {
|
||||
@@ -147,19 +142,15 @@ public class MockitoPostProcessor extends InstantiationAwareBeanPostProcessorAda
|
||||
}
|
||||
}
|
||||
|
||||
private Set<Class<?>> getConfigurationClasses(
|
||||
ConfigurableListableBeanFactory beanFactory) {
|
||||
private Set<Class<?>> getConfigurationClasses(ConfigurableListableBeanFactory beanFactory) {
|
||||
Set<Class<?>> configurationClasses = new LinkedHashSet<>();
|
||||
for (BeanDefinition beanDefinition : getConfigurationBeanDefinitions(beanFactory)
|
||||
.values()) {
|
||||
configurationClasses.add(ClassUtils.resolveClassName(
|
||||
beanDefinition.getBeanClassName(), this.classLoader));
|
||||
for (BeanDefinition beanDefinition : getConfigurationBeanDefinitions(beanFactory).values()) {
|
||||
configurationClasses.add(ClassUtils.resolveClassName(beanDefinition.getBeanClassName(), this.classLoader));
|
||||
}
|
||||
return configurationClasses;
|
||||
}
|
||||
|
||||
private Map<String, BeanDefinition> getConfigurationBeanDefinitions(
|
||||
ConfigurableListableBeanFactory beanFactory) {
|
||||
private Map<String, BeanDefinition> getConfigurationBeanDefinitions(ConfigurableListableBeanFactory beanFactory) {
|
||||
Map<String, BeanDefinition> definitions = new LinkedHashMap<>();
|
||||
for (String beanName : beanFactory.getBeanDefinitionNames()) {
|
||||
BeanDefinition definition = beanFactory.getBeanDefinition(beanName);
|
||||
@@ -170,8 +161,8 @@ public class MockitoPostProcessor extends InstantiationAwareBeanPostProcessorAda
|
||||
return definitions;
|
||||
}
|
||||
|
||||
private void register(ConfigurableListableBeanFactory beanFactory,
|
||||
BeanDefinitionRegistry registry, Definition definition, Field field) {
|
||||
private void register(ConfigurableListableBeanFactory beanFactory, BeanDefinitionRegistry registry,
|
||||
Definition definition, Field field) {
|
||||
if (definition instanceof MockDefinition) {
|
||||
registerMock(beanFactory, registry, (MockDefinition) definition, field);
|
||||
}
|
||||
@@ -180,8 +171,8 @@ public class MockitoPostProcessor extends InstantiationAwareBeanPostProcessorAda
|
||||
}
|
||||
}
|
||||
|
||||
private void registerMock(ConfigurableListableBeanFactory beanFactory,
|
||||
BeanDefinitionRegistry registry, MockDefinition definition, Field field) {
|
||||
private void registerMock(ConfigurableListableBeanFactory beanFactory, BeanDefinitionRegistry registry,
|
||||
MockDefinition definition, Field field) {
|
||||
RootBeanDefinition beanDefinition = createBeanDefinition(definition);
|
||||
String beanName = getBeanName(beanFactory, registry, definition, beanDefinition);
|
||||
String transformedBeanName = BeanFactoryUtils.transformedBeanName(beanName);
|
||||
@@ -201,8 +192,7 @@ public class MockitoPostProcessor extends InstantiationAwareBeanPostProcessorAda
|
||||
}
|
||||
|
||||
private RootBeanDefinition createBeanDefinition(MockDefinition mockDefinition) {
|
||||
RootBeanDefinition definition = new RootBeanDefinition(
|
||||
mockDefinition.getTypeToMock().resolve());
|
||||
RootBeanDefinition definition = new RootBeanDefinition(mockDefinition.getTypeToMock().resolve());
|
||||
definition.setTargetType(mockDefinition.getTypeToMock());
|
||||
if (mockDefinition.getQualifier() != null) {
|
||||
mockDefinition.getQualifier().applyTo(definition);
|
||||
@@ -210,40 +200,35 @@ public class MockitoPostProcessor extends InstantiationAwareBeanPostProcessorAda
|
||||
return definition;
|
||||
}
|
||||
|
||||
private String getBeanName(ConfigurableListableBeanFactory beanFactory,
|
||||
BeanDefinitionRegistry registry, MockDefinition mockDefinition,
|
||||
RootBeanDefinition beanDefinition) {
|
||||
private String getBeanName(ConfigurableListableBeanFactory beanFactory, BeanDefinitionRegistry registry,
|
||||
MockDefinition mockDefinition, RootBeanDefinition beanDefinition) {
|
||||
if (StringUtils.hasLength(mockDefinition.getName())) {
|
||||
return mockDefinition.getName();
|
||||
}
|
||||
Set<String> existingBeans = getExistingBeans(beanFactory,
|
||||
mockDefinition.getTypeToMock(), mockDefinition.getQualifier());
|
||||
Set<String> existingBeans = getExistingBeans(beanFactory, mockDefinition.getTypeToMock(),
|
||||
mockDefinition.getQualifier());
|
||||
if (existingBeans.isEmpty()) {
|
||||
return MockitoPostProcessor.beanNameGenerator.generateBeanName(beanDefinition,
|
||||
registry);
|
||||
return MockitoPostProcessor.beanNameGenerator.generateBeanName(beanDefinition, registry);
|
||||
}
|
||||
if (existingBeans.size() == 1) {
|
||||
return existingBeans.iterator().next();
|
||||
}
|
||||
String primaryCandidate = determinePrimaryCandidate(registry, existingBeans,
|
||||
mockDefinition.getTypeToMock());
|
||||
String primaryCandidate = determinePrimaryCandidate(registry, existingBeans, mockDefinition.getTypeToMock());
|
||||
if (primaryCandidate != null) {
|
||||
return primaryCandidate;
|
||||
}
|
||||
throw new IllegalStateException(
|
||||
"Unable to register mock bean " + mockDefinition.getTypeToMock()
|
||||
+ " expected a single matching bean to replace but found "
|
||||
+ existingBeans);
|
||||
throw new IllegalStateException("Unable to register mock bean " + mockDefinition.getTypeToMock()
|
||||
+ " expected a single matching bean to replace but found " + existingBeans);
|
||||
}
|
||||
|
||||
private void copyBeanDefinitionDetails(BeanDefinition from, RootBeanDefinition to) {
|
||||
to.setPrimary(from.isPrimary());
|
||||
}
|
||||
|
||||
private void registerSpy(ConfigurableListableBeanFactory beanFactory,
|
||||
BeanDefinitionRegistry registry, SpyDefinition spyDefinition, Field field) {
|
||||
Set<String> existingBeans = getExistingBeans(beanFactory,
|
||||
spyDefinition.getTypeToSpy(), spyDefinition.getQualifier());
|
||||
private void registerSpy(ConfigurableListableBeanFactory beanFactory, BeanDefinitionRegistry registry,
|
||||
SpyDefinition spyDefinition, Field field) {
|
||||
Set<String> existingBeans = getExistingBeans(beanFactory, spyDefinition.getTypeToSpy(),
|
||||
spyDefinition.getQualifier());
|
||||
if (ObjectUtils.isEmpty(existingBeans)) {
|
||||
createSpy(registry, spyDefinition, field);
|
||||
}
|
||||
@@ -252,8 +237,8 @@ public class MockitoPostProcessor extends InstantiationAwareBeanPostProcessorAda
|
||||
}
|
||||
}
|
||||
|
||||
private Set<String> getExistingBeans(ConfigurableListableBeanFactory beanFactory,
|
||||
ResolvableType type, QualifierDefinition qualifier) {
|
||||
private Set<String> getExistingBeans(ConfigurableListableBeanFactory beanFactory, ResolvableType type,
|
||||
QualifierDefinition qualifier) {
|
||||
Set<String> candidates = new TreeSet<>();
|
||||
for (String candidate : getExistingBeans(beanFactory, type)) {
|
||||
if (qualifier == null || qualifier.matches(beanFactory, candidate)) {
|
||||
@@ -263,10 +248,8 @@ public class MockitoPostProcessor extends InstantiationAwareBeanPostProcessorAda
|
||||
return candidates;
|
||||
}
|
||||
|
||||
private Set<String> getExistingBeans(ConfigurableListableBeanFactory beanFactory,
|
||||
ResolvableType type) {
|
||||
Set<String> beans = new LinkedHashSet<>(
|
||||
Arrays.asList(beanFactory.getBeanNamesForType(type)));
|
||||
private Set<String> getExistingBeans(ConfigurableListableBeanFactory beanFactory, ResolvableType type) {
|
||||
Set<String> beans = new LinkedHashSet<>(Arrays.asList(beanFactory.getBeanNamesForType(type)));
|
||||
String typeName = type.resolve(Object.class).getName();
|
||||
for (String beanName : beanFactory.getBeanNamesForType(FactoryBean.class)) {
|
||||
beanName = BeanFactoryUtils.transformedBeanName(beanName);
|
||||
@@ -288,49 +271,43 @@ public class MockitoPostProcessor extends InstantiationAwareBeanPostProcessorAda
|
||||
}
|
||||
}
|
||||
|
||||
private void createSpy(BeanDefinitionRegistry registry, SpyDefinition spyDefinition,
|
||||
Field field) {
|
||||
RootBeanDefinition beanDefinition = new RootBeanDefinition(
|
||||
spyDefinition.getTypeToSpy().resolve());
|
||||
String beanName = MockitoPostProcessor.beanNameGenerator
|
||||
.generateBeanName(beanDefinition, registry);
|
||||
private void createSpy(BeanDefinitionRegistry registry, SpyDefinition spyDefinition, Field field) {
|
||||
RootBeanDefinition beanDefinition = new RootBeanDefinition(spyDefinition.getTypeToSpy().resolve());
|
||||
String beanName = MockitoPostProcessor.beanNameGenerator.generateBeanName(beanDefinition, registry);
|
||||
registry.registerBeanDefinition(beanName, beanDefinition);
|
||||
registerSpy(spyDefinition, field, beanName);
|
||||
}
|
||||
|
||||
private void registerSpies(BeanDefinitionRegistry registry,
|
||||
SpyDefinition spyDefinition, Field field, Collection<String> existingBeans) {
|
||||
private void registerSpies(BeanDefinitionRegistry registry, SpyDefinition spyDefinition, Field field,
|
||||
Collection<String> existingBeans) {
|
||||
try {
|
||||
String beanName = determineBeanName(existingBeans, spyDefinition, registry);
|
||||
registerSpy(spyDefinition, field, beanName);
|
||||
}
|
||||
catch (RuntimeException ex) {
|
||||
throw new IllegalStateException(
|
||||
"Unable to register spy bean " + spyDefinition.getTypeToSpy(), ex);
|
||||
throw new IllegalStateException("Unable to register spy bean " + spyDefinition.getTypeToSpy(), ex);
|
||||
}
|
||||
}
|
||||
|
||||
private String determineBeanName(Collection<String> existingBeans,
|
||||
SpyDefinition definition, BeanDefinitionRegistry registry) {
|
||||
private String determineBeanName(Collection<String> existingBeans, SpyDefinition definition,
|
||||
BeanDefinitionRegistry registry) {
|
||||
if (StringUtils.hasText(definition.getName())) {
|
||||
return definition.getName();
|
||||
}
|
||||
if (existingBeans.size() == 1) {
|
||||
return existingBeans.iterator().next();
|
||||
}
|
||||
return determinePrimaryCandidate(registry, existingBeans,
|
||||
definition.getTypeToSpy());
|
||||
return determinePrimaryCandidate(registry, existingBeans, definition.getTypeToSpy());
|
||||
}
|
||||
|
||||
private String determinePrimaryCandidate(BeanDefinitionRegistry registry,
|
||||
Collection<String> candidateBeanNames, ResolvableType type) {
|
||||
private String determinePrimaryCandidate(BeanDefinitionRegistry registry, Collection<String> candidateBeanNames,
|
||||
ResolvableType type) {
|
||||
String primaryBeanName = null;
|
||||
for (String candidateBeanName : candidateBeanNames) {
|
||||
BeanDefinition beanDefinition = registry.getBeanDefinition(candidateBeanName);
|
||||
if (beanDefinition.isPrimary()) {
|
||||
if (primaryBeanName != null) {
|
||||
throw new NoUniqueBeanDefinitionException(type.resolve(),
|
||||
candidateBeanNames.size(),
|
||||
throw new NoUniqueBeanDefinitionException(type.resolve(), candidateBeanNames.size(),
|
||||
"more than one 'primary' bean found among candidates: "
|
||||
+ Arrays.asList(candidateBeanNames));
|
||||
}
|
||||
@@ -348,8 +325,7 @@ public class MockitoPostProcessor extends InstantiationAwareBeanPostProcessorAda
|
||||
}
|
||||
}
|
||||
|
||||
protected final Object createSpyIfNecessary(Object bean, String beanName)
|
||||
throws BeansException {
|
||||
protected final Object createSpyIfNecessary(Object bean, String beanName) throws BeansException {
|
||||
SpyDefinition definition = this.spies.get(beanName);
|
||||
if (definition != null) {
|
||||
bean = definition.createSpy(beanName, bean);
|
||||
@@ -358,11 +334,9 @@ public class MockitoPostProcessor extends InstantiationAwareBeanPostProcessorAda
|
||||
}
|
||||
|
||||
@Override
|
||||
public PropertyValues postProcessPropertyValues(PropertyValues pvs,
|
||||
PropertyDescriptor[] pds, final Object bean, String beanName)
|
||||
throws BeansException {
|
||||
ReflectionUtils.doWithFields(bean.getClass(),
|
||||
(field) -> postProcessField(bean, field));
|
||||
public PropertyValues postProcessPropertyValues(PropertyValues pvs, PropertyDescriptor[] pds, final Object bean,
|
||||
String beanName) throws BeansException {
|
||||
ReflectionUtils.doWithFields(bean.getClass(), (field) -> postProcessField(bean, field));
|
||||
return pvs;
|
||||
}
|
||||
|
||||
@@ -375,8 +349,7 @@ public class MockitoPostProcessor extends InstantiationAwareBeanPostProcessorAda
|
||||
|
||||
void inject(Field field, Object target, Definition definition) {
|
||||
String beanName = this.beanNameRegistry.get(definition);
|
||||
Assert.state(StringUtils.hasLength(beanName),
|
||||
() -> "No bean found for definition " + definition);
|
||||
Assert.state(StringUtils.hasLength(beanName), () -> "No bean found for definition " + definition);
|
||||
inject(field, target, beanName);
|
||||
}
|
||||
|
||||
@@ -413,8 +386,7 @@ public class MockitoPostProcessor extends InstantiationAwareBeanPostProcessorAda
|
||||
* @param registry the bean definition registry
|
||||
* @param definitions the initial mock/spy definitions
|
||||
*/
|
||||
public static void register(BeanDefinitionRegistry registry,
|
||||
Set<Definition> definitions) {
|
||||
public static void register(BeanDefinitionRegistry registry, Set<Definition> definitions) {
|
||||
register(registry, MockitoPostProcessor.class, definitions);
|
||||
}
|
||||
|
||||
@@ -426,13 +398,11 @@ public class MockitoPostProcessor extends InstantiationAwareBeanPostProcessorAda
|
||||
* @param definitions the initial mock/spy definitions
|
||||
*/
|
||||
@SuppressWarnings("unchecked")
|
||||
public static void register(BeanDefinitionRegistry registry,
|
||||
Class<? extends MockitoPostProcessor> postProcessor,
|
||||
public static void register(BeanDefinitionRegistry registry, Class<? extends MockitoPostProcessor> postProcessor,
|
||||
Set<Definition> definitions) {
|
||||
SpyPostProcessor.register(registry);
|
||||
BeanDefinition definition = getOrAddBeanDefinition(registry, postProcessor);
|
||||
ValueHolder constructorArg = definition.getConstructorArgumentValues()
|
||||
.getIndexedArgumentValue(0, Set.class);
|
||||
ValueHolder constructorArg = definition.getConstructorArgumentValues().getIndexedArgumentValue(0, Set.class);
|
||||
Set<Definition> existing = (Set<Definition>) constructorArg.getValue();
|
||||
if (definitions != null) {
|
||||
existing.addAll(definitions);
|
||||
@@ -444,10 +414,8 @@ public class MockitoPostProcessor extends InstantiationAwareBeanPostProcessorAda
|
||||
if (!registry.containsBeanDefinition(BEAN_NAME)) {
|
||||
RootBeanDefinition definition = new RootBeanDefinition(postProcessor);
|
||||
definition.setRole(BeanDefinition.ROLE_INFRASTRUCTURE);
|
||||
ConstructorArgumentValues constructorArguments = definition
|
||||
.getConstructorArgumentValues();
|
||||
constructorArguments.addIndexedArgumentValue(0,
|
||||
new LinkedHashSet<MockDefinition>());
|
||||
ConstructorArgumentValues constructorArguments = definition.getConstructorArgumentValues();
|
||||
constructorArguments.addIndexedArgumentValue(0, new LinkedHashSet<MockDefinition>());
|
||||
registry.registerBeanDefinition(BEAN_NAME, definition);
|
||||
return definition;
|
||||
}
|
||||
@@ -458,8 +426,7 @@ public class MockitoPostProcessor extends InstantiationAwareBeanPostProcessorAda
|
||||
* {@link BeanPostProcessor} to handle {@link SpyBean} definitions. Registered as a
|
||||
* separate processor so that it can be ordered above AOP post processors.
|
||||
*/
|
||||
static class SpyPostProcessor extends InstantiationAwareBeanPostProcessorAdapter
|
||||
implements PriorityOrdered {
|
||||
static class SpyPostProcessor extends InstantiationAwareBeanPostProcessorAdapter implements PriorityOrdered {
|
||||
|
||||
private static final String BEAN_NAME = SpyPostProcessor.class.getName();
|
||||
|
||||
@@ -475,14 +442,12 @@ public class MockitoPostProcessor extends InstantiationAwareBeanPostProcessorAda
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object getEarlyBeanReference(Object bean, String beanName)
|
||||
throws BeansException {
|
||||
public Object getEarlyBeanReference(Object bean, String beanName) throws BeansException {
|
||||
return this.mockitoPostProcessor.createSpyIfNecessary(bean, beanName);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object postProcessAfterInitialization(Object bean, String beanName)
|
||||
throws BeansException {
|
||||
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
|
||||
if (bean instanceof FactoryBean) {
|
||||
return bean;
|
||||
}
|
||||
@@ -491,11 +456,9 @@ public class MockitoPostProcessor extends InstantiationAwareBeanPostProcessorAda
|
||||
|
||||
public static void register(BeanDefinitionRegistry registry) {
|
||||
if (!registry.containsBeanDefinition(BEAN_NAME)) {
|
||||
RootBeanDefinition definition = new RootBeanDefinition(
|
||||
SpyPostProcessor.class);
|
||||
RootBeanDefinition definition = new RootBeanDefinition(SpyPostProcessor.class);
|
||||
definition.setRole(BeanDefinition.ROLE_INFRASTRUCTURE);
|
||||
ConstructorArgumentValues constructorArguments = definition
|
||||
.getConstructorArgumentValues();
|
||||
ConstructorArgumentValues constructorArguments = definition.getConstructorArgumentValues();
|
||||
constructorArguments.addIndexedArgumentValue(0,
|
||||
new RuntimeBeanReference(MockitoPostProcessor.BEAN_NAME));
|
||||
registry.registerBeanDefinition(BEAN_NAME, definition);
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2012-2018 the original author or authors.
|
||||
* Copyright 2012-2019 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -56,8 +56,8 @@ public class MockitoTestExecutionListener extends AbstractTestExecutionListener
|
||||
|
||||
@Override
|
||||
public void beforeTestMethod(TestContext testContext) throws Exception {
|
||||
if (Boolean.TRUE.equals(testContext.getAttribute(
|
||||
DependencyInjectionTestExecutionListener.REINJECT_DEPENDENCIES_ATTRIBUTE))) {
|
||||
if (Boolean.TRUE.equals(
|
||||
testContext.getAttribute(DependencyInjectionTestExecutionListener.REINJECT_DEPENDENCIES_ATTRIBUTE))) {
|
||||
initMocks(testContext);
|
||||
reinjectFields(testContext);
|
||||
}
|
||||
@@ -76,23 +76,19 @@ public class MockitoTestExecutionListener extends AbstractTestExecutionListener
|
||||
}
|
||||
|
||||
private void injectFields(TestContext testContext) {
|
||||
postProcessFields(testContext,
|
||||
(mockitoField, postProcessor) -> postProcessor.inject(mockitoField.field,
|
||||
mockitoField.target, mockitoField.definition));
|
||||
postProcessFields(testContext, (mockitoField, postProcessor) -> postProcessor.inject(mockitoField.field,
|
||||
mockitoField.target, mockitoField.definition));
|
||||
}
|
||||
|
||||
private void reinjectFields(final TestContext testContext) {
|
||||
postProcessFields(testContext, (mockitoField, postProcessor) -> {
|
||||
ReflectionUtils.makeAccessible(mockitoField.field);
|
||||
ReflectionUtils.setField(mockitoField.field, testContext.getTestInstance(),
|
||||
null);
|
||||
postProcessor.inject(mockitoField.field, mockitoField.target,
|
||||
mockitoField.definition);
|
||||
ReflectionUtils.setField(mockitoField.field, testContext.getTestInstance(), null);
|
||||
postProcessor.inject(mockitoField.field, mockitoField.target, mockitoField.definition);
|
||||
});
|
||||
}
|
||||
|
||||
private void postProcessFields(TestContext testContext,
|
||||
BiConsumer<MockitoField, MockitoPostProcessor> consumer) {
|
||||
private void postProcessFields(TestContext testContext, BiConsumer<MockitoField, MockitoPostProcessor> consumer) {
|
||||
DefinitionsParser parser = new DefinitionsParser();
|
||||
parser.parse(testContext.getTestClass());
|
||||
if (!parser.getDefinitions().isEmpty()) {
|
||||
@@ -101,8 +97,7 @@ public class MockitoTestExecutionListener extends AbstractTestExecutionListener
|
||||
for (Definition definition : parser.getDefinitions()) {
|
||||
Field field = parser.getField(definition);
|
||||
if (field != null) {
|
||||
consumer.accept(new MockitoField(field, testContext.getTestInstance(),
|
||||
definition), postProcessor);
|
||||
consumer.accept(new MockitoField(field, testContext.getTestInstance(), definition), postProcessor);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -116,8 +111,7 @@ public class MockitoTestExecutionListener extends AbstractTestExecutionListener
|
||||
private final Set<Annotation> annotations = new LinkedHashSet<>();
|
||||
|
||||
@Override
|
||||
public void doWith(Field field)
|
||||
throws IllegalArgumentException, IllegalAccessException {
|
||||
public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException {
|
||||
for (Annotation annotation : field.getDeclaredAnnotations()) {
|
||||
if (annotation.annotationType().getName().startsWith("org.mockito")) {
|
||||
this.annotations.add(annotation);
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
|
||||
|
||||
@@ -118,8 +118,7 @@ public class TestRestTemplate {
|
||||
* @param password the password (or {@code null})
|
||||
* @param httpClientOptions client options to use if the Apache HTTP Client is used
|
||||
*/
|
||||
public TestRestTemplate(String username, String password,
|
||||
HttpClientOption... httpClientOptions) {
|
||||
public TestRestTemplate(String username, String password, HttpClientOption... httpClientOptions) {
|
||||
this(new RestTemplateBuilder(), username, password, httpClientOptions);
|
||||
}
|
||||
|
||||
@@ -132,42 +131,34 @@ public class TestRestTemplate {
|
||||
* @param httpClientOptions client options to use if the Apache HTTP Client is used
|
||||
* @since 2.0.0
|
||||
*/
|
||||
public TestRestTemplate(RestTemplateBuilder restTemplateBuilder, String username,
|
||||
String password, HttpClientOption... httpClientOptions) {
|
||||
this((restTemplateBuilder != null) ? restTemplateBuilder.build() : null, username,
|
||||
password, httpClientOptions);
|
||||
public TestRestTemplate(RestTemplateBuilder restTemplateBuilder, String username, String password,
|
||||
HttpClientOption... httpClientOptions) {
|
||||
this((restTemplateBuilder != null) ? restTemplateBuilder.build() : null, username, password, httpClientOptions);
|
||||
}
|
||||
|
||||
private TestRestTemplate(RestTemplate restTemplate, String username, String password,
|
||||
HttpClientOption... httpClientOptions) {
|
||||
Assert.notNull(restTemplate, "RestTemplate must not be null");
|
||||
this.httpClientOptions = httpClientOptions;
|
||||
if (getRequestFactoryClass(restTemplate)
|
||||
.isAssignableFrom(HttpComponentsClientHttpRequestFactory.class)) {
|
||||
restTemplate.setRequestFactory(
|
||||
new CustomHttpComponentsClientHttpRequestFactory(httpClientOptions));
|
||||
if (getRequestFactoryClass(restTemplate).isAssignableFrom(HttpComponentsClientHttpRequestFactory.class)) {
|
||||
restTemplate.setRequestFactory(new CustomHttpComponentsClientHttpRequestFactory(httpClientOptions));
|
||||
}
|
||||
addAuthentication(restTemplate, username, password);
|
||||
restTemplate.setErrorHandler(new NoOpResponseErrorHandler());
|
||||
this.restTemplate = restTemplate;
|
||||
}
|
||||
|
||||
private Class<? extends ClientHttpRequestFactory> getRequestFactoryClass(
|
||||
RestTemplate restTemplate) {
|
||||
private Class<? extends ClientHttpRequestFactory> getRequestFactoryClass(RestTemplate restTemplate) {
|
||||
ClientHttpRequestFactory requestFactory = restTemplate.getRequestFactory();
|
||||
if (InterceptingClientHttpRequestFactory.class
|
||||
.isAssignableFrom(requestFactory.getClass())) {
|
||||
Field requestFactoryField = ReflectionUtils.findField(RestTemplate.class,
|
||||
"requestFactory");
|
||||
if (InterceptingClientHttpRequestFactory.class.isAssignableFrom(requestFactory.getClass())) {
|
||||
Field requestFactoryField = ReflectionUtils.findField(RestTemplate.class, "requestFactory");
|
||||
ReflectionUtils.makeAccessible(requestFactoryField);
|
||||
requestFactory = (ClientHttpRequestFactory) ReflectionUtils
|
||||
.getField(requestFactoryField, restTemplate);
|
||||
requestFactory = (ClientHttpRequestFactory) ReflectionUtils.getField(requestFactoryField, restTemplate);
|
||||
}
|
||||
return requestFactory.getClass();
|
||||
}
|
||||
|
||||
private void addAuthentication(RestTemplate restTemplate, String username,
|
||||
String password) {
|
||||
private void addAuthentication(RestTemplate restTemplate, String username, String password) {
|
||||
if (username == null) {
|
||||
return;
|
||||
}
|
||||
@@ -219,8 +210,7 @@ public class TestRestTemplate {
|
||||
* @throws RestClientException on client-side HTTP error on client-side HTTP error
|
||||
* @see RestTemplate#getForObject(String, Class, Object...)
|
||||
*/
|
||||
public <T> T getForObject(String url, Class<T> responseType, Object... urlVariables)
|
||||
throws RestClientException {
|
||||
public <T> T getForObject(String url, Class<T> responseType, Object... urlVariables) throws RestClientException {
|
||||
return this.restTemplate.getForObject(url, responseType, urlVariables);
|
||||
}
|
||||
|
||||
@@ -237,8 +227,8 @@ public class TestRestTemplate {
|
||||
* @throws RestClientException on client-side HTTP error
|
||||
* @see RestTemplate#getForObject(String, Class, Object...)
|
||||
*/
|
||||
public <T> T getForObject(String url, Class<T> responseType,
|
||||
Map<String, ?> urlVariables) throws RestClientException {
|
||||
public <T> T getForObject(String url, Class<T> responseType, Map<String, ?> urlVariables)
|
||||
throws RestClientException {
|
||||
return this.restTemplate.getForObject(url, responseType, urlVariables);
|
||||
}
|
||||
|
||||
@@ -270,8 +260,8 @@ public class TestRestTemplate {
|
||||
* @see RestTemplate#getForEntity(java.lang.String, java.lang.Class,
|
||||
* java.lang.Object[])
|
||||
*/
|
||||
public <T> ResponseEntity<T> getForEntity(String url, Class<T> responseType,
|
||||
Object... urlVariables) throws RestClientException {
|
||||
public <T> ResponseEntity<T> getForEntity(String url, Class<T> responseType, Object... urlVariables)
|
||||
throws RestClientException {
|
||||
return this.restTemplate.getForEntity(url, responseType, urlVariables);
|
||||
}
|
||||
|
||||
@@ -288,8 +278,8 @@ public class TestRestTemplate {
|
||||
* @throws RestClientException on client-side HTTP error
|
||||
* @see RestTemplate#getForEntity(java.lang.String, java.lang.Class, java.util.Map)
|
||||
*/
|
||||
public <T> ResponseEntity<T> getForEntity(String url, Class<T> responseType,
|
||||
Map<String, ?> urlVariables) throws RestClientException {
|
||||
public <T> ResponseEntity<T> getForEntity(String url, Class<T> responseType, Map<String, ?> urlVariables)
|
||||
throws RestClientException {
|
||||
return this.restTemplate.getForEntity(url, responseType, urlVariables);
|
||||
}
|
||||
|
||||
@@ -303,8 +293,7 @@ public class TestRestTemplate {
|
||||
* @throws RestClientException on client-side HTTP error
|
||||
* @see RestTemplate#getForEntity(java.net.URI, java.lang.Class)
|
||||
*/
|
||||
public <T> ResponseEntity<T> getForEntity(URI url, Class<T> responseType)
|
||||
throws RestClientException {
|
||||
public <T> ResponseEntity<T> getForEntity(URI url, Class<T> responseType) throws RestClientException {
|
||||
return this.restTemplate.getForEntity(applyRootUriIfNecessary(url), responseType);
|
||||
}
|
||||
|
||||
@@ -318,8 +307,7 @@ public class TestRestTemplate {
|
||||
* @throws RestClientException on client-side HTTP error
|
||||
* @see RestTemplate#headForHeaders(java.lang.String, java.lang.Object[])
|
||||
*/
|
||||
public HttpHeaders headForHeaders(String url, Object... urlVariables)
|
||||
throws RestClientException {
|
||||
public HttpHeaders headForHeaders(String url, Object... urlVariables) throws RestClientException {
|
||||
return this.restTemplate.headForHeaders(url, urlVariables);
|
||||
}
|
||||
|
||||
@@ -333,8 +321,7 @@ public class TestRestTemplate {
|
||||
* @throws RestClientException on client-side HTTP error
|
||||
* @see RestTemplate#headForHeaders(java.lang.String, java.util.Map)
|
||||
*/
|
||||
public HttpHeaders headForHeaders(String url, Map<String, ?> urlVariables)
|
||||
throws RestClientException {
|
||||
public HttpHeaders headForHeaders(String url, Map<String, ?> urlVariables) throws RestClientException {
|
||||
return this.restTemplate.headForHeaders(url, urlVariables);
|
||||
}
|
||||
|
||||
@@ -367,8 +354,7 @@ public class TestRestTemplate {
|
||||
* @see RestTemplate#postForLocation(java.lang.String, java.lang.Object,
|
||||
* java.lang.Object[])
|
||||
*/
|
||||
public URI postForLocation(String url, Object request, Object... urlVariables)
|
||||
throws RestClientException {
|
||||
public URI postForLocation(String url, Object request, Object... urlVariables) throws RestClientException {
|
||||
return this.restTemplate.postForLocation(url, request, urlVariables);
|
||||
}
|
||||
|
||||
@@ -390,8 +376,7 @@ public class TestRestTemplate {
|
||||
* @see RestTemplate#postForLocation(java.lang.String, java.lang.Object,
|
||||
* java.util.Map)
|
||||
*/
|
||||
public URI postForLocation(String url, Object request, Map<String, ?> urlVariables)
|
||||
throws RestClientException {
|
||||
public URI postForLocation(String url, Object request, Map<String, ?> urlVariables) throws RestClientException {
|
||||
return this.restTemplate.postForLocation(url, request, urlVariables);
|
||||
}
|
||||
|
||||
@@ -432,8 +417,8 @@ public class TestRestTemplate {
|
||||
* @see RestTemplate#postForObject(java.lang.String, java.lang.Object,
|
||||
* java.lang.Class, java.lang.Object[])
|
||||
*/
|
||||
public <T> T postForObject(String url, Object request, Class<T> responseType,
|
||||
Object... urlVariables) throws RestClientException {
|
||||
public <T> T postForObject(String url, Object request, Class<T> responseType, Object... urlVariables)
|
||||
throws RestClientException {
|
||||
return this.restTemplate.postForObject(url, request, responseType, urlVariables);
|
||||
}
|
||||
|
||||
@@ -456,8 +441,8 @@ public class TestRestTemplate {
|
||||
* @see RestTemplate#postForObject(java.lang.String, java.lang.Object,
|
||||
* java.lang.Class, java.util.Map)
|
||||
*/
|
||||
public <T> T postForObject(String url, Object request, Class<T> responseType,
|
||||
Map<String, ?> urlVariables) throws RestClientException {
|
||||
public <T> T postForObject(String url, Object request, Class<T> responseType, Map<String, ?> urlVariables)
|
||||
throws RestClientException {
|
||||
return this.restTemplate.postForObject(url, request, responseType, urlVariables);
|
||||
}
|
||||
|
||||
@@ -476,10 +461,8 @@ public class TestRestTemplate {
|
||||
* @see HttpEntity
|
||||
* @see RestTemplate#postForObject(java.net.URI, java.lang.Object, java.lang.Class)
|
||||
*/
|
||||
public <T> T postForObject(URI url, Object request, Class<T> responseType)
|
||||
throws RestClientException {
|
||||
return this.restTemplate.postForObject(applyRootUriIfNecessary(url), request,
|
||||
responseType);
|
||||
public <T> T postForObject(URI url, Object request, Class<T> responseType) throws RestClientException {
|
||||
return this.restTemplate.postForObject(applyRootUriIfNecessary(url), request, responseType);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -501,8 +484,8 @@ public class TestRestTemplate {
|
||||
* @see RestTemplate#postForEntity(java.lang.String, java.lang.Object,
|
||||
* java.lang.Class, java.lang.Object[])
|
||||
*/
|
||||
public <T> ResponseEntity<T> postForEntity(String url, Object request,
|
||||
Class<T> responseType, Object... urlVariables) throws RestClientException {
|
||||
public <T> ResponseEntity<T> postForEntity(String url, Object request, Class<T> responseType,
|
||||
Object... urlVariables) throws RestClientException {
|
||||
return this.restTemplate.postForEntity(url, request, responseType, urlVariables);
|
||||
}
|
||||
|
||||
@@ -525,9 +508,8 @@ public class TestRestTemplate {
|
||||
* @see RestTemplate#postForEntity(java.lang.String, java.lang.Object,
|
||||
* java.lang.Class, java.util.Map)
|
||||
*/
|
||||
public <T> ResponseEntity<T> postForEntity(String url, Object request,
|
||||
Class<T> responseType, Map<String, ?> urlVariables)
|
||||
throws RestClientException {
|
||||
public <T> ResponseEntity<T> postForEntity(String url, Object request, Class<T> responseType,
|
||||
Map<String, ?> urlVariables) throws RestClientException {
|
||||
return this.restTemplate.postForEntity(url, request, responseType, urlVariables);
|
||||
}
|
||||
|
||||
@@ -546,10 +528,9 @@ public class TestRestTemplate {
|
||||
* @see HttpEntity
|
||||
* @see RestTemplate#postForEntity(java.net.URI, java.lang.Object, java.lang.Class)
|
||||
*/
|
||||
public <T> ResponseEntity<T> postForEntity(URI url, Object request,
|
||||
Class<T> responseType) throws RestClientException {
|
||||
return this.restTemplate.postForEntity(applyRootUriIfNecessary(url), request,
|
||||
responseType);
|
||||
public <T> ResponseEntity<T> postForEntity(URI url, Object request, Class<T> responseType)
|
||||
throws RestClientException {
|
||||
return this.restTemplate.postForEntity(applyRootUriIfNecessary(url), request, responseType);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -566,8 +547,7 @@ public class TestRestTemplate {
|
||||
* @see HttpEntity
|
||||
* @see RestTemplate#put(java.lang.String, java.lang.Object, java.lang.Object[])
|
||||
*/
|
||||
public void put(String url, Object request, Object... urlVariables)
|
||||
throws RestClientException {
|
||||
public void put(String url, Object request, Object... urlVariables) throws RestClientException {
|
||||
this.restTemplate.put(url, request, urlVariables);
|
||||
}
|
||||
|
||||
@@ -585,8 +565,7 @@ public class TestRestTemplate {
|
||||
* @see HttpEntity
|
||||
* @see RestTemplate#put(java.lang.String, java.lang.Object, java.util.Map)
|
||||
*/
|
||||
public void put(String url, Object request, Map<String, ?> urlVariables)
|
||||
throws RestClientException {
|
||||
public void put(String url, Object request, Map<String, ?> urlVariables) throws RestClientException {
|
||||
this.restTemplate.put(url, request, urlVariables);
|
||||
}
|
||||
|
||||
@@ -623,8 +602,8 @@ public class TestRestTemplate {
|
||||
* @since 1.4.4
|
||||
* @see HttpEntity
|
||||
*/
|
||||
public <T> T patchForObject(String url, Object request, Class<T> responseType,
|
||||
Object... uriVariables) throws RestClientException {
|
||||
public <T> T patchForObject(String url, Object request, Class<T> responseType, Object... uriVariables)
|
||||
throws RestClientException {
|
||||
return this.restTemplate.patchForObject(url, request, responseType, uriVariables);
|
||||
}
|
||||
|
||||
@@ -646,8 +625,8 @@ public class TestRestTemplate {
|
||||
* @since 1.4.4
|
||||
* @see HttpEntity
|
||||
*/
|
||||
public <T> T patchForObject(String url, Object request, Class<T> responseType,
|
||||
Map<String, ?> uriVariables) throws RestClientException {
|
||||
public <T> T patchForObject(String url, Object request, Class<T> responseType, Map<String, ?> uriVariables)
|
||||
throws RestClientException {
|
||||
return this.restTemplate.patchForObject(url, request, responseType, uriVariables);
|
||||
}
|
||||
|
||||
@@ -666,10 +645,8 @@ public class TestRestTemplate {
|
||||
* @since 1.4.4
|
||||
* @see HttpEntity
|
||||
*/
|
||||
public <T> T patchForObject(URI url, Object request, Class<T> responseType)
|
||||
throws RestClientException {
|
||||
return this.restTemplate.patchForObject(applyRootUriIfNecessary(url), request,
|
||||
responseType);
|
||||
public <T> T patchForObject(URI url, Object request, Class<T> responseType) throws RestClientException {
|
||||
return this.restTemplate.patchForObject(applyRootUriIfNecessary(url), request, responseType);
|
||||
|
||||
}
|
||||
|
||||
@@ -695,8 +672,7 @@ public class TestRestTemplate {
|
||||
* @throws RestClientException on client-side HTTP error
|
||||
* @see RestTemplate#delete(java.lang.String, java.util.Map)
|
||||
*/
|
||||
public void delete(String url, Map<String, ?> urlVariables)
|
||||
throws RestClientException {
|
||||
public void delete(String url, Map<String, ?> urlVariables) throws RestClientException {
|
||||
this.restTemplate.delete(url, urlVariables);
|
||||
}
|
||||
|
||||
@@ -720,8 +696,7 @@ public class TestRestTemplate {
|
||||
* @throws RestClientException on client-side HTTP error
|
||||
* @see RestTemplate#optionsForAllow(java.lang.String, java.lang.Object[])
|
||||
*/
|
||||
public Set<HttpMethod> optionsForAllow(String url, Object... urlVariables)
|
||||
throws RestClientException {
|
||||
public Set<HttpMethod> optionsForAllow(String url, Object... urlVariables) throws RestClientException {
|
||||
return this.restTemplate.optionsForAllow(url, urlVariables);
|
||||
}
|
||||
|
||||
@@ -735,8 +710,7 @@ public class TestRestTemplate {
|
||||
* @throws RestClientException on client-side HTTP error
|
||||
* @see RestTemplate#optionsForAllow(java.lang.String, java.util.Map)
|
||||
*/
|
||||
public Set<HttpMethod> optionsForAllow(String url, Map<String, ?> urlVariables)
|
||||
throws RestClientException {
|
||||
public Set<HttpMethod> optionsForAllow(String url, Map<String, ?> urlVariables) throws RestClientException {
|
||||
return this.restTemplate.optionsForAllow(url, urlVariables);
|
||||
}
|
||||
|
||||
@@ -768,11 +742,9 @@ public class TestRestTemplate {
|
||||
* @see RestTemplate#exchange(java.lang.String, org.springframework.http.HttpMethod,
|
||||
* org.springframework.http.HttpEntity, java.lang.Class, java.lang.Object[])
|
||||
*/
|
||||
public <T> ResponseEntity<T> exchange(String url, HttpMethod method,
|
||||
HttpEntity<?> requestEntity, Class<T> responseType, Object... urlVariables)
|
||||
throws RestClientException {
|
||||
return this.restTemplate.exchange(url, method, requestEntity, responseType,
|
||||
urlVariables);
|
||||
public <T> ResponseEntity<T> exchange(String url, HttpMethod method, HttpEntity<?> requestEntity,
|
||||
Class<T> responseType, Object... urlVariables) throws RestClientException {
|
||||
return this.restTemplate.exchange(url, method, requestEntity, responseType, urlVariables);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -792,11 +764,9 @@ public class TestRestTemplate {
|
||||
* @see RestTemplate#exchange(java.lang.String, org.springframework.http.HttpMethod,
|
||||
* org.springframework.http.HttpEntity, java.lang.Class, java.util.Map)
|
||||
*/
|
||||
public <T> ResponseEntity<T> exchange(String url, HttpMethod method,
|
||||
HttpEntity<?> requestEntity, Class<T> responseType,
|
||||
Map<String, ?> urlVariables) throws RestClientException {
|
||||
return this.restTemplate.exchange(url, method, requestEntity, responseType,
|
||||
urlVariables);
|
||||
public <T> ResponseEntity<T> exchange(String url, HttpMethod method, HttpEntity<?> requestEntity,
|
||||
Class<T> responseType, Map<String, ?> urlVariables) throws RestClientException {
|
||||
return this.restTemplate.exchange(url, method, requestEntity, responseType, urlVariables);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -813,11 +783,9 @@ public class TestRestTemplate {
|
||||
* @see RestTemplate#exchange(java.net.URI, org.springframework.http.HttpMethod,
|
||||
* org.springframework.http.HttpEntity, java.lang.Class)
|
||||
*/
|
||||
public <T> ResponseEntity<T> exchange(URI url, HttpMethod method,
|
||||
HttpEntity<?> requestEntity, Class<T> responseType)
|
||||
throws RestClientException {
|
||||
return this.restTemplate.exchange(applyRootUriIfNecessary(url), method,
|
||||
requestEntity, responseType);
|
||||
public <T> ResponseEntity<T> exchange(URI url, HttpMethod method, HttpEntity<?> requestEntity,
|
||||
Class<T> responseType) throws RestClientException {
|
||||
return this.restTemplate.exchange(applyRootUriIfNecessary(url), method, requestEntity, responseType);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -841,11 +809,9 @@ public class TestRestTemplate {
|
||||
* org.springframework.http.HttpEntity,
|
||||
* org.springframework.core.ParameterizedTypeReference, java.lang.Object[])
|
||||
*/
|
||||
public <T> ResponseEntity<T> exchange(String url, HttpMethod method,
|
||||
HttpEntity<?> requestEntity, ParameterizedTypeReference<T> responseType,
|
||||
Object... urlVariables) throws RestClientException {
|
||||
return this.restTemplate.exchange(url, method, requestEntity, responseType,
|
||||
urlVariables);
|
||||
public <T> ResponseEntity<T> exchange(String url, HttpMethod method, HttpEntity<?> requestEntity,
|
||||
ParameterizedTypeReference<T> responseType, Object... urlVariables) throws RestClientException {
|
||||
return this.restTemplate.exchange(url, method, requestEntity, responseType, urlVariables);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -869,11 +835,9 @@ public class TestRestTemplate {
|
||||
* org.springframework.http.HttpEntity,
|
||||
* org.springframework.core.ParameterizedTypeReference, java.util.Map)
|
||||
*/
|
||||
public <T> ResponseEntity<T> exchange(String url, HttpMethod method,
|
||||
HttpEntity<?> requestEntity, ParameterizedTypeReference<T> responseType,
|
||||
Map<String, ?> urlVariables) throws RestClientException {
|
||||
return this.restTemplate.exchange(url, method, requestEntity, responseType,
|
||||
urlVariables);
|
||||
public <T> ResponseEntity<T> exchange(String url, HttpMethod method, HttpEntity<?> requestEntity,
|
||||
ParameterizedTypeReference<T> responseType, Map<String, ?> urlVariables) throws RestClientException {
|
||||
return this.restTemplate.exchange(url, method, requestEntity, responseType, urlVariables);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -896,11 +860,9 @@ public class TestRestTemplate {
|
||||
* org.springframework.http.HttpEntity,
|
||||
* org.springframework.core.ParameterizedTypeReference)
|
||||
*/
|
||||
public <T> ResponseEntity<T> exchange(URI url, HttpMethod method,
|
||||
HttpEntity<?> requestEntity, ParameterizedTypeReference<T> responseType)
|
||||
throws RestClientException {
|
||||
return this.restTemplate.exchange(applyRootUriIfNecessary(url), method,
|
||||
requestEntity, responseType);
|
||||
public <T> ResponseEntity<T> exchange(URI url, HttpMethod method, HttpEntity<?> requestEntity,
|
||||
ParameterizedTypeReference<T> responseType) throws RestClientException {
|
||||
return this.restTemplate.exchange(applyRootUriIfNecessary(url), method, requestEntity, responseType);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -918,10 +880,9 @@ public class TestRestTemplate {
|
||||
* @throws RestClientException on client-side HTTP error
|
||||
* @see RestTemplate#exchange(org.springframework.http.RequestEntity, java.lang.Class)
|
||||
*/
|
||||
public <T> ResponseEntity<T> exchange(RequestEntity<?> requestEntity,
|
||||
Class<T> responseType) throws RestClientException {
|
||||
return this.restTemplate.exchange(
|
||||
createRequestEntityWithRootAppliedUri(requestEntity), responseType);
|
||||
public <T> ResponseEntity<T> exchange(RequestEntity<?> requestEntity, Class<T> responseType)
|
||||
throws RestClientException {
|
||||
return this.restTemplate.exchange(createRequestEntityWithRootAppliedUri(requestEntity), responseType);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -941,10 +902,9 @@ public class TestRestTemplate {
|
||||
* @see RestTemplate#exchange(org.springframework.http.RequestEntity,
|
||||
* org.springframework.core.ParameterizedTypeReference)
|
||||
*/
|
||||
public <T> ResponseEntity<T> exchange(RequestEntity<?> requestEntity,
|
||||
ParameterizedTypeReference<T> responseType) throws RestClientException {
|
||||
return this.restTemplate.exchange(
|
||||
createRequestEntityWithRootAppliedUri(requestEntity), responseType);
|
||||
public <T> ResponseEntity<T> exchange(RequestEntity<?> requestEntity, ParameterizedTypeReference<T> responseType)
|
||||
throws RestClientException {
|
||||
return this.restTemplate.exchange(createRequestEntityWithRootAppliedUri(requestEntity), responseType);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -965,10 +925,8 @@ public class TestRestTemplate {
|
||||
* org.springframework.web.client.ResponseExtractor, java.lang.Object[])
|
||||
*/
|
||||
public <T> T execute(String url, HttpMethod method, RequestCallback requestCallback,
|
||||
ResponseExtractor<T> responseExtractor, Object... urlVariables)
|
||||
throws RestClientException {
|
||||
return this.restTemplate.execute(url, method, requestCallback, responseExtractor,
|
||||
urlVariables);
|
||||
ResponseExtractor<T> responseExtractor, Object... urlVariables) throws RestClientException {
|
||||
return this.restTemplate.execute(url, method, requestCallback, responseExtractor, urlVariables);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -989,10 +947,8 @@ public class TestRestTemplate {
|
||||
* org.springframework.web.client.ResponseExtractor, java.util.Map)
|
||||
*/
|
||||
public <T> T execute(String url, HttpMethod method, RequestCallback requestCallback,
|
||||
ResponseExtractor<T> responseExtractor, Map<String, ?> urlVariables)
|
||||
throws RestClientException {
|
||||
return this.restTemplate.execute(url, method, requestCallback, responseExtractor,
|
||||
urlVariables);
|
||||
ResponseExtractor<T> responseExtractor, Map<String, ?> urlVariables) throws RestClientException {
|
||||
return this.restTemplate.execute(url, method, requestCallback, responseExtractor, urlVariables);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -1011,8 +967,7 @@ public class TestRestTemplate {
|
||||
*/
|
||||
public <T> T execute(URI url, HttpMethod method, RequestCallback requestCallback,
|
||||
ResponseExtractor<T> responseExtractor) throws RestClientException {
|
||||
return this.restTemplate.execute(applyRootUriIfNecessary(url), method,
|
||||
requestCallback, responseExtractor);
|
||||
return this.restTemplate.execute(applyRootUriIfNecessary(url), method, requestCallback, responseExtractor);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -1035,23 +990,20 @@ public class TestRestTemplate {
|
||||
* @since 1.4.1
|
||||
*/
|
||||
public TestRestTemplate withBasicAuth(String username, String password) {
|
||||
RestTemplate restTemplate = new RestTemplateBuilder()
|
||||
.requestFactory(getRequestFactorySupplier())
|
||||
RestTemplate restTemplate = new RestTemplateBuilder().requestFactory(getRequestFactorySupplier())
|
||||
.messageConverters(getRestTemplate().getMessageConverters())
|
||||
.interceptors(getRestTemplate().getInterceptors())
|
||||
.uriTemplateHandler(getRestTemplate().getUriTemplateHandler()).build();
|
||||
TestRestTemplate testRestTemplate = new TestRestTemplate(restTemplate, username,
|
||||
password, this.httpClientOptions);
|
||||
testRestTemplate.getRestTemplate()
|
||||
.setErrorHandler(getRestTemplate().getErrorHandler());
|
||||
TestRestTemplate testRestTemplate = new TestRestTemplate(restTemplate, username, password,
|
||||
this.httpClientOptions);
|
||||
testRestTemplate.getRestTemplate().setErrorHandler(getRestTemplate().getErrorHandler());
|
||||
return testRestTemplate;
|
||||
}
|
||||
|
||||
private Supplier<ClientHttpRequestFactory> getRequestFactorySupplier() {
|
||||
return () -> {
|
||||
try {
|
||||
return BeanUtils
|
||||
.instantiateClass(getRequestFactoryClass(getRestTemplate()));
|
||||
return BeanUtils.instantiateClass(getRequestFactoryClass(getRestTemplate()));
|
||||
}
|
||||
catch (BeanInstantiationException ex) {
|
||||
return new ClientHttpRequestFactorySupplier().get();
|
||||
@@ -1060,19 +1012,15 @@ public class TestRestTemplate {
|
||||
}
|
||||
|
||||
@SuppressWarnings({ "rawtypes", "unchecked" })
|
||||
private RequestEntity<?> createRequestEntityWithRootAppliedUri(
|
||||
RequestEntity<?> requestEntity) {
|
||||
return new RequestEntity(requestEntity.getBody(), requestEntity.getHeaders(),
|
||||
requestEntity.getMethod(),
|
||||
private RequestEntity<?> createRequestEntityWithRootAppliedUri(RequestEntity<?> requestEntity) {
|
||||
return new RequestEntity(requestEntity.getBody(), requestEntity.getHeaders(), requestEntity.getMethod(),
|
||||
applyRootUriIfNecessary(requestEntity.getUrl()), requestEntity.getType());
|
||||
}
|
||||
|
||||
private URI applyRootUriIfNecessary(URI uri) {
|
||||
UriTemplateHandler uriTemplateHandler = this.restTemplate.getUriTemplateHandler();
|
||||
if ((uriTemplateHandler instanceof RootUriTemplateHandler)
|
||||
&& uri.toString().startsWith("/")) {
|
||||
return URI.create(((RootUriTemplateHandler) uriTemplateHandler).getRootUri()
|
||||
+ uri.toString());
|
||||
if ((uriTemplateHandler instanceof RootUriTemplateHandler) && uri.toString().startsWith("/")) {
|
||||
return URI.create(((RootUriTemplateHandler) uriTemplateHandler).getRootUri() + uri.toString());
|
||||
}
|
||||
return uri;
|
||||
}
|
||||
@@ -1102,19 +1050,16 @@ public class TestRestTemplate {
|
||||
/**
|
||||
* {@link HttpComponentsClientHttpRequestFactory} to apply customizations.
|
||||
*/
|
||||
protected static class CustomHttpComponentsClientHttpRequestFactory
|
||||
extends HttpComponentsClientHttpRequestFactory {
|
||||
protected static class CustomHttpComponentsClientHttpRequestFactory extends HttpComponentsClientHttpRequestFactory {
|
||||
|
||||
private final String cookieSpec;
|
||||
|
||||
private final boolean enableRedirects;
|
||||
|
||||
public CustomHttpComponentsClientHttpRequestFactory(
|
||||
HttpClientOption[] httpClientOptions) {
|
||||
Set<HttpClientOption> options = new HashSet<>(
|
||||
Arrays.asList(httpClientOptions));
|
||||
this.cookieSpec = (options.contains(HttpClientOption.ENABLE_COOKIES)
|
||||
? CookieSpecs.STANDARD : CookieSpecs.IGNORE_COOKIES);
|
||||
public CustomHttpComponentsClientHttpRequestFactory(HttpClientOption[] httpClientOptions) {
|
||||
Set<HttpClientOption> options = new HashSet<>(Arrays.asList(httpClientOptions));
|
||||
this.cookieSpec = (options.contains(HttpClientOption.ENABLE_COOKIES) ? CookieSpecs.STANDARD
|
||||
: CookieSpecs.IGNORE_COOKIES);
|
||||
this.enableRedirects = options.contains(HttpClientOption.ENABLE_REDIRECTS);
|
||||
if (options.contains(HttpClientOption.SSL)) {
|
||||
setHttpClient(createSslHttpClient());
|
||||
@@ -1124,9 +1069,7 @@ public class TestRestTemplate {
|
||||
private HttpClient createSslHttpClient() {
|
||||
try {
|
||||
SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(
|
||||
new SSLContextBuilder()
|
||||
.loadTrustMaterial(null, new TrustSelfSignedStrategy())
|
||||
.build());
|
||||
new SSLContextBuilder().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build());
|
||||
return HttpClients.custom().setSSLSocketFactory(socketFactory).build();
|
||||
}
|
||||
catch (Exception ex) {
|
||||
@@ -1142,8 +1085,7 @@ public class TestRestTemplate {
|
||||
}
|
||||
|
||||
protected RequestConfig getRequestConfig() {
|
||||
Builder builder = RequestConfig.custom().setCookieSpec(this.cookieSpec)
|
||||
.setAuthenticationEnabled(false)
|
||||
Builder builder = RequestConfig.custom().setCookieSpec(this.cookieSpec).setAuthenticationEnabled(false)
|
||||
.setRedirectsEnabled(this.enableRedirects);
|
||||
return builder.build();
|
||||
}
|
||||
|
||||
@@ -52,8 +52,8 @@ class TestRestTemplateContextCustomizer implements ContextCustomizer {
|
||||
@Override
|
||||
public void customizeContext(ConfigurableApplicationContext context,
|
||||
MergedContextConfiguration mergedContextConfiguration) {
|
||||
SpringBootTest annotation = AnnotatedElementUtils.getMergedAnnotation(
|
||||
mergedContextConfiguration.getTestClass(), SpringBootTest.class);
|
||||
SpringBootTest annotation = AnnotatedElementUtils.getMergedAnnotation(mergedContextConfiguration.getTestClass(),
|
||||
SpringBootTest.class);
|
||||
if (annotation.webEnvironment().isEmbedded()) {
|
||||
registerTestRestTemplate(context);
|
||||
}
|
||||
@@ -67,11 +67,9 @@ class TestRestTemplateContextCustomizer implements ContextCustomizer {
|
||||
}
|
||||
|
||||
private void registerTestRestTemplate(BeanDefinitionRegistry registry) {
|
||||
RootBeanDefinition definition = new RootBeanDefinition(
|
||||
TestRestTemplateRegistrar.class);
|
||||
RootBeanDefinition definition = new RootBeanDefinition(TestRestTemplateRegistrar.class);
|
||||
definition.setRole(BeanDefinition.ROLE_INFRASTRUCTURE);
|
||||
registry.registerBeanDefinition(TestRestTemplateRegistrar.class.getName(),
|
||||
definition);
|
||||
registry.registerBeanDefinition(TestRestTemplateRegistrar.class.getName(), definition);
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -108,11 +106,9 @@ class TestRestTemplateContextCustomizer implements ContextCustomizer {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry)
|
||||
throws BeansException {
|
||||
if (BeanFactoryUtils.beanNamesForTypeIncludingAncestors(
|
||||
(ListableBeanFactory) this.beanFactory, TestRestTemplate.class, false,
|
||||
false).length == 0) {
|
||||
public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {
|
||||
if (BeanFactoryUtils.beanNamesForTypeIncludingAncestors((ListableBeanFactory) this.beanFactory,
|
||||
TestRestTemplate.class, false, false).length == 0) {
|
||||
registry.registerBeanDefinition(TestRestTemplate.class.getName(),
|
||||
new RootBeanDefinition(TestRestTemplateFactory.class));
|
||||
}
|
||||
@@ -120,8 +116,7 @@ class TestRestTemplateContextCustomizer implements ContextCustomizer {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory)
|
||||
throws BeansException {
|
||||
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
|
||||
}
|
||||
|
||||
}
|
||||
@@ -129,8 +124,7 @@ class TestRestTemplateContextCustomizer implements ContextCustomizer {
|
||||
/**
|
||||
* {@link FactoryBean} used to create and configure a {@link TestRestTemplate}.
|
||||
*/
|
||||
public static class TestRestTemplateFactory
|
||||
implements FactoryBean<TestRestTemplate>, ApplicationContextAware {
|
||||
public static class TestRestTemplateFactory implements FactoryBean<TestRestTemplate>, ApplicationContextAware {
|
||||
|
||||
private static final HttpClientOption[] DEFAULT_OPTIONS = {};
|
||||
|
||||
@@ -139,14 +133,13 @@ class TestRestTemplateContextCustomizer implements ContextCustomizer {
|
||||
private TestRestTemplate template;
|
||||
|
||||
@Override
|
||||
public void setApplicationContext(ApplicationContext applicationContext)
|
||||
throws BeansException {
|
||||
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
|
||||
RestTemplateBuilder builder = getRestTemplateBuilder(applicationContext);
|
||||
boolean sslEnabled = isSslEnabled(applicationContext);
|
||||
TestRestTemplate template = new TestRestTemplate(builder, null, null,
|
||||
sslEnabled ? SSL_OPTIONS : DEFAULT_OPTIONS);
|
||||
LocalHostUriTemplateHandler handler = new LocalHostUriTemplateHandler(
|
||||
applicationContext.getEnvironment(), sslEnabled ? "https" : "http");
|
||||
LocalHostUriTemplateHandler handler = new LocalHostUriTemplateHandler(applicationContext.getEnvironment(),
|
||||
sslEnabled ? "https" : "http");
|
||||
template.setUriTemplateHandler(handler);
|
||||
this.template = template;
|
||||
}
|
||||
@@ -155,16 +148,14 @@ class TestRestTemplateContextCustomizer implements ContextCustomizer {
|
||||
try {
|
||||
AbstractServletWebServerFactory webServerFactory = context
|
||||
.getBean(AbstractServletWebServerFactory.class);
|
||||
return webServerFactory.getSsl() != null
|
||||
&& webServerFactory.getSsl().isEnabled();
|
||||
return webServerFactory.getSsl() != null && webServerFactory.getSsl().isEnabled();
|
||||
}
|
||||
catch (NoSuchBeanDefinitionException ex) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private RestTemplateBuilder getRestTemplateBuilder(
|
||||
ApplicationContext applicationContext) {
|
||||
private RestTemplateBuilder getRestTemplateBuilder(ApplicationContext applicationContext) {
|
||||
try {
|
||||
return applicationContext.getBean(RestTemplateBuilder.class);
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2012-2018 the original author or authors.
|
||||
* Copyright 2012-2019 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -35,8 +35,7 @@ class TestRestTemplateContextCustomizerFactory implements ContextCustomizerFacto
|
||||
@Override
|
||||
public ContextCustomizer createContextCustomizer(Class<?> testClass,
|
||||
List<ContextConfigurationAttributes> configAttributes) {
|
||||
if (AnnotatedElementUtils.findMergedAnnotation(testClass,
|
||||
SpringBootTest.class) != null) {
|
||||
if (AnnotatedElementUtils.findMergedAnnotation(testClass, SpringBootTest.class) != null) {
|
||||
return new TestRestTemplateContextCustomizer();
|
||||
}
|
||||
return null;
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -53,10 +53,9 @@ import org.springframework.web.reactive.function.client.ExchangeStrategies;
|
||||
class WebTestClientContextCustomizer implements ContextCustomizer {
|
||||
|
||||
@Override
|
||||
public void customizeContext(ConfigurableApplicationContext context,
|
||||
MergedContextConfiguration mergedConfig) {
|
||||
SpringBootTest annotation = AnnotatedElementUtils
|
||||
.getMergedAnnotation(mergedConfig.getTestClass(), SpringBootTest.class);
|
||||
public void customizeContext(ConfigurableApplicationContext context, MergedContextConfiguration mergedConfig) {
|
||||
SpringBootTest annotation = AnnotatedElementUtils.getMergedAnnotation(mergedConfig.getTestClass(),
|
||||
SpringBootTest.class);
|
||||
if (annotation.webEnvironment().isEmbedded()) {
|
||||
registerWebTestClient(context);
|
||||
}
|
||||
@@ -70,11 +69,9 @@ class WebTestClientContextCustomizer implements ContextCustomizer {
|
||||
}
|
||||
|
||||
private void registerWebTestClient(BeanDefinitionRegistry registry) {
|
||||
RootBeanDefinition definition = new RootBeanDefinition(
|
||||
WebTestClientRegistrar.class);
|
||||
RootBeanDefinition definition = new RootBeanDefinition(WebTestClientRegistrar.class);
|
||||
definition.setRole(BeanDefinition.ROLE_INFRASTRUCTURE);
|
||||
registry.registerBeanDefinition(WebTestClientRegistrar.class.getName(),
|
||||
definition);
|
||||
registry.registerBeanDefinition(WebTestClientRegistrar.class.getName(), definition);
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -108,11 +105,9 @@ class WebTestClientContextCustomizer implements ContextCustomizer {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry)
|
||||
throws BeansException {
|
||||
if (BeanFactoryUtils.beanNamesForTypeIncludingAncestors(
|
||||
(ListableBeanFactory) this.beanFactory, WebTestClient.class, false,
|
||||
false).length == 0) {
|
||||
public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {
|
||||
if (BeanFactoryUtils.beanNamesForTypeIncludingAncestors((ListableBeanFactory) this.beanFactory,
|
||||
WebTestClient.class, false, false).length == 0) {
|
||||
registry.registerBeanDefinition(WebTestClient.class.getName(),
|
||||
new RootBeanDefinition(WebTestClientFactory.class));
|
||||
}
|
||||
@@ -120,8 +115,7 @@ class WebTestClientContextCustomizer implements ContextCustomizer {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory)
|
||||
throws BeansException {
|
||||
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
|
||||
}
|
||||
|
||||
}
|
||||
@@ -129,16 +123,14 @@ class WebTestClientContextCustomizer implements ContextCustomizer {
|
||||
/**
|
||||
* {@link FactoryBean} used to create and configure a {@link WebTestClient}.
|
||||
*/
|
||||
public static class WebTestClientFactory
|
||||
implements FactoryBean<WebTestClient>, ApplicationContextAware {
|
||||
public static class WebTestClientFactory implements FactoryBean<WebTestClient>, ApplicationContextAware {
|
||||
|
||||
private ApplicationContext applicationContext;
|
||||
|
||||
private WebTestClient object;
|
||||
|
||||
@Override
|
||||
public void setApplicationContext(ApplicationContext applicationContext)
|
||||
throws BeansException {
|
||||
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
|
||||
this.applicationContext = applicationContext;
|
||||
}
|
||||
|
||||
@@ -162,8 +154,7 @@ class WebTestClientContextCustomizer implements ContextCustomizer {
|
||||
|
||||
private WebTestClient createWebTestClient() {
|
||||
boolean sslEnabled = isSslEnabled(this.applicationContext);
|
||||
String port = this.applicationContext.getEnvironment()
|
||||
.getProperty("local.server.port", "8080");
|
||||
String port = this.applicationContext.getEnvironment().getProperty("local.server.port", "8080");
|
||||
String baseUrl = (sslEnabled ? "https" : "http") + "://localhost:" + port;
|
||||
WebTestClient.Builder builder = WebTestClient.bindToServer();
|
||||
customizeWebTestClientCodecs(builder, this.applicationContext);
|
||||
@@ -174,22 +165,18 @@ class WebTestClientContextCustomizer implements ContextCustomizer {
|
||||
try {
|
||||
AbstractReactiveWebServerFactory webServerFactory = context
|
||||
.getBean(AbstractReactiveWebServerFactory.class);
|
||||
return webServerFactory.getSsl() != null
|
||||
&& webServerFactory.getSsl().isEnabled();
|
||||
return webServerFactory.getSsl() != null && webServerFactory.getSsl().isEnabled();
|
||||
}
|
||||
catch (NoSuchBeanDefinitionException ex) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private void customizeWebTestClientCodecs(WebTestClient.Builder clientBuilder,
|
||||
ApplicationContext context) {
|
||||
Collection<CodecCustomizer> codecCustomizers = context
|
||||
.getBeansOfType(CodecCustomizer.class).values();
|
||||
private void customizeWebTestClientCodecs(WebTestClient.Builder clientBuilder, ApplicationContext context) {
|
||||
Collection<CodecCustomizer> codecCustomizers = context.getBeansOfType(CodecCustomizer.class).values();
|
||||
if (!CollectionUtils.isEmpty(codecCustomizers)) {
|
||||
clientBuilder.exchangeStrategies(ExchangeStrategies.builder()
|
||||
.codecs((codecs) -> codecCustomizers.forEach(
|
||||
(codecCustomizer) -> codecCustomizer.customize(codecs)))
|
||||
clientBuilder.exchangeStrategies(ExchangeStrategies.builder().codecs(
|
||||
(codecs) -> codecCustomizers.forEach((codecCustomizer) -> codecCustomizer.customize(codecs)))
|
||||
.build());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2012-2018 the original author or authors.
|
||||
* Copyright 2012-2019 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -37,8 +37,8 @@ class WebTestClientContextCustomizerFactory implements ContextCustomizerFactory
|
||||
@Override
|
||||
public ContextCustomizer createContextCustomizer(Class<?> testClass,
|
||||
List<ContextConfigurationAttributes> configAttributes) {
|
||||
if (isWebClientPresent() && AnnotatedElementUtils.findMergedAnnotation(testClass,
|
||||
SpringBootTest.class) != null) {
|
||||
if (isWebClientPresent()
|
||||
&& AnnotatedElementUtils.findMergedAnnotation(testClass, SpringBootTest.class) != null) {
|
||||
return new WebTestClientContextCustomizer();
|
||||
}
|
||||
return null;
|
||||
|
||||
@@ -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.
|
||||
@@ -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
|
||||
|
||||
@@ -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 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");
|
||||
}
|
||||
|
||||
@@ -88,8 +87,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 {
|
||||
|
||||
@@ -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,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 {
|
||||
|
||||
@@ -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.
|
||||
@@ -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) {
|
||||
|
||||
@@ -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.
|
||||
@@ -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
|
||||
|
||||
@@ -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.
|
||||
@@ -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) {
|
||||
|
||||
@@ -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.
|
||||
@@ -44,8 +44,7 @@ public class SpringBootTestActiveProfileTests {
|
||||
|
||||
@Test
|
||||
public void profiles() {
|
||||
assertThat(this.context.getEnvironment().getActiveProfiles())
|
||||
.containsExactly("override");
|
||||
assertThat(this.context.getEnvironment().getActiveProfiles()).containsExactly("override");
|
||||
}
|
||||
|
||||
@Configuration
|
||||
|
||||
@@ -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.
|
||||
@@ -33,8 +33,8 @@ import org.springframework.web.reactive.config.EnableWebFlux;
|
||||
*/
|
||||
@RunWith(SpringRunner.class)
|
||||
@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 {
|
||||
|
||||
|
||||
@@ -45,8 +45,7 @@ public class SpringBootTestReactiveWebEnvironmentUserDefinedTestRestTemplateTest
|
||||
|
||||
@Test
|
||||
public void restTemplateIsUserDefined() {
|
||||
assertThat(getContext().getBean("testRestTemplate"))
|
||||
.isInstanceOf(RestTemplate.class);
|
||||
assertThat(getContext().getBean("testRestTemplate")).isInstanceOf(RestTemplate.class);
|
||||
}
|
||||
|
||||
@Configuration
|
||||
|
||||
@@ -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.
|
||||
@@ -40,13 +40,11 @@ import static org.assertj.core.api.Assertions.assertThat;
|
||||
@RunWith(SpringRunner.class)
|
||||
@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
|
||||
|
||||
@@ -44,8 +44,7 @@ import static org.assertj.core.api.Assertions.assertThat;
|
||||
*/
|
||||
@RunWith(SpringRunner.class)
|
||||
@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 {
|
||||
|
||||
@@ -33,10 +33,8 @@ import org.springframework.web.servlet.config.annotation.EnableWebMvc;
|
||||
*/
|
||||
@RunWith(SpringRunner.class)
|
||||
@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
|
||||
@EnableWebMvc
|
||||
|
||||
@@ -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.
|
||||
@@ -77,8 +77,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
|
||||
|
||||
@@ -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 @@ public class SpringBootTestWebEnvironmentMockWithWebAppConfigurationTests {
|
||||
|
||||
@Test
|
||||
public void resourcePath() {
|
||||
assertThat(this.servletContext).hasFieldOrPropertyWithValue("resourceBasePath",
|
||||
"src/mymain/mywebapp");
|
||||
assertThat(this.servletContext).hasFieldOrPropertyWithValue("resourceBasePath", "src/mymain/mywebapp");
|
||||
}
|
||||
|
||||
@Configuration
|
||||
|
||||
@@ -38,8 +38,7 @@ import static org.assertj.core.api.Assertions.assertThat;
|
||||
*/
|
||||
@RunWith(SpringRunner.class)
|
||||
@DirtiesContext
|
||||
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT,
|
||||
properties = { "server.port=12345" })
|
||||
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, properties = { "server.port=12345" })
|
||||
public class SpringBootTestWebEnvironmentRandomPortCustomPortTests {
|
||||
|
||||
@Autowired
|
||||
|
||||
@@ -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.
|
||||
@@ -40,8 +40,7 @@ import static org.assertj.core.api.Assertions.assertThat;
|
||||
@RunWith(SpringRunner.class)
|
||||
@DirtiesContext
|
||||
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, properties = { "value=123" })
|
||||
public class SpringBootTestWebEnvironmentRandomPortTests
|
||||
extends AbstractSpringBootTestWebServerWebEnvironmentTests {
|
||||
public class SpringBootTestWebEnvironmentRandomPortTests extends AbstractSpringBootTestWebServerWebEnvironmentTests {
|
||||
|
||||
@Test
|
||||
public void testRestTemplateShouldUseBuilder() {
|
||||
@@ -56,8 +55,7 @@ public class SpringBootTestWebEnvironmentRandomPortTests
|
||||
|
||||
@Bean
|
||||
public RestTemplateBuilder restTemplateBuilder() {
|
||||
return new RestTemplateBuilder()
|
||||
.additionalMessageConverters(new MyConverter());
|
||||
return new RestTemplateBuilder().additionalMessageConverters(new MyConverter());
|
||||
|
||||
}
|
||||
|
||||
|
||||
@@ -38,8 +38,7 @@ import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
|
||||
@RunWith(SpringRunner.class)
|
||||
@DirtiesContext
|
||||
@SpringBootTest
|
||||
@ContextConfiguration(
|
||||
classes = SpringBootTestWithContextConfigurationIntegrationTests.Config.class)
|
||||
@ContextConfiguration(classes = SpringBootTestWithContextConfigurationIntegrationTests.Config.class)
|
||||
public class SpringBootTestWithContextConfigurationIntegrationTests {
|
||||
|
||||
@Autowired
|
||||
|
||||
@@ -39,11 +39,10 @@ import static org.assertj.core.api.Assertions.assertThat;
|
||||
*/
|
||||
@RunWith(SpringRunner.class)
|
||||
@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 {
|
||||
|
||||
@@ -73,14 +72,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
|
||||
|
||||
@@ -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.
|
||||
@@ -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,64 +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);
|
||||
assertThatIllegalStateException()
|
||||
.isThrownBy(() -> context.getSourceApplicationContext())
|
||||
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();
|
||||
@@ -178,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);
|
||||
@@ -187,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
|
||||
|
||||
@@ -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.
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
|
||||
@@ -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,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();
|
||||
}
|
||||
|
||||
|
||||
@@ -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.
|
||||
@@ -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(
|
||||
|
||||
@@ -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.
|
||||
@@ -41,61 +41,52 @@ 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();
|
||||
}
|
||||
|
||||
private MetadataReader getMetadataReader(Class<?> source) throws IOException {
|
||||
|
||||
@@ -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,62 +109,54 @@ 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 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"));
|
||||
}
|
||||
|
||||
|
||||
@@ -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.
|
||||
@@ -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
|
||||
|
||||
@@ -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 @@ 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);
|
||||
|
||||
@Rule
|
||||
public TemporaryFolder temp = new TemporaryFolder();
|
||||
@@ -94,15 +93,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");
|
||||
}
|
||||
|
||||
@@ -185,8 +183,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}.
|
||||
|
||||
@@ -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.
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
|
||||
@@ -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,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);
|
||||
}
|
||||
|
||||
@@ -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,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());
|
||||
|
||||
}
|
||||
|
||||
|
||||
@@ -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.
|
||||
@@ -57,8 +57,7 @@ public class JsonContentAssertTests {
|
||||
|
||||
private static final String SIMPSONS = loadJson("simpsons.json");
|
||||
|
||||
private static JSONComparator COMPARATOR = new DefaultComparator(
|
||||
JSONCompareMode.LENIENT);
|
||||
private static JSONComparator COMPARATOR = new DefaultComparator(JSONCompareMode.LENIENT);
|
||||
|
||||
@Rule
|
||||
public TemporaryFolder tempFolder = new TemporaryFolder();
|
||||
@@ -230,8 +229,7 @@ public class JsonContentAssertTests {
|
||||
|
||||
@Test(expected = AssertionError.class)
|
||||
public void isStrictlyEqualToJsonWhenResourcePathAndClassIsNotMatchingShouldFail() {
|
||||
assertThat(forJson(SOURCE)).isStrictlyEqualToJson("lenient-same.json",
|
||||
getClass());
|
||||
assertThat(forJson(SOURCE)).isStrictlyEqualToJson("lenient-same.json", getClass());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -261,8 +259,7 @@ public class JsonContentAssertTests {
|
||||
|
||||
@Test(expected = AssertionError.class)
|
||||
public void isStrictlyEqualToJsonWhenInputStreamIsNotMatchingShouldFail() {
|
||||
assertThat(forJson(SOURCE))
|
||||
.isStrictlyEqualToJson(createInputStream(LENIENT_SAME));
|
||||
assertThat(forJson(SOURCE)).isStrictlyEqualToJson(createInputStream(LENIENT_SAME));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -287,75 +284,62 @@ public class JsonContentAssertTests {
|
||||
|
||||
@Test
|
||||
public void isEqualToJsonWhenResourcePathIsMatchingAndLenientShouldPass() {
|
||||
assertThat(forJson(SOURCE)).isEqualToJson("lenient-same.json",
|
||||
JSONCompareMode.LENIENT);
|
||||
assertThat(forJson(SOURCE)).isEqualToJson("lenient-same.json", JSONCompareMode.LENIENT);
|
||||
}
|
||||
|
||||
@Test(expected = AssertionError.class)
|
||||
public void isEqualToJsonWhenResourcePathIsNotMatchingAndLenientShouldFail() {
|
||||
assertThat(forJson(SOURCE)).isEqualToJson("different.json",
|
||||
JSONCompareMode.LENIENT);
|
||||
assertThat(forJson(SOURCE)).isEqualToJson("different.json", JSONCompareMode.LENIENT);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void isEqualToJsonWhenResourcePathAndClassIsMatchingAndLenientShouldPass() {
|
||||
assertThat(forJson(SOURCE)).isEqualToJson("lenient-same.json", getClass(),
|
||||
JSONCompareMode.LENIENT);
|
||||
assertThat(forJson(SOURCE)).isEqualToJson("lenient-same.json", getClass(), JSONCompareMode.LENIENT);
|
||||
}
|
||||
|
||||
@Test(expected = AssertionError.class)
|
||||
public void isEqualToJsonWhenResourcePathAndClassIsNotMatchingAndLenientShouldFail() {
|
||||
assertThat(forJson(SOURCE)).isEqualToJson("different.json", getClass(),
|
||||
JSONCompareMode.LENIENT);
|
||||
assertThat(forJson(SOURCE)).isEqualToJson("different.json", getClass(), JSONCompareMode.LENIENT);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void isEqualToJsonWhenBytesAreMatchingAndLenientShouldPass() {
|
||||
assertThat(forJson(SOURCE)).isEqualToJson(LENIENT_SAME.getBytes(),
|
||||
JSONCompareMode.LENIENT);
|
||||
assertThat(forJson(SOURCE)).isEqualToJson(LENIENT_SAME.getBytes(), JSONCompareMode.LENIENT);
|
||||
}
|
||||
|
||||
@Test(expected = AssertionError.class)
|
||||
public void isEqualToJsonWhenBytesAreNotMatchingAndLenientShouldFail() {
|
||||
assertThat(forJson(SOURCE)).isEqualToJson(DIFFERENT.getBytes(),
|
||||
JSONCompareMode.LENIENT);
|
||||
assertThat(forJson(SOURCE)).isEqualToJson(DIFFERENT.getBytes(), JSONCompareMode.LENIENT);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void isEqualToJsonWhenFileIsMatchingAndLenientShouldPass() throws Exception {
|
||||
assertThat(forJson(SOURCE)).isEqualToJson(createFile(LENIENT_SAME),
|
||||
JSONCompareMode.LENIENT);
|
||||
assertThat(forJson(SOURCE)).isEqualToJson(createFile(LENIENT_SAME), JSONCompareMode.LENIENT);
|
||||
}
|
||||
|
||||
@Test(expected = AssertionError.class)
|
||||
public void isEqualToJsonWhenFileIsNotMatchingAndLenientShouldFail()
|
||||
throws Exception {
|
||||
assertThat(forJson(SOURCE)).isEqualToJson(createFile(DIFFERENT),
|
||||
JSONCompareMode.LENIENT);
|
||||
public void isEqualToJsonWhenFileIsNotMatchingAndLenientShouldFail() throws Exception {
|
||||
assertThat(forJson(SOURCE)).isEqualToJson(createFile(DIFFERENT), JSONCompareMode.LENIENT);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void isEqualToJsonWhenInputStreamIsMatchingAndLenientShouldPass() {
|
||||
assertThat(forJson(SOURCE)).isEqualToJson(createInputStream(LENIENT_SAME),
|
||||
JSONCompareMode.LENIENT);
|
||||
assertThat(forJson(SOURCE)).isEqualToJson(createInputStream(LENIENT_SAME), JSONCompareMode.LENIENT);
|
||||
}
|
||||
|
||||
@Test(expected = AssertionError.class)
|
||||
public void isEqualToJsonWhenInputStreamIsNotMatchingAndLenientShouldFail() {
|
||||
assertThat(forJson(SOURCE)).isEqualToJson(createInputStream(DIFFERENT),
|
||||
JSONCompareMode.LENIENT);
|
||||
assertThat(forJson(SOURCE)).isEqualToJson(createInputStream(DIFFERENT), JSONCompareMode.LENIENT);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void isEqualToJsonWhenResourceIsMatchingAndLenientShouldPass() {
|
||||
assertThat(forJson(SOURCE)).isEqualToJson(createResource(LENIENT_SAME),
|
||||
JSONCompareMode.LENIENT);
|
||||
assertThat(forJson(SOURCE)).isEqualToJson(createResource(LENIENT_SAME), JSONCompareMode.LENIENT);
|
||||
}
|
||||
|
||||
@Test(expected = AssertionError.class)
|
||||
public void isEqualToJsonWhenResourceIsNotMatchingAndLenientShouldFail() {
|
||||
assertThat(forJson(SOURCE)).isEqualToJson(createResource(DIFFERENT),
|
||||
JSONCompareMode.LENIENT);
|
||||
assertThat(forJson(SOURCE)).isEqualToJson(createResource(DIFFERENT), JSONCompareMode.LENIENT);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -380,14 +364,12 @@ public class JsonContentAssertTests {
|
||||
|
||||
@Test
|
||||
public void isEqualToJsonWhenResourcePathAndClassAreMatchingAndComparatorShouldPass() {
|
||||
assertThat(forJson(SOURCE)).isEqualToJson("lenient-same.json", getClass(),
|
||||
COMPARATOR);
|
||||
assertThat(forJson(SOURCE)).isEqualToJson("lenient-same.json", getClass(), COMPARATOR);
|
||||
}
|
||||
|
||||
@Test(expected = AssertionError.class)
|
||||
public void isEqualToJsonWhenResourcePathAndClassAreNotMatchingAndComparatorShouldFail() {
|
||||
assertThat(forJson(SOURCE)).isEqualToJson("different.json", getClass(),
|
||||
COMPARATOR);
|
||||
assertThat(forJson(SOURCE)).isEqualToJson("different.json", getClass(), COMPARATOR);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -401,33 +383,28 @@ public class JsonContentAssertTests {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void isEqualToJsonWhenFileIsMatchingAndComparatorShouldPass()
|
||||
throws Exception {
|
||||
public void isEqualToJsonWhenFileIsMatchingAndComparatorShouldPass() throws Exception {
|
||||
assertThat(forJson(SOURCE)).isEqualToJson(createFile(LENIENT_SAME), COMPARATOR);
|
||||
}
|
||||
|
||||
@Test(expected = AssertionError.class)
|
||||
public void isEqualToJsonWhenFileIsNotMatchingAndComparatorShouldFail()
|
||||
throws Exception {
|
||||
public void isEqualToJsonWhenFileIsNotMatchingAndComparatorShouldFail() throws Exception {
|
||||
assertThat(forJson(SOURCE)).isEqualToJson(createFile(DIFFERENT), COMPARATOR);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void isEqualToJsonWhenInputStreamIsMatchingAndComparatorShouldPass() {
|
||||
assertThat(forJson(SOURCE)).isEqualToJson(createInputStream(LENIENT_SAME),
|
||||
COMPARATOR);
|
||||
assertThat(forJson(SOURCE)).isEqualToJson(createInputStream(LENIENT_SAME), COMPARATOR);
|
||||
}
|
||||
|
||||
@Test(expected = AssertionError.class)
|
||||
public void isEqualToJsonWhenInputStreamIsNotMatchingAndComparatorShouldFail() {
|
||||
assertThat(forJson(SOURCE)).isEqualToJson(createInputStream(DIFFERENT),
|
||||
COMPARATOR);
|
||||
assertThat(forJson(SOURCE)).isEqualToJson(createInputStream(DIFFERENT), COMPARATOR);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void isEqualToJsonWhenResourceIsMatchingAndComparatorShouldPass() {
|
||||
assertThat(forJson(SOURCE)).isEqualToJson(createResource(LENIENT_SAME),
|
||||
COMPARATOR);
|
||||
assertThat(forJson(SOURCE)).isEqualToJson(createResource(LENIENT_SAME), COMPARATOR);
|
||||
}
|
||||
|
||||
@Test(expected = AssertionError.class)
|
||||
@@ -602,8 +579,7 @@ public class JsonContentAssertTests {
|
||||
|
||||
@Test
|
||||
public void isNotStrictlyEqualToJsonWhenResourcePathAndClassAreNotMatchingShouldPass() {
|
||||
assertThat(forJson(SOURCE)).isNotStrictlyEqualToJson("lenient-same.json",
|
||||
getClass());
|
||||
assertThat(forJson(SOURCE)).isNotStrictlyEqualToJson("lenient-same.json", getClass());
|
||||
}
|
||||
|
||||
@Test(expected = AssertionError.class)
|
||||
@@ -622,8 +598,7 @@ public class JsonContentAssertTests {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void isNotStrictlyEqualToJsonWhenFileIsNotMatchingShouldPass()
|
||||
throws Exception {
|
||||
public void isNotStrictlyEqualToJsonWhenFileIsNotMatchingShouldPass() throws Exception {
|
||||
assertThat(forJson(SOURCE)).isNotStrictlyEqualToJson(createFile(LENIENT_SAME));
|
||||
}
|
||||
|
||||
@@ -634,8 +609,7 @@ public class JsonContentAssertTests {
|
||||
|
||||
@Test
|
||||
public void isNotStrictlyEqualToJsonWhenInputStreamIsNotMatchingShouldPass() {
|
||||
assertThat(forJson(SOURCE))
|
||||
.isNotStrictlyEqualToJson(createInputStream(LENIENT_SAME));
|
||||
assertThat(forJson(SOURCE)).isNotStrictlyEqualToJson(createInputStream(LENIENT_SAME));
|
||||
}
|
||||
|
||||
@Test(expected = AssertionError.class)
|
||||
@@ -645,14 +619,12 @@ public class JsonContentAssertTests {
|
||||
|
||||
@Test
|
||||
public void isNotStrictlyEqualToJsonWhenResourceIsNotMatchingShouldPass() {
|
||||
assertThat(forJson(SOURCE))
|
||||
.isNotStrictlyEqualToJson(createResource(LENIENT_SAME));
|
||||
assertThat(forJson(SOURCE)).isNotStrictlyEqualToJson(createResource(LENIENT_SAME));
|
||||
}
|
||||
|
||||
@Test(expected = AssertionError.class)
|
||||
public void isNotEqualToJsonWhenStringIsMatchingAndLenientShouldFail() {
|
||||
assertThat(forJson(SOURCE)).isNotEqualToJson(LENIENT_SAME,
|
||||
JSONCompareMode.LENIENT);
|
||||
assertThat(forJson(SOURCE)).isNotEqualToJson(LENIENT_SAME, JSONCompareMode.LENIENT);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -662,76 +634,62 @@ public class JsonContentAssertTests {
|
||||
|
||||
@Test(expected = AssertionError.class)
|
||||
public void isNotEqualToJsonWhenResourcePathIsMatchingAndLenientShouldFail() {
|
||||
assertThat(forJson(SOURCE)).isNotEqualToJson("lenient-same.json",
|
||||
JSONCompareMode.LENIENT);
|
||||
assertThat(forJson(SOURCE)).isNotEqualToJson("lenient-same.json", JSONCompareMode.LENIENT);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void isNotEqualToJsonWhenResourcePathIsNotMatchingAndLenientShouldPass() {
|
||||
assertThat(forJson(SOURCE)).isNotEqualToJson("different.json",
|
||||
JSONCompareMode.LENIENT);
|
||||
assertThat(forJson(SOURCE)).isNotEqualToJson("different.json", JSONCompareMode.LENIENT);
|
||||
}
|
||||
|
||||
@Test(expected = AssertionError.class)
|
||||
public void isNotEqualToJsonWhenResourcePathAndClassAreMatchingAndLenientShouldFail() {
|
||||
assertThat(forJson(SOURCE)).isNotEqualToJson("lenient-same.json", getClass(),
|
||||
JSONCompareMode.LENIENT);
|
||||
assertThat(forJson(SOURCE)).isNotEqualToJson("lenient-same.json", getClass(), JSONCompareMode.LENIENT);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void isNotEqualToJsonWhenResourcePathAndClassAreNotMatchingAndLenientShouldPass() {
|
||||
assertThat(forJson(SOURCE)).isNotEqualToJson("different.json", getClass(),
|
||||
JSONCompareMode.LENIENT);
|
||||
assertThat(forJson(SOURCE)).isNotEqualToJson("different.json", getClass(), JSONCompareMode.LENIENT);
|
||||
}
|
||||
|
||||
@Test(expected = AssertionError.class)
|
||||
public void isNotEqualToJsonWhenBytesAreMatchingAndLenientShouldFail() {
|
||||
assertThat(forJson(SOURCE)).isNotEqualToJson(LENIENT_SAME.getBytes(),
|
||||
JSONCompareMode.LENIENT);
|
||||
assertThat(forJson(SOURCE)).isNotEqualToJson(LENIENT_SAME.getBytes(), JSONCompareMode.LENIENT);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void isNotEqualToJsonWhenBytesAreNotMatchingAndLenientShouldPass() {
|
||||
assertThat(forJson(SOURCE)).isNotEqualToJson(DIFFERENT.getBytes(),
|
||||
JSONCompareMode.LENIENT);
|
||||
assertThat(forJson(SOURCE)).isNotEqualToJson(DIFFERENT.getBytes(), JSONCompareMode.LENIENT);
|
||||
}
|
||||
|
||||
@Test(expected = AssertionError.class)
|
||||
public void isNotEqualToJsonWhenFileIsMatchingAndLenientShouldFail()
|
||||
throws Exception {
|
||||
assertThat(forJson(SOURCE)).isNotEqualToJson(createFile(LENIENT_SAME),
|
||||
JSONCompareMode.LENIENT);
|
||||
public void isNotEqualToJsonWhenFileIsMatchingAndLenientShouldFail() throws Exception {
|
||||
assertThat(forJson(SOURCE)).isNotEqualToJson(createFile(LENIENT_SAME), JSONCompareMode.LENIENT);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void isNotEqualToJsonWhenFileIsNotMatchingAndLenientShouldPass()
|
||||
throws Exception {
|
||||
assertThat(forJson(SOURCE)).isNotEqualToJson(createFile(DIFFERENT),
|
||||
JSONCompareMode.LENIENT);
|
||||
public void isNotEqualToJsonWhenFileIsNotMatchingAndLenientShouldPass() throws Exception {
|
||||
assertThat(forJson(SOURCE)).isNotEqualToJson(createFile(DIFFERENT), JSONCompareMode.LENIENT);
|
||||
}
|
||||
|
||||
@Test(expected = AssertionError.class)
|
||||
public void isNotEqualToJsonWhenInputStreamIsMatchingAndLenientShouldFail() {
|
||||
assertThat(forJson(SOURCE)).isNotEqualToJson(createInputStream(LENIENT_SAME),
|
||||
JSONCompareMode.LENIENT);
|
||||
assertThat(forJson(SOURCE)).isNotEqualToJson(createInputStream(LENIENT_SAME), JSONCompareMode.LENIENT);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void isNotEqualToJsonWhenInputStreamIsNotMatchingAndLenientShouldPass() {
|
||||
assertThat(forJson(SOURCE)).isNotEqualToJson(createInputStream(DIFFERENT),
|
||||
JSONCompareMode.LENIENT);
|
||||
assertThat(forJson(SOURCE)).isNotEqualToJson(createInputStream(DIFFERENT), JSONCompareMode.LENIENT);
|
||||
}
|
||||
|
||||
@Test(expected = AssertionError.class)
|
||||
public void isNotEqualToJsonWhenResourceIsMatchingAndLenientShouldFail() {
|
||||
assertThat(forJson(SOURCE)).isNotEqualToJson(createResource(LENIENT_SAME),
|
||||
JSONCompareMode.LENIENT);
|
||||
assertThat(forJson(SOURCE)).isNotEqualToJson(createResource(LENIENT_SAME), JSONCompareMode.LENIENT);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void isNotEqualToJsonWhenResourceIsNotMatchingAndLenientShouldPass() {
|
||||
assertThat(forJson(SOURCE)).isNotEqualToJson(createResource(DIFFERENT),
|
||||
JSONCompareMode.LENIENT);
|
||||
assertThat(forJson(SOURCE)).isNotEqualToJson(createResource(DIFFERENT), JSONCompareMode.LENIENT);
|
||||
}
|
||||
|
||||
@Test(expected = AssertionError.class)
|
||||
@@ -756,14 +714,12 @@ public class JsonContentAssertTests {
|
||||
|
||||
@Test(expected = AssertionError.class)
|
||||
public void isNotEqualToJsonWhenResourcePathAndClassAreMatchingAndComparatorShouldFail() {
|
||||
assertThat(forJson(SOURCE)).isNotEqualToJson("lenient-same.json", getClass(),
|
||||
COMPARATOR);
|
||||
assertThat(forJson(SOURCE)).isNotEqualToJson("lenient-same.json", getClass(), COMPARATOR);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void isNotEqualToJsonWhenResourcePathAndClassAreNotMatchingAndComparatorShouldPass() {
|
||||
assertThat(forJson(SOURCE)).isNotEqualToJson("different.json", getClass(),
|
||||
COMPARATOR);
|
||||
assertThat(forJson(SOURCE)).isNotEqualToJson("different.json", getClass(), COMPARATOR);
|
||||
}
|
||||
|
||||
@Test(expected = AssertionError.class)
|
||||
@@ -777,40 +733,33 @@ public class JsonContentAssertTests {
|
||||
}
|
||||
|
||||
@Test(expected = AssertionError.class)
|
||||
public void isNotEqualToJsonWhenFileIsMatchingAndComparatorShouldFail()
|
||||
throws Exception {
|
||||
assertThat(forJson(SOURCE)).isNotEqualToJson(createFile(LENIENT_SAME),
|
||||
COMPARATOR);
|
||||
public void isNotEqualToJsonWhenFileIsMatchingAndComparatorShouldFail() throws Exception {
|
||||
assertThat(forJson(SOURCE)).isNotEqualToJson(createFile(LENIENT_SAME), COMPARATOR);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void isNotEqualToJsonWhenFileIsNotMatchingAndComparatorShouldPass()
|
||||
throws Exception {
|
||||
public void isNotEqualToJsonWhenFileIsNotMatchingAndComparatorShouldPass() throws Exception {
|
||||
assertThat(forJson(SOURCE)).isNotEqualToJson(createFile(DIFFERENT), COMPARATOR);
|
||||
}
|
||||
|
||||
@Test(expected = AssertionError.class)
|
||||
public void isNotEqualToJsonWhenInputStreamIsMatchingAndComparatorShouldFail() {
|
||||
assertThat(forJson(SOURCE)).isNotEqualToJson(createInputStream(LENIENT_SAME),
|
||||
COMPARATOR);
|
||||
assertThat(forJson(SOURCE)).isNotEqualToJson(createInputStream(LENIENT_SAME), COMPARATOR);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void isNotEqualToJsonWhenInputStreamIsNotMatchingAndComparatorShouldPass() {
|
||||
assertThat(forJson(SOURCE)).isNotEqualToJson(createInputStream(DIFFERENT),
|
||||
COMPARATOR);
|
||||
assertThat(forJson(SOURCE)).isNotEqualToJson(createInputStream(DIFFERENT), COMPARATOR);
|
||||
}
|
||||
|
||||
@Test(expected = AssertionError.class)
|
||||
public void isNotEqualToJsonWhenResourceIsMatchingAndComparatorShouldFail() {
|
||||
assertThat(forJson(SOURCE)).isNotEqualToJson(createResource(LENIENT_SAME),
|
||||
COMPARATOR);
|
||||
assertThat(forJson(SOURCE)).isNotEqualToJson(createResource(LENIENT_SAME), COMPARATOR);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void isNotEqualToJsonWhenResourceIsNotMatchingAndComparatorShouldPass() {
|
||||
assertThat(forJson(SOURCE)).isNotEqualToJson(createResource(DIFFERENT),
|
||||
COMPARATOR);
|
||||
assertThat(forJson(SOURCE)).isNotEqualToJson(createResource(DIFFERENT), COMPARATOR);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -830,16 +779,14 @@ public class JsonContentAssertTests {
|
||||
|
||||
@Test
|
||||
public void hasJsonPathValueForIndefinitePathWithResults() {
|
||||
assertThat(forJson(SIMPSONS))
|
||||
.hasJsonPathValue("$.familyMembers[?(@.name == 'Bart')]");
|
||||
assertThat(forJson(SIMPSONS)).hasJsonPathValue("$.familyMembers[?(@.name == 'Bart')]");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void hasJsonPathValueForIndefinitePathWithEmptyResults() {
|
||||
String expression = "$.familyMembers[?(@.name == 'Dilbert')]";
|
||||
assertThatExceptionOfType(AssertionError.class)
|
||||
.isThrownBy(
|
||||
() -> assertThat(forJson(SIMPSONS)).hasJsonPathValue(expression))
|
||||
.isThrownBy(() -> assertThat(forJson(SIMPSONS)).hasJsonPathValue(expression))
|
||||
.withMessageContaining("No value at JSON path \"" + expression + "\"");
|
||||
}
|
||||
|
||||
@@ -851,34 +798,31 @@ public class JsonContentAssertTests {
|
||||
@Test
|
||||
public void doesNotHaveJsonPathValueForAnEmptyArray() {
|
||||
String expression = "$.emptyArray";
|
||||
assertThatExceptionOfType(AssertionError.class).isThrownBy(
|
||||
() -> assertThat(forJson(TYPES)).doesNotHaveJsonPathValue(expression))
|
||||
.withMessageContaining("Expected no value at JSON path \"" + expression
|
||||
+ "\" but found: []");
|
||||
assertThatExceptionOfType(AssertionError.class)
|
||||
.isThrownBy(() -> assertThat(forJson(TYPES)).doesNotHaveJsonPathValue(expression))
|
||||
.withMessageContaining("Expected no value at JSON path \"" + expression + "\" but found: []");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void doesNotHaveJsonPathValueForAnEmptyMap() {
|
||||
String expression = "$.emptyMap";
|
||||
assertThatExceptionOfType(AssertionError.class).isThrownBy(
|
||||
() -> assertThat(forJson(TYPES)).doesNotHaveJsonPathValue(expression))
|
||||
.withMessageContaining("Expected no value at JSON path \"" + expression
|
||||
+ "\" but found: {}");
|
||||
assertThatExceptionOfType(AssertionError.class)
|
||||
.isThrownBy(() -> assertThat(forJson(TYPES)).doesNotHaveJsonPathValue(expression))
|
||||
.withMessageContaining("Expected no value at JSON path \"" + expression + "\" but found: {}");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void doesNotHaveJsonPathValueForIndefinitePathWithResults() {
|
||||
String expression = "$.familyMembers[?(@.name == 'Bart')]";
|
||||
assertThatExceptionOfType(AssertionError.class).isThrownBy(
|
||||
() -> assertThat(forJson(SIMPSONS)).doesNotHaveJsonPathValue(expression))
|
||||
.withMessageContaining("Expected no value at JSON path \"" + expression
|
||||
+ "\" but found: [{\"name\":\"Bart\"}]");
|
||||
assertThatExceptionOfType(AssertionError.class)
|
||||
.isThrownBy(() -> assertThat(forJson(SIMPSONS)).doesNotHaveJsonPathValue(expression))
|
||||
.withMessageContaining(
|
||||
"Expected no value at JSON path \"" + expression + "\" but found: [{\"name\":\"Bart\"}]");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void doesNotHaveJsonPathValueForIndefinitePathWithEmptyResults() {
|
||||
assertThat(forJson(SIMPSONS))
|
||||
.doesNotHaveJsonPathValue("$.familyMembers[?(@.name == 'Dilbert')]");
|
||||
assertThat(forJson(SIMPSONS)).doesNotHaveJsonPathValue("$.familyMembers[?(@.name == 'Dilbert')]");
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -898,26 +842,24 @@ public class JsonContentAssertTests {
|
||||
|
||||
@Test
|
||||
public void hasEmptyJsonPathValueForIndefinitePathWithEmptyResults() {
|
||||
assertThat(forJson(SIMPSONS))
|
||||
.hasEmptyJsonPathValue("$.familyMembers[?(@.name == 'Dilbert')]");
|
||||
assertThat(forJson(SIMPSONS)).hasEmptyJsonPathValue("$.familyMembers[?(@.name == 'Dilbert')]");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void hasEmptyJsonPathValueForIndefinitePathWithResults() {
|
||||
String expression = "$.familyMembers[?(@.name == 'Bart')]";
|
||||
assertThatExceptionOfType(AssertionError.class).isThrownBy(
|
||||
() -> assertThat(forJson(SIMPSONS)).hasEmptyJsonPathValue(expression))
|
||||
.withMessageContaining("Expected an empty value at JSON path \""
|
||||
+ expression + "\" but found: [{\"name\":\"Bart\"}]");
|
||||
assertThatExceptionOfType(AssertionError.class)
|
||||
.isThrownBy(() -> assertThat(forJson(SIMPSONS)).hasEmptyJsonPathValue(expression))
|
||||
.withMessageContaining(
|
||||
"Expected an empty value at JSON path \"" + expression + "\" but found: [{\"name\":\"Bart\"}]");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void hasEmptyJsonPathValueForWhitespace() {
|
||||
String expression = "$.whitespace";
|
||||
assertThatExceptionOfType(AssertionError.class).isThrownBy(
|
||||
() -> assertThat(forJson(TYPES)).hasEmptyJsonPathValue(expression))
|
||||
.withMessageContaining("Expected an empty value at JSON path \""
|
||||
+ expression + "\" but found: ' '");
|
||||
assertThatExceptionOfType(AssertionError.class)
|
||||
.isThrownBy(() -> assertThat(forJson(TYPES)).hasEmptyJsonPathValue(expression))
|
||||
.withMessageContaining("Expected an empty value at JSON path \"" + expression + "\" but found: ' '");
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -947,48 +889,39 @@ public class JsonContentAssertTests {
|
||||
|
||||
@Test
|
||||
public void doesNotHaveEmptyJsonPathValueForIndefinitePathWithResults() {
|
||||
assertThat(forJson(SIMPSONS))
|
||||
.doesNotHaveEmptyJsonPathValue("$.familyMembers[?(@.name == 'Bart')]");
|
||||
assertThat(forJson(SIMPSONS)).doesNotHaveEmptyJsonPathValue("$.familyMembers[?(@.name == 'Bart')]");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void doesNotHaveEmptyJsonPathValueForIndefinitePathWithEmptyResults() {
|
||||
String expression = "$.familyMembers[?(@.name == 'Dilbert')]";
|
||||
assertThatExceptionOfType(AssertionError.class)
|
||||
.isThrownBy(() -> assertThat(forJson(SIMPSONS))
|
||||
.doesNotHaveEmptyJsonPathValue(expression))
|
||||
.withMessageContaining("Expected a non-empty value at JSON path \""
|
||||
+ expression + "\" but found: []");
|
||||
.isThrownBy(() -> assertThat(forJson(SIMPSONS)).doesNotHaveEmptyJsonPathValue(expression))
|
||||
.withMessageContaining("Expected a non-empty value at JSON path \"" + expression + "\" but found: []");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void doesNotHaveEmptyJsonPathValueForAnEmptyString() {
|
||||
String expression = "$.emptyString";
|
||||
assertThatExceptionOfType(AssertionError.class)
|
||||
.isThrownBy(() -> assertThat(forJson(TYPES))
|
||||
.doesNotHaveEmptyJsonPathValue(expression))
|
||||
.withMessageContaining("Expected a non-empty value at JSON path \""
|
||||
+ expression + "\" but found: ''");
|
||||
.isThrownBy(() -> assertThat(forJson(TYPES)).doesNotHaveEmptyJsonPathValue(expression))
|
||||
.withMessageContaining("Expected a non-empty value at JSON path \"" + expression + "\" but found: ''");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void doesNotHaveEmptyJsonPathValueForForAnEmptyArray() {
|
||||
String expression = "$.emptyArray";
|
||||
assertThatExceptionOfType(AssertionError.class)
|
||||
.isThrownBy(() -> assertThat(forJson(TYPES))
|
||||
.doesNotHaveEmptyJsonPathValue(expression))
|
||||
.withMessageContaining("Expected a non-empty value at JSON path \""
|
||||
+ expression + "\" but found: []");
|
||||
.isThrownBy(() -> assertThat(forJson(TYPES)).doesNotHaveEmptyJsonPathValue(expression))
|
||||
.withMessageContaining("Expected a non-empty value at JSON path \"" + expression + "\" but found: []");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void doesNotHaveEmptyJsonPathValueForAnEmptyMap() {
|
||||
String expression = "$.emptyMap";
|
||||
assertThatExceptionOfType(AssertionError.class)
|
||||
.isThrownBy(() -> assertThat(forJson(TYPES))
|
||||
.doesNotHaveEmptyJsonPathValue(expression))
|
||||
.withMessageContaining("Expected a non-empty value at JSON path \""
|
||||
+ expression + "\" but found: {}");
|
||||
.isThrownBy(() -> assertThat(forJson(TYPES)).doesNotHaveEmptyJsonPathValue(expression))
|
||||
.withMessageContaining("Expected a non-empty value at JSON path \"" + expression + "\" but found: {}");
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -1004,10 +937,9 @@ public class JsonContentAssertTests {
|
||||
@Test
|
||||
public void hasJsonPathStringValueForNonString() {
|
||||
String expression = "$.bool";
|
||||
assertThatExceptionOfType(AssertionError.class).isThrownBy(
|
||||
() -> assertThat(forJson(TYPES)).hasJsonPathStringValue(expression))
|
||||
.withMessageContaining("Expected a string at JSON path \"" + expression
|
||||
+ "\" but found: true");
|
||||
assertThatExceptionOfType(AssertionError.class)
|
||||
.isThrownBy(() -> assertThat(forJson(TYPES)).hasJsonPathStringValue(expression))
|
||||
.withMessageContaining("Expected a string at JSON path \"" + expression + "\" but found: true");
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -1018,10 +950,9 @@ public class JsonContentAssertTests {
|
||||
@Test
|
||||
public void hasJsonPathNumberValueForNonNumber() {
|
||||
String expression = "$.bool";
|
||||
assertThatExceptionOfType(AssertionError.class).isThrownBy(
|
||||
() -> assertThat(forJson(TYPES)).hasJsonPathNumberValue(expression))
|
||||
.withMessageContaining("Expected a number at JSON path \"" + expression
|
||||
+ "\" but found: true");
|
||||
assertThatExceptionOfType(AssertionError.class)
|
||||
.isThrownBy(() -> assertThat(forJson(TYPES)).hasJsonPathNumberValue(expression))
|
||||
.withMessageContaining("Expected a number at JSON path \"" + expression + "\" but found: true");
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -1032,10 +963,9 @@ public class JsonContentAssertTests {
|
||||
@Test
|
||||
public void hasJsonPathBooleanValueForNonBoolean() {
|
||||
String expression = "$.num";
|
||||
assertThatExceptionOfType(AssertionError.class).isThrownBy(
|
||||
() -> assertThat(forJson(TYPES)).hasJsonPathBooleanValue(expression))
|
||||
.withMessageContaining("Expected a boolean at JSON path \"" + expression
|
||||
+ "\" but found: 5");
|
||||
assertThatExceptionOfType(AssertionError.class)
|
||||
.isThrownBy(() -> assertThat(forJson(TYPES)).hasJsonPathBooleanValue(expression))
|
||||
.withMessageContaining("Expected a boolean at JSON path \"" + expression + "\" but found: 5");
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -1051,10 +981,9 @@ public class JsonContentAssertTests {
|
||||
@Test
|
||||
public void hasJsonPathArrayValueForNonArray() {
|
||||
String expression = "$.str";
|
||||
assertThatExceptionOfType(AssertionError.class).isThrownBy(
|
||||
() -> assertThat(forJson(TYPES)).hasJsonPathArrayValue(expression))
|
||||
.withMessageContaining("Expected an array at JSON path \"" + expression
|
||||
+ "\" but found: 'foo'");
|
||||
assertThatExceptionOfType(AssertionError.class)
|
||||
.isThrownBy(() -> assertThat(forJson(TYPES)).hasJsonPathArrayValue(expression))
|
||||
.withMessageContaining("Expected an array at JSON path \"" + expression + "\" but found: 'foo'");
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -1071,10 +1000,8 @@ public class JsonContentAssertTests {
|
||||
public void hasJsonPathMapValueForNonMap() {
|
||||
String expression = "$.str";
|
||||
assertThatExceptionOfType(AssertionError.class)
|
||||
.isThrownBy(
|
||||
() -> assertThat(forJson(TYPES)).hasJsonPathMapValue(expression))
|
||||
.withMessageContaining("Expected a map at JSON path \"" + expression
|
||||
+ "\" but found: 'foo'");
|
||||
.isThrownBy(() -> assertThat(forJson(TYPES)).hasJsonPathMapValue(expression))
|
||||
.withMessageContaining("Expected a map at JSON path \"" + expression + "\" but found: 'foo'");
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -1089,8 +1016,7 @@ public class JsonContentAssertTests {
|
||||
|
||||
@Test
|
||||
public void extractingJsonPathStringValue() {
|
||||
assertThat(forJson(TYPES)).extractingJsonPathStringValue("@.str")
|
||||
.isEqualTo("foo");
|
||||
assertThat(forJson(TYPES)).extractingJsonPathStringValue("@.str").isEqualTo("foo");
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -1100,18 +1026,15 @@ public class JsonContentAssertTests {
|
||||
|
||||
@Test
|
||||
public void extractingJsonPathStringValueForEmptyString() {
|
||||
assertThat(forJson(TYPES)).extractingJsonPathStringValue("@.emptyString")
|
||||
.isEmpty();
|
||||
assertThat(forJson(TYPES)).extractingJsonPathStringValue("@.emptyString").isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void extractingJsonPathStringValueForWrongType() {
|
||||
String expression = "$.num";
|
||||
assertThatExceptionOfType(AssertionError.class)
|
||||
.isThrownBy(() -> assertThat(forJson(TYPES))
|
||||
.extractingJsonPathStringValue(expression))
|
||||
.withMessageContaining("Expected a string at JSON path \"" + expression
|
||||
+ "\" but found: 5");
|
||||
.isThrownBy(() -> assertThat(forJson(TYPES)).extractingJsonPathStringValue(expression))
|
||||
.withMessageContaining("Expected a string at JSON path \"" + expression + "\" but found: 5");
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -1128,10 +1051,8 @@ public class JsonContentAssertTests {
|
||||
public void extractingJsonPathNumberValueForWrongType() {
|
||||
String expression = "$.str";
|
||||
assertThatExceptionOfType(AssertionError.class)
|
||||
.isThrownBy(() -> assertThat(forJson(TYPES))
|
||||
.extractingJsonPathNumberValue(expression))
|
||||
.withMessageContaining("Expected a number at JSON path \"" + expression
|
||||
+ "\" but found: 'foo'");
|
||||
.isThrownBy(() -> assertThat(forJson(TYPES)).extractingJsonPathNumberValue(expression))
|
||||
.withMessageContaining("Expected a number at JSON path \"" + expression + "\" but found: 'foo'");
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -1148,16 +1069,13 @@ public class JsonContentAssertTests {
|
||||
public void extractingJsonPathBooleanValueForWrongType() {
|
||||
String expression = "$.str";
|
||||
assertThatExceptionOfType(AssertionError.class)
|
||||
.isThrownBy(() -> assertThat(forJson(TYPES))
|
||||
.extractingJsonPathBooleanValue(expression))
|
||||
.withMessageContaining("Expected a boolean at JSON path \"" + expression
|
||||
+ "\" but found: 'foo'");
|
||||
.isThrownBy(() -> assertThat(forJson(TYPES)).extractingJsonPathBooleanValue(expression))
|
||||
.withMessageContaining("Expected a boolean at JSON path \"" + expression + "\" but found: 'foo'");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void extractingJsonPathArrayValue() {
|
||||
assertThat(forJson(TYPES)).extractingJsonPathArrayValue("@.arr")
|
||||
.containsExactly(42);
|
||||
assertThat(forJson(TYPES)).extractingJsonPathArrayValue("@.arr").containsExactly(42);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -1173,16 +1091,14 @@ public class JsonContentAssertTests {
|
||||
@Test
|
||||
public void extractingJsonPathArrayValueForWrongType() {
|
||||
String expression = "$.str";
|
||||
assertThatExceptionOfType(AssertionError.class).isThrownBy(
|
||||
() -> assertThat(forJson(TYPES)).extractingJsonPathArrayValue(expression))
|
||||
.withMessageContaining("Expected an array at JSON path \"" + expression
|
||||
+ "\" but found: 'foo'");
|
||||
assertThatExceptionOfType(AssertionError.class)
|
||||
.isThrownBy(() -> assertThat(forJson(TYPES)).extractingJsonPathArrayValue(expression))
|
||||
.withMessageContaining("Expected an array at JSON path \"" + expression + "\" but found: 'foo'");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void extractingJsonPathMapValue() {
|
||||
assertThat(forJson(TYPES)).extractingJsonPathMapValue("@.colorMap")
|
||||
.contains(entry("red", "rojo"));
|
||||
assertThat(forJson(TYPES)).extractingJsonPathMapValue("@.colorMap").contains(entry("red", "rojo"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -1198,10 +1114,9 @@ public class JsonContentAssertTests {
|
||||
@Test
|
||||
public void extractingJsonPathMapValueForWrongType() {
|
||||
String expression = "$.str";
|
||||
assertThatExceptionOfType(AssertionError.class).isThrownBy(
|
||||
() -> assertThat(forJson(TYPES)).extractingJsonPathMapValue(expression))
|
||||
.withMessageContaining("Expected a map at JSON path \"" + expression
|
||||
+ "\" but found: 'foo'");
|
||||
assertThatExceptionOfType(AssertionError.class)
|
||||
.isThrownBy(() -> assertThat(forJson(TYPES)).extractingJsonPathMapValue(expression))
|
||||
.withMessageContaining("Expected a map at JSON path \"" + expression + "\" but found: 'foo'");
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -1225,8 +1140,7 @@ public class JsonContentAssertTests {
|
||||
|
||||
private static String loadJson(String path) {
|
||||
try {
|
||||
ClassPathResource resource = new ClassPathResource(path,
|
||||
JsonContentAssertTests.class);
|
||||
ClassPathResource resource = new ClassPathResource(path, JsonContentAssertTests.class);
|
||||
return new String(FileCopyUtils.copyToByteArray(resource.getInputStream()));
|
||||
}
|
||||
catch (Exception ex) {
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2012-2018 the original author or authors.
|
||||
* Copyright 2012-2019 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -37,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());
|
||||
|
||||
}
|
||||
|
||||
|
||||
@@ -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,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 {
|
||||
|
||||
}
|
||||
|
||||
@@ -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.
|
||||
@@ -52,8 +52,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();
|
||||
@@ -73,8 +72,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;
|
||||
}
|
||||
|
||||
|
||||
@@ -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.
|
||||
@@ -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");
|
||||
}
|
||||
|
||||
|
||||
@@ -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,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");
|
||||
|
||||
@@ -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,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);
|
||||
}
|
||||
|
||||
|
||||
@@ -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.
|
||||
@@ -40,28 +40,23 @@ public class MockitoContextCustomizerFactoryTests {
|
||||
|
||||
@Test
|
||||
public void getContextCustomizerWithoutAnnotationReturnsCustomizer() {
|
||||
ContextCustomizer customizer = this.factory
|
||||
.createContextCustomizer(NoMockBeanAnnotation.class, null);
|
||||
ContextCustomizer customizer = this.factory.createContextCustomizer(NoMockBeanAnnotation.class, null);
|
||||
assertThat(customizer).isNotNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void getContextCustomizerWithAnnotationReturnsCustomizer() {
|
||||
ContextCustomizer customizer = this.factory
|
||||
.createContextCustomizer(WithMockBeanAnnotation.class, null);
|
||||
ContextCustomizer customizer = this.factory.createContextCustomizer(WithMockBeanAnnotation.class, null);
|
||||
assertThat(customizer).isNotNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void getContextCustomizerUsesMocksAsCacheKey() {
|
||||
ContextCustomizer customizer = this.factory
|
||||
.createContextCustomizer(WithMockBeanAnnotation.class, null);
|
||||
ContextCustomizer customizer = this.factory.createContextCustomizer(WithMockBeanAnnotation.class, null);
|
||||
assertThat(customizer).isNotNull();
|
||||
ContextCustomizer same = this.factory
|
||||
.createContextCustomizer(WithSameMockBeanAnnotation.class, null);
|
||||
ContextCustomizer same = this.factory.createContextCustomizer(WithSameMockBeanAnnotation.class, null);
|
||||
assertThat(customizer).isNotNull();
|
||||
ContextCustomizer different = this.factory
|
||||
.createContextCustomizer(WithDifferentMockBeanAnnotation.class, null);
|
||||
ContextCustomizer different = this.factory.createContextCustomizer(WithDifferentMockBeanAnnotation.class, null);
|
||||
assertThat(different).isNotNull();
|
||||
assertThat(customizer.hashCode()).isEqualTo(same.hashCode());
|
||||
assertThat(customizer.hashCode()).isNotEqualTo(different.hashCode());
|
||||
|
||||
@@ -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,18 +43,15 @@ public class MockitoContextCustomizerTests {
|
||||
MockDefinition d1 = createTestMockDefinition(ExampleService.class);
|
||||
MockDefinition d2 = createTestMockDefinition(ExampleServiceCaller.class);
|
||||
MockitoContextCustomizer c1 = new MockitoContextCustomizer(NO_DEFINITIONS);
|
||||
MockitoContextCustomizer c2 = new MockitoContextCustomizer(
|
||||
new LinkedHashSet<>(Arrays.asList(d1, d2)));
|
||||
MockitoContextCustomizer c3 = new MockitoContextCustomizer(
|
||||
new LinkedHashSet<>(Arrays.asList(d2, d1)));
|
||||
MockitoContextCustomizer c2 = new MockitoContextCustomizer(new LinkedHashSet<>(Arrays.asList(d1, d2)));
|
||||
MockitoContextCustomizer c3 = new MockitoContextCustomizer(new LinkedHashSet<>(Arrays.asList(d2, d1)));
|
||||
assertThat(c2.hashCode()).isEqualTo(c3.hashCode());
|
||||
assertThat(c1).isEqualTo(c1).isNotEqualTo(c2);
|
||||
assertThat(c2).isEqualTo(c2).isEqualTo(c3).isNotEqualTo(c1);
|
||||
}
|
||||
|
||||
private MockDefinition createTestMockDefinition(Class<?> typeToMock) {
|
||||
return new MockDefinition(null, ResolvableType.forClass(typeToMock), null, null,
|
||||
false, null, null);
|
||||
return new MockDefinition(null, ResolvableType.forClass(typeToMock), null, null, false, null, null);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2012-2018 the original author or authors.
|
||||
* Copyright 2012-2019 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -48,10 +48,8 @@ public class MockitoPostProcessorTests {
|
||||
MockitoPostProcessor.register(context);
|
||||
context.register(MultipleBeans.class);
|
||||
assertThatIllegalStateException().isThrownBy(context::refresh)
|
||||
.withMessageContaining(
|
||||
"Unable to register mock bean " + ExampleService.class.getName()
|
||||
+ " expected a single matching bean to replace "
|
||||
+ "but found [example1, example2]");
|
||||
.withMessageContaining("Unable to register mock bean " + ExampleService.class.getName()
|
||||
+ " expected a single matching bean to replace " + "but found [example1, example2]");
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -60,25 +58,20 @@ public class MockitoPostProcessorTests {
|
||||
MockitoPostProcessor.register(context);
|
||||
context.register(MultipleQualifiedBeans.class);
|
||||
assertThatIllegalStateException().isThrownBy(context::refresh)
|
||||
.withMessageContaining(
|
||||
"Unable to register mock bean " + ExampleService.class.getName()
|
||||
+ " expected a single matching bean to replace "
|
||||
+ "but found [example1, example3]");
|
||||
.withMessageContaining("Unable to register mock bean " + ExampleService.class.getName()
|
||||
+ " expected a single matching bean to replace " + "but found [example1, example3]");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void canMockBeanProducedByFactoryBeanWithObjectTypeAttribute() {
|
||||
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
|
||||
MockitoPostProcessor.register(context);
|
||||
RootBeanDefinition factoryBeanDefinition = new RootBeanDefinition(
|
||||
TestFactoryBean.class);
|
||||
factoryBeanDefinition.setAttribute("factoryBeanObjectType",
|
||||
SomeInterface.class.getName());
|
||||
RootBeanDefinition factoryBeanDefinition = new RootBeanDefinition(TestFactoryBean.class);
|
||||
factoryBeanDefinition.setAttribute("factoryBeanObjectType", SomeInterface.class.getName());
|
||||
context.registerBeanDefinition("beanToBeMocked", factoryBeanDefinition);
|
||||
context.register(MockedFactoryBean.class);
|
||||
context.refresh();
|
||||
assertThat(Mockito.mockingDetails(context.getBean("beanToBeMocked")).isMock())
|
||||
.isTrue();
|
||||
assertThat(Mockito.mockingDetails(context.getBean("beanToBeMocked")).isMock()).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -87,16 +80,11 @@ public class MockitoPostProcessorTests {
|
||||
MockitoPostProcessor.register(context);
|
||||
context.register(MockPrimaryBean.class);
|
||||
context.refresh();
|
||||
assertThat(Mockito.mockingDetails(context.getBean(MockPrimaryBean.class).mock)
|
||||
.isMock()).isTrue();
|
||||
assertThat(Mockito.mockingDetails(context.getBean(ExampleService.class)).isMock())
|
||||
.isTrue();
|
||||
assertThat(Mockito
|
||||
.mockingDetails(context.getBean("examplePrimary", ExampleService.class))
|
||||
.isMock()).isTrue();
|
||||
assertThat(Mockito
|
||||
.mockingDetails(context.getBean("exampleQualified", ExampleService.class))
|
||||
.isMock()).isFalse();
|
||||
assertThat(Mockito.mockingDetails(context.getBean(MockPrimaryBean.class).mock).isMock()).isTrue();
|
||||
assertThat(Mockito.mockingDetails(context.getBean(ExampleService.class)).isMock()).isTrue();
|
||||
assertThat(Mockito.mockingDetails(context.getBean("examplePrimary", ExampleService.class)).isMock()).isTrue();
|
||||
assertThat(Mockito.mockingDetails(context.getBean("exampleQualified", ExampleService.class)).isMock())
|
||||
.isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -105,16 +93,10 @@ public class MockitoPostProcessorTests {
|
||||
MockitoPostProcessor.register(context);
|
||||
context.register(MockQualifiedBean.class);
|
||||
context.refresh();
|
||||
assertThat(Mockito.mockingDetails(context.getBean(MockQualifiedBean.class).mock)
|
||||
.isMock()).isTrue();
|
||||
assertThat(Mockito.mockingDetails(context.getBean(ExampleService.class)).isMock())
|
||||
.isFalse();
|
||||
assertThat(Mockito
|
||||
.mockingDetails(context.getBean("examplePrimary", ExampleService.class))
|
||||
.isMock()).isFalse();
|
||||
assertThat(Mockito
|
||||
.mockingDetails(context.getBean("exampleQualified", ExampleService.class))
|
||||
.isMock()).isTrue();
|
||||
assertThat(Mockito.mockingDetails(context.getBean(MockQualifiedBean.class).mock).isMock()).isTrue();
|
||||
assertThat(Mockito.mockingDetails(context.getBean(ExampleService.class)).isMock()).isFalse();
|
||||
assertThat(Mockito.mockingDetails(context.getBean("examplePrimary", ExampleService.class)).isMock()).isFalse();
|
||||
assertThat(Mockito.mockingDetails(context.getBean("exampleQualified", ExampleService.class)).isMock()).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -123,17 +105,10 @@ public class MockitoPostProcessorTests {
|
||||
MockitoPostProcessor.register(context);
|
||||
context.register(SpyPrimaryBean.class);
|
||||
context.refresh();
|
||||
assertThat(
|
||||
Mockito.mockingDetails(context.getBean(SpyPrimaryBean.class).spy).isSpy())
|
||||
.isTrue();
|
||||
assertThat(Mockito.mockingDetails(context.getBean(ExampleService.class)).isSpy())
|
||||
.isTrue();
|
||||
assertThat(Mockito
|
||||
.mockingDetails(context.getBean("examplePrimary", ExampleService.class))
|
||||
.isSpy()).isTrue();
|
||||
assertThat(Mockito
|
||||
.mockingDetails(context.getBean("exampleQualified", ExampleService.class))
|
||||
.isSpy()).isFalse();
|
||||
assertThat(Mockito.mockingDetails(context.getBean(SpyPrimaryBean.class).spy).isSpy()).isTrue();
|
||||
assertThat(Mockito.mockingDetails(context.getBean(ExampleService.class)).isSpy()).isTrue();
|
||||
assertThat(Mockito.mockingDetails(context.getBean("examplePrimary", ExampleService.class)).isSpy()).isTrue();
|
||||
assertThat(Mockito.mockingDetails(context.getBean("exampleQualified", ExampleService.class)).isSpy()).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -142,16 +117,10 @@ public class MockitoPostProcessorTests {
|
||||
MockitoPostProcessor.register(context);
|
||||
context.register(SpyQualifiedBean.class);
|
||||
context.refresh();
|
||||
assertThat(Mockito.mockingDetails(context.getBean(SpyQualifiedBean.class).spy)
|
||||
.isSpy()).isTrue();
|
||||
assertThat(Mockito.mockingDetails(context.getBean(ExampleService.class)).isSpy())
|
||||
.isFalse();
|
||||
assertThat(Mockito
|
||||
.mockingDetails(context.getBean("examplePrimary", ExampleService.class))
|
||||
.isSpy()).isFalse();
|
||||
assertThat(Mockito
|
||||
.mockingDetails(context.getBean("exampleQualified", ExampleService.class))
|
||||
.isSpy()).isTrue();
|
||||
assertThat(Mockito.mockingDetails(context.getBean(SpyQualifiedBean.class).spy).isSpy()).isTrue();
|
||||
assertThat(Mockito.mockingDetails(context.getBean(ExampleService.class)).isSpy()).isFalse();
|
||||
assertThat(Mockito.mockingDetails(context.getBean("examplePrimary", ExampleService.class)).isSpy()).isFalse();
|
||||
assertThat(Mockito.mockingDetails(context.getBean("exampleQualified", ExampleService.class)).isSpy()).isTrue();
|
||||
}
|
||||
|
||||
@Configuration
|
||||
|
||||
@@ -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.
|
||||
@@ -59,8 +59,7 @@ public class MockitoTestExecutionListenerTests {
|
||||
@Before
|
||||
public void setup() {
|
||||
MockitoAnnotations.initMocks(this);
|
||||
given(this.applicationContext.getBean(MockitoPostProcessor.class))
|
||||
.willReturn(this.postProcessor);
|
||||
given(this.applicationContext.getBean(MockitoPostProcessor.class)).willReturn(this.postProcessor);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -75,30 +74,25 @@ public class MockitoTestExecutionListenerTests {
|
||||
public void prepareTestInstanceShouldInjectMockBean() throws Exception {
|
||||
WithMockBean instance = new WithMockBean();
|
||||
this.listener.prepareTestInstance(mockTestContext(instance));
|
||||
verify(this.postProcessor).inject(this.fieldCaptor.capture(), eq(instance),
|
||||
any(MockDefinition.class));
|
||||
verify(this.postProcessor).inject(this.fieldCaptor.capture(), eq(instance), any(MockDefinition.class));
|
||||
assertThat(this.fieldCaptor.getValue().getName()).isEqualTo("mockBean");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void beforeTestMethodShouldDoNothingWhenDirtiesContextAttributeIsNotSet()
|
||||
throws Exception {
|
||||
public void beforeTestMethodShouldDoNothingWhenDirtiesContextAttributeIsNotSet() throws Exception {
|
||||
WithMockBean instance = new WithMockBean();
|
||||
this.listener.beforeTestMethod(mockTestContext(instance));
|
||||
verifyNoMoreInteractions(this.postProcessor);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void beforeTestMethodShouldInjectMockBeanWhenDirtiesContextAttributeIsSet()
|
||||
throws Exception {
|
||||
public void beforeTestMethodShouldInjectMockBeanWhenDirtiesContextAttributeIsSet() throws Exception {
|
||||
WithMockBean instance = new WithMockBean();
|
||||
TestContext mockTestContext = mockTestContext(instance);
|
||||
given(mockTestContext.getAttribute(
|
||||
DependencyInjectionTestExecutionListener.REINJECT_DEPENDENCIES_ATTRIBUTE))
|
||||
.willReturn(Boolean.TRUE);
|
||||
given(mockTestContext.getAttribute(DependencyInjectionTestExecutionListener.REINJECT_DEPENDENCIES_ATTRIBUTE))
|
||||
.willReturn(Boolean.TRUE);
|
||||
this.listener.beforeTestMethod(mockTestContext);
|
||||
verify(this.postProcessor).inject(this.fieldCaptor.capture(), eq(instance),
|
||||
(MockDefinition) any());
|
||||
verify(this.postProcessor).inject(this.fieldCaptor.capture(), eq(instance), (MockDefinition) any());
|
||||
assertThat(this.fieldCaptor.getValue().getName()).isEqualTo("mockBean");
|
||||
}
|
||||
|
||||
|
||||
@@ -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.
|
||||
@@ -85,10 +85,8 @@ public class QualifierDefinitionTests {
|
||||
Field field = ReflectionUtils.findField(ConfigA.class, "directQualifier");
|
||||
QualifierDefinition qualifierDefinition = QualifierDefinition.forElement(field);
|
||||
qualifierDefinition.matches(this.beanFactory, "bean");
|
||||
verify(this.beanFactory).isAutowireCandidate(eq("bean"),
|
||||
this.descriptorCaptor.capture());
|
||||
assertThat(this.descriptorCaptor.getValue().getAnnotatedElement())
|
||||
.isEqualTo(field);
|
||||
verify(this.beanFactory).isAutowireCandidate(eq("bean"), this.descriptorCaptor.capture());
|
||||
assertThat(this.descriptorCaptor.getValue().getAnnotatedElement()).isEqualTo(field);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -106,24 +104,23 @@ public class QualifierDefinitionTests {
|
||||
.forElement(ReflectionUtils.findField(ConfigA.class, "directQualifier"));
|
||||
QualifierDefinition directQualifier2 = QualifierDefinition
|
||||
.forElement(ReflectionUtils.findField(ConfigB.class, "directQualifier"));
|
||||
QualifierDefinition differentDirectQualifier1 = QualifierDefinition.forElement(
|
||||
ReflectionUtils.findField(ConfigA.class, "differentDirectQualifier"));
|
||||
QualifierDefinition differentDirectQualifier2 = QualifierDefinition.forElement(
|
||||
ReflectionUtils.findField(ConfigB.class, "differentDirectQualifier"));
|
||||
QualifierDefinition differentDirectQualifier1 = QualifierDefinition
|
||||
.forElement(ReflectionUtils.findField(ConfigA.class, "differentDirectQualifier"));
|
||||
QualifierDefinition differentDirectQualifier2 = QualifierDefinition
|
||||
.forElement(ReflectionUtils.findField(ConfigB.class, "differentDirectQualifier"));
|
||||
QualifierDefinition customQualifier1 = QualifierDefinition
|
||||
.forElement(ReflectionUtils.findField(ConfigA.class, "customQualifier"));
|
||||
QualifierDefinition customQualifier2 = QualifierDefinition
|
||||
.forElement(ReflectionUtils.findField(ConfigB.class, "customQualifier"));
|
||||
assertThat(directQualifier1.hashCode()).isEqualTo(directQualifier2.hashCode());
|
||||
assertThat(differentDirectQualifier1.hashCode())
|
||||
.isEqualTo(differentDirectQualifier2.hashCode());
|
||||
assertThat(differentDirectQualifier1.hashCode()).isEqualTo(differentDirectQualifier2.hashCode());
|
||||
assertThat(customQualifier1.hashCode()).isEqualTo(customQualifier2.hashCode());
|
||||
assertThat(differentDirectQualifier1).isEqualTo(differentDirectQualifier1)
|
||||
.isEqualTo(differentDirectQualifier2).isNotEqualTo(directQualifier2);
|
||||
assertThat(directQualifier1).isEqualTo(directQualifier1)
|
||||
.isEqualTo(directQualifier2).isNotEqualTo(differentDirectQualifier1);
|
||||
assertThat(customQualifier1).isEqualTo(customQualifier1)
|
||||
.isEqualTo(customQualifier2).isNotEqualTo(differentDirectQualifier1);
|
||||
assertThat(differentDirectQualifier1).isEqualTo(differentDirectQualifier1).isEqualTo(differentDirectQualifier2)
|
||||
.isNotEqualTo(directQualifier2);
|
||||
assertThat(directQualifier1).isEqualTo(directQualifier1).isEqualTo(directQualifier2)
|
||||
.isNotEqualTo(differentDirectQualifier1);
|
||||
assertThat(customQualifier1).isEqualTo(customQualifier1).isEqualTo(customQualifier2)
|
||||
.isNotEqualTo(differentDirectQualifier1);
|
||||
}
|
||||
|
||||
@Configuration
|
||||
|
||||
@@ -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.
|
||||
@@ -53,8 +53,7 @@ public class SpyBeanOnContextHierarchyIntegrationTests {
|
||||
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 SpyBeanOnContextHierarchyIntegrationTests {
|
||||
private ApplicationContext context;
|
||||
|
||||
@Override
|
||||
public void setApplicationContext(ApplicationContext applicationContext)
|
||||
throws BeansException {
|
||||
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
|
||||
this.context = 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.
|
||||
@@ -61,8 +61,7 @@ public class SpyBeanOnTestFieldForExistingBeanWithQualifierIntegrationTests {
|
||||
@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");
|
||||
}
|
||||
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user