Upgrade to spring-javaformat 0.0.11
This commit is contained in:
@@ -37,8 +37,7 @@ public class ConfigFileApplicationContextInitializer
|
||||
public void initialize(final ConfigurableApplicationContext applicationContext) {
|
||||
new ConfigFileApplicationListener() {
|
||||
public void apply() {
|
||||
addPropertySources(applicationContext.getEnvironment(),
|
||||
applicationContext);
|
||||
addPropertySources(applicationContext.getEnvironment(), applicationContext);
|
||||
addPostProcessors(applicationContext);
|
||||
}
|
||||
}.apply();
|
||||
|
||||
@@ -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);
|
||||
BeanDefinition definition = registry.getBeanDefinition(beanName);
|
||||
return definition;
|
||||
@@ -167,12 +162,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;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -182,8 +174,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();
|
||||
|
||||
@@ -194,13 +185,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) {
|
||||
@@ -245,12 +234,11 @@ class ImportsContextCustomizer implements ContextCustomizer {
|
||||
Set<Class<?>> seen = new HashSet<Class<?>>();
|
||||
collectClassAnnotations(testClass, annotations, seen);
|
||||
Set<Object> determinedImports = determineImports(annotations, testClass);
|
||||
this.key = Collections.<Object>unmodifiableSet(
|
||||
(determinedImports != null) ? determinedImports : annotations);
|
||||
this.key = Collections
|
||||
.<Object>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()) {
|
||||
@@ -262,13 +250,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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -282,15 +269,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<Object>();
|
||||
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;
|
||||
}
|
||||
@@ -307,12 +291,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)) {
|
||||
@@ -332,9 +314,7 @@ 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);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -35,15 +35,13 @@ import org.springframework.util.ClassUtils;
|
||||
*/
|
||||
final class SpringBootConfigurationFinder {
|
||||
|
||||
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 ClassPathScanningCandidateComponentProvider scanner;
|
||||
|
||||
SpringBootConfigurationFinder() {
|
||||
this.scanner = new ClassPathScanningCandidateComponentProvider(false);
|
||||
this.scanner.addIncludeFilter(
|
||||
new AnnotationTypeFilter(SpringBootConfiguration.class));
|
||||
this.scanner.addIncludeFilter(new AnnotationTypeFilter(SpringBootConfiguration.class));
|
||||
this.scanner.setResourcePattern("*.class");
|
||||
}
|
||||
|
||||
@@ -67,10 +65,8 @@ final class SpringBootConfigurationFinder {
|
||||
Set<BeanDefinition> components = this.scanner.findCandidateComponents(source);
|
||||
if (!components.isEmpty()) {
|
||||
Assert.state(components.size() == 1,
|
||||
"Found multiple @SpringBootConfiguration annotated classes "
|
||||
+ components);
|
||||
return ClassUtils.resolveClassName(
|
||||
components.iterator().next().getBeanClassName(), null);
|
||||
"Found multiple @SpringBootConfiguration annotated classes " + components);
|
||||
return ClassUtils.resolveClassName(components.iterator().next().getBeanClassName(), null);
|
||||
}
|
||||
source = getParentPackage(source);
|
||||
}
|
||||
|
||||
@@ -89,8 +89,7 @@ public class SpringBootContextLoader extends AbstractContextLoader {
|
||||
}
|
||||
|
||||
@Override
|
||||
public ApplicationContext loadContext(MergedContextConfiguration config)
|
||||
throws Exception {
|
||||
public ApplicationContext loadContext(MergedContextConfiguration config) throws Exception {
|
||||
SpringApplication application = getSpringApplication();
|
||||
application.setMainApplicationClass(config.getTestClass());
|
||||
application.setSources(getSources(config));
|
||||
@@ -98,16 +97,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.setWebEnvironment(true);
|
||||
if (!isEmbeddedWebEnvironment(config)) {
|
||||
@@ -135,17 +131,16 @@ public class SpringBootContextLoader extends AbstractContextLoader {
|
||||
Set<Object> sources = new LinkedHashSet<Object>();
|
||||
sources.addAll(Arrays.asList(mergedConfig.getClasses()));
|
||||
sources.addAll(Arrays.asList(mergedConfig.getLocations()));
|
||||
Assert.state(!sources.isEmpty(), "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(!sources.isEmpty(),
|
||||
"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() + ").");
|
||||
return sources;
|
||||
}
|
||||
|
||||
private void setActiveProfiles(ConfigurableEnvironment environment,
|
||||
String[] profiles) {
|
||||
EnvironmentTestUtils.addEnvironment(environment, "spring.profiles.active="
|
||||
+ StringUtils.arrayToCommaDelimitedString(profiles));
|
||||
private void setActiveProfiles(ConfigurableEnvironment environment, String[] profiles) {
|
||||
EnvironmentTestUtils.addEnvironment(environment,
|
||||
"spring.profiles.active=" + StringUtils.arrayToCommaDelimitedString(profiles));
|
||||
}
|
||||
|
||||
protected String[] getInlinedProperties(MergedContextConfiguration config) {
|
||||
@@ -165,22 +160,21 @@ public class SpringBootContextLoader extends AbstractContextLoader {
|
||||
|
||||
private boolean hasCustomServerPort(List<String> properties) {
|
||||
PropertySources sources = convertToPropertySources(properties);
|
||||
RelaxedPropertyResolver resolver = new RelaxedPropertyResolver(
|
||||
new PropertySourcesPropertyResolver(sources), "server.");
|
||||
RelaxedPropertyResolver resolver = new RelaxedPropertyResolver(new PropertySourcesPropertyResolver(sources),
|
||||
"server.");
|
||||
return resolver.containsProperty("port");
|
||||
}
|
||||
|
||||
private PropertySources convertToPropertySources(List<String> properties) {
|
||||
Map<String, Object> source = TestPropertySourceUtils
|
||||
.convertInlinedPropertiesToMap(
|
||||
properties.toArray(new String[properties.size()]));
|
||||
.convertInlinedPropertiesToMap(properties.toArray(new String[properties.size()]));
|
||||
MutablePropertySources sources = new MutablePropertySources();
|
||||
sources.addFirst(new MapPropertySource("inline", source));
|
||||
return sources;
|
||||
}
|
||||
|
||||
private List<ApplicationContextInitializer<?>> getInitializers(
|
||||
MergedContextConfiguration config, SpringApplication application) {
|
||||
private List<ApplicationContextInitializer<?>> getInitializers(MergedContextConfiguration config,
|
||||
SpringApplication application) {
|
||||
List<ApplicationContextInitializer<?>> initializers = new ArrayList<ApplicationContextInitializer<?>>();
|
||||
for (ContextCustomizer contextCustomizer : config.getContextCustomizers()) {
|
||||
initializers.add(new ContextCustomizerAdapter(contextCustomizer, config));
|
||||
@@ -191,8 +185,7 @@ public class SpringBootContextLoader extends AbstractContextLoader {
|
||||
initializers.add(BeanUtils.instantiate(initializerClass));
|
||||
}
|
||||
if (config.getParent() != null) {
|
||||
initializers.add(new ParentContextApplicationContextInitializer(
|
||||
config.getParentApplicationContext()));
|
||||
initializers.add(new ParentContextApplicationContextInitializer(config.getParentApplicationContext()));
|
||||
}
|
||||
return initializers;
|
||||
}
|
||||
@@ -203,8 +196,8 @@ public class SpringBootContextLoader extends AbstractContextLoader {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
SpringBootTest annotation = AnnotatedElementUtils
|
||||
.findMergedAnnotation(config.getTestClass(), SpringBootTest.class);
|
||||
SpringBootTest annotation = AnnotatedElementUtils.findMergedAnnotation(config.getTestClass(),
|
||||
SpringBootTest.class);
|
||||
if (annotation != null && annotation.webEnvironment().isEmbedded()) {
|
||||
return true;
|
||||
}
|
||||
@@ -212,12 +205,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);
|
||||
}
|
||||
}
|
||||
@@ -232,14 +223,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
|
||||
@@ -259,21 +249,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));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -289,8 +276,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;
|
||||
}
|
||||
|
||||
@@ -74,8 +74,7 @@ public class SpringBootTestContextBootstrapper extends DefaultTestContextBootstr
|
||||
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() {
|
||||
@@ -95,8 +94,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);
|
||||
}
|
||||
@@ -115,8 +113,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<Class<?>>();
|
||||
combined.addAll(Arrays.asList(classes));
|
||||
if (configAttributes.getClasses() != null) {
|
||||
@@ -126,31 +123,24 @@ 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);
|
||||
List<String> propertySourceProperties = getAndProcessPropertySourceProperties(mergedConfig);
|
||||
mergedConfig = createModifiedConfig(mergedConfig, classes,
|
||||
propertySourceProperties
|
||||
.toArray(new String[propertySourceProperties.size()]));
|
||||
propertySourceProperties.toArray(new String[propertySourceProperties.size()]));
|
||||
WebEnvironment webEnvironment = getWebEnvironment(mergedConfig.getTestClass());
|
||||
if (webEnvironment != null && isWebEnvironmentSupported(mergedConfig)) {
|
||||
if (webEnvironment.isEmbedded() || (webEnvironment == WebEnvironment.MOCK
|
||||
&& hasWebEnvironmentClasses())) {
|
||||
if (webEnvironment.isEmbedded() || (webEnvironment == WebEnvironment.MOCK && hasWebEnvironmentClasses())) {
|
||||
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);
|
||||
}
|
||||
}
|
||||
return mergedConfig;
|
||||
@@ -158,22 +148,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<Class<?>>(
|
||||
Arrays.asList(attributes.getClasses()));
|
||||
ContextConfigurationAttributes attributes = new ContextConfigurationAttributes(candidateConfig.getTestClass(),
|
||||
configuration);
|
||||
Set<Class<?>> configurationClasses = new HashSet<Class<?>>(Arrays.asList(attributes.getClasses()));
|
||||
for (Class<?> candidate : candidateConfig.getClasses()) {
|
||||
if (configurationClasses.contains(candidate)) {
|
||||
return true;
|
||||
@@ -191,20 +178,15 @@ public class SpringBootTestContextBootstrapper extends DefaultTestContextBootstr
|
||||
return true;
|
||||
}
|
||||
|
||||
protected Class<?>[] getOrFindConfigurationClasses(
|
||||
MergedContextConfiguration mergedConfig) {
|
||||
protected Class<?>[] getOrFindConfigurationClasses(MergedContextConfiguration mergedConfig) {
|
||||
Class<?>[] classes = mergedConfig.getClasses();
|
||||
if (containsNonTestComponent(classes) || mergedConfig.hasLocations()) {
|
||||
return classes;
|
||||
}
|
||||
Class<?> found = new SpringBootConfigurationFinder()
|
||||
.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());
|
||||
Class<?> found = new SpringBootConfigurationFinder().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());
|
||||
return merge(found, classes);
|
||||
}
|
||||
|
||||
@@ -224,8 +206,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<String>(
|
||||
Arrays.asList(mergedConfig.getPropertySourceProperties()));
|
||||
String differentiator = getDifferentiatorPropertySourceProperty();
|
||||
@@ -253,8 +234,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);
|
||||
@@ -300,13 +280,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);
|
||||
}
|
||||
|
||||
@@ -316,10 +294,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());
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -330,13 +307,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());
|
||||
|
||||
@@ -45,8 +45,8 @@ class SpringBootTestContextCustomizer 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);
|
||||
}
|
||||
@@ -60,8 +60,7 @@ class SpringBootTestContextCustomizer implements ContextCustomizer {
|
||||
|
||||
}
|
||||
|
||||
private void registerTestRestTemplate(ConfigurableApplicationContext context,
|
||||
BeanDefinitionRegistry registry) {
|
||||
private void registerTestRestTemplate(ConfigurableApplicationContext context, BeanDefinitionRegistry registry) {
|
||||
registry.registerBeanDefinition(TestRestTemplate.class.getName(),
|
||||
new RootBeanDefinition(TestRestTemplateFactory.class));
|
||||
}
|
||||
@@ -82,8 +81,7 @@ class SpringBootTestContextCustomizer 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 = {};
|
||||
|
||||
@@ -92,14 +90,13 @@ class SpringBootTestContextCustomizer implements ContextCustomizer {
|
||||
private TestRestTemplate object;
|
||||
|
||||
@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.build(), 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.object = template;
|
||||
}
|
||||
@@ -115,8 +112,7 @@ class SpringBootTestContextCustomizer implements ContextCustomizer {
|
||||
}
|
||||
}
|
||||
|
||||
private RestTemplateBuilder getRestTemplateBuilder(
|
||||
ApplicationContext applicationContext) {
|
||||
private RestTemplateBuilder getRestTemplateBuilder(ApplicationContext applicationContext) {
|
||||
try {
|
||||
return applicationContext.getBean(RestTemplateBuilder.class);
|
||||
}
|
||||
|
||||
@@ -34,8 +34,7 @@ class SpringBootTestContextCustomizerFactory implements ContextCustomizerFactory
|
||||
@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 SpringBootTestContextCustomizer();
|
||||
}
|
||||
return null;
|
||||
|
||||
@@ -32,8 +32,7 @@ class ExcludeFilterContextCustomizer implements ContextCustomizer {
|
||||
@Override
|
||||
public void customizeContext(ConfigurableApplicationContext context,
|
||||
MergedContextConfiguration mergedContextConfiguration) {
|
||||
context.getBeanFactory().registerSingleton(TestTypeExcludeFilter.class.getName(),
|
||||
new TestTypeExcludeFilter());
|
||||
context.getBeanFactory().registerSingleton(TestTypeExcludeFilter.class.getName(), new TestTypeExcludeFilter());
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
@@ -36,8 +36,8 @@ class TestTypeExcludeFilter extends TypeExcludeFilter {
|
||||
private static final String[] METHOD_ANNOTATIONS = { "org.junit.Test" };
|
||||
|
||||
@Override
|
||||
public boolean match(MetadataReader metadataReader,
|
||||
MetadataReaderFactory metadataReaderFactory) throws IOException {
|
||||
public boolean match(MetadataReader metadataReader, MetadataReaderFactory metadataReaderFactory)
|
||||
throws IOException {
|
||||
if (isTestConfiguration(metadataReader)) {
|
||||
return true;
|
||||
}
|
||||
@@ -47,8 +47,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;
|
||||
}
|
||||
}
|
||||
@@ -60,8 +59,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) {
|
||||
|
||||
@@ -311,8 +311,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)");
|
||||
}
|
||||
|
||||
@@ -323,8 +322,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
|
||||
@@ -334,8 +332,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);
|
||||
}
|
||||
@@ -347,8 +344,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
|
||||
@@ -361,8 +357,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;
|
||||
}
|
||||
@@ -380,23 +375,20 @@ public abstract class AbstractJsonMarshalTester<T> {
|
||||
});
|
||||
}
|
||||
|
||||
public void initFields(final Object testInstance,
|
||||
final ObjectFactory<M> marshaller) {
|
||||
public void initFields(final Object testInstance, final ObjectFactory<M> marshaller) {
|
||||
Assert.notNull(testInstance, "TestInstance must not be null");
|
||||
Assert.notNull(marshaller, "Marshaller must not be null");
|
||||
ReflectionUtils.doWithFields(testInstance.getClass(), new FieldCallback() {
|
||||
|
||||
@Override
|
||||
public void doWith(Field field)
|
||||
throws IllegalArgumentException, IllegalAccessException {
|
||||
public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException {
|
||||
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);
|
||||
@@ -408,12 +400,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);
|
||||
|
||||
}
|
||||
|
||||
|
||||
@@ -94,8 +94,7 @@ public class BasicJsonTester {
|
||||
* @param type the type under test
|
||||
* @since 1.4.1
|
||||
*/
|
||||
protected final void initialize(Class<?> resourceLoadClass, Charset charset,
|
||||
ResolvableType type) {
|
||||
protected final void initialize(Class<?> resourceLoadClass, Charset charset, ResolvableType type) {
|
||||
if (this.loader == null) {
|
||||
this.loader = new JsonLoader(resourceLoadClass, charset);
|
||||
}
|
||||
|
||||
@@ -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<URL>();
|
||||
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<Object>(resourceLoadClass, type, marshaller);
|
||||
}
|
||||
|
||||
|
||||
@@ -79,13 +79,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;
|
||||
@@ -93,8 +91,7 @@ public class JacksonTester<T> extends AbstractJsonMarshalTester<T> {
|
||||
}
|
||||
|
||||
@Override
|
||||
protected T readObject(InputStream inputStream, ResolvableType type)
|
||||
throws IOException {
|
||||
protected T readObject(InputStream inputStream, ResolvableType type) throws IOException {
|
||||
return getObjectReader(type).readValue(inputStream);
|
||||
}
|
||||
|
||||
@@ -146,8 +143,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);
|
||||
}
|
||||
|
||||
@@ -158,8 +154,7 @@ public class JacksonTester<T> extends AbstractJsonMarshalTester<T> {
|
||||
* @return the new instance
|
||||
*/
|
||||
public JacksonTester<T> forView(Class<?> view) {
|
||||
return new JacksonTester<T>(this.getResourceLoadClass(), this.getType(),
|
||||
this.objectMapper, view);
|
||||
return new JacksonTester<T>(this.getResourceLoadClass(), this.getType(), this.objectMapper, view);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -172,8 +167,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<Object>(resourceLoadClass, type, marshaller);
|
||||
}
|
||||
|
||||
@@ -74,8 +74,7 @@ public final class JsonContent<T> implements AssertProvider<JsonContentAssert> {
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "JsonContent " + this.json
|
||||
+ ((this.type != null) ? " created from " + this.type : "");
|
||||
return "JsonContent " + this.json + ((this.type != null) ? " created from " + this.type : "");
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -68,8 +68,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) {
|
||||
super(json, JsonContentAssert.class);
|
||||
this.loader = new JsonLoader(resourceLoadClass, charset);
|
||||
}
|
||||
@@ -198,8 +197,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));
|
||||
}
|
||||
@@ -212,8 +210,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));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -262,8 +259,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));
|
||||
}
|
||||
@@ -276,8 +272,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));
|
||||
}
|
||||
@@ -313,8 +308,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));
|
||||
}
|
||||
|
||||
@@ -325,8 +319,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));
|
||||
}
|
||||
@@ -341,8 +334,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));
|
||||
}
|
||||
@@ -355,8 +347,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));
|
||||
}
|
||||
@@ -392,8 +383,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));
|
||||
}
|
||||
@@ -507,8 +497,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));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -534,8 +523,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));
|
||||
}
|
||||
@@ -598,8 +586,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));
|
||||
}
|
||||
@@ -612,8 +599,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));
|
||||
}
|
||||
@@ -625,8 +611,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));
|
||||
}
|
||||
@@ -638,8 +623,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));
|
||||
}
|
||||
@@ -651,8 +635,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));
|
||||
}
|
||||
@@ -664,8 +647,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));
|
||||
}
|
||||
@@ -680,8 +662,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));
|
||||
}
|
||||
@@ -694,8 +675,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));
|
||||
}
|
||||
@@ -707,8 +687,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));
|
||||
}
|
||||
@@ -732,8 +711,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));
|
||||
}
|
||||
@@ -745,8 +723,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));
|
||||
}
|
||||
@@ -775,8 +752,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;
|
||||
}
|
||||
@@ -790,8 +766,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;
|
||||
}
|
||||
@@ -805,8 +780,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;
|
||||
}
|
||||
@@ -820,8 +794,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;
|
||||
}
|
||||
@@ -834,8 +807,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;
|
||||
}
|
||||
@@ -849,8 +821,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;
|
||||
}
|
||||
@@ -865,8 +836,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;
|
||||
}
|
||||
@@ -880,8 +850,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;
|
||||
}
|
||||
@@ -894,8 +863,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));
|
||||
}
|
||||
|
||||
@@ -907,10 +875,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"));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -921,10 +888,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"));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -935,10 +900,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"));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -951,10 +914,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"));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -968,15 +929,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);
|
||||
@@ -984,14 +943,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) {
|
||||
@@ -1002,14 +959,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) {
|
||||
@@ -1053,8 +1008,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);
|
||||
@@ -1122,9 +1076,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))));
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -54,8 +54,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();
|
||||
}
|
||||
@@ -88,8 +87,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);
|
||||
|
||||
@@ -62,8 +62,7 @@ public final class ObjectContent<T> implements AssertProvider<ObjectContentAsser
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "ObjectContent " + this.object
|
||||
+ ((this.type != null) ? " created from " + this.type : "");
|
||||
return "ObjectContent " + this.object + ((this.type != null) ? " created from " + this.type : "");
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -63,8 +63,7 @@ class DefinitionsParser {
|
||||
ReflectionUtils.doWithFields(source, new FieldCallback() {
|
||||
|
||||
@Override
|
||||
public void doWith(Field field)
|
||||
throws IllegalArgumentException, IllegalAccessException {
|
||||
public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException {
|
||||
parseElement(field);
|
||||
}
|
||||
|
||||
@@ -72,28 +71,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");
|
||||
}
|
||||
@@ -101,22 +95,18 @@ 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);
|
||||
if (element instanceof Field) {
|
||||
@@ -125,8 +115,7 @@ class DefinitionsParser {
|
||||
}
|
||||
}
|
||||
|
||||
private Set<ResolvableType> getOrDeduceTypes(AnnotatedElement element,
|
||||
Class<?>[] value) {
|
||||
private Set<ResolvableType> getOrDeduceTypes(AnnotatedElement element, Class<?>[] value) {
|
||||
Set<ResolvableType> types = new LinkedHashSet<ResolvableType>();
|
||||
for (Class<?> clazz : value) {
|
||||
types.add(ResolvableType.forClass(clazz));
|
||||
|
||||
@@ -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() {
|
||||
|
||||
@@ -53,8 +53,7 @@ public enum MockReset {
|
||||
*/
|
||||
NONE;
|
||||
|
||||
private static final boolean MOCKITO_PRESENT = ClassUtils
|
||||
.isPresent("org.mockito.internal.util.MockUtil", null);
|
||||
private static final boolean MOCKITO_PRESENT = ClassUtils.isPresent("org.mockito.internal.util.MockUtil", null);
|
||||
|
||||
/**
|
||||
* Create {@link MockSettings settings} to be used with mocks where reset should occur
|
||||
|
||||
@@ -60,8 +60,8 @@ class MockitoAopProxyTargetInterceptor implements MethodInterceptor {
|
||||
public Object invoke(MethodInvocation invocation) throws Throwable {
|
||||
if (this.verification.isVerifying()) {
|
||||
this.verification.replaceVerifyMock(this.source, this.target);
|
||||
return AopUtils.invokeJoinpointUsingReflection(this.target,
|
||||
invocation.getMethod(), invocation.getArguments());
|
||||
return AopUtils.invokeJoinpointUsingReflection(this.target, invocation.getMethod(),
|
||||
invocation.getArguments());
|
||||
}
|
||||
return invocation.proceed();
|
||||
}
|
||||
@@ -113,8 +113,7 @@ class MockitoAopProxyTargetInterceptor implements MethodInterceptor {
|
||||
if (mode instanceof MockAwareVerificationMode) {
|
||||
MockAwareVerificationMode mockAwareMode = (MockAwareVerificationMode) mode;
|
||||
if (mockAwareMode.getMock() == source) {
|
||||
mode = MockitoApi.get().createMockAwareVerificationMode(
|
||||
target, mockAwareMode);
|
||||
mode = MockitoApi.get().createMockAwareVerificationMode(target, mockAwareMode);
|
||||
}
|
||||
}
|
||||
resetVerificationStarted(mode);
|
||||
|
||||
@@ -71,8 +71,7 @@ abstract class MockitoApi {
|
||||
* @param storage the storage to use
|
||||
* @param matchers the matchers to set
|
||||
*/
|
||||
public abstract void reportMatchers(ArgumentMatcherStorage storage,
|
||||
List<LocalizedMatcher> matchers);
|
||||
public abstract void reportMatchers(ArgumentMatcherStorage storage, List<LocalizedMatcher> matchers);
|
||||
|
||||
/**
|
||||
* Create a new {@link MockAwareVerificationMode} instance.
|
||||
@@ -80,8 +79,7 @@ abstract class MockitoApi {
|
||||
* @param mode the verification mode
|
||||
* @return a new {@link MockAwareVerificationMode} instance
|
||||
*/
|
||||
public abstract MockAwareVerificationMode createMockAwareVerificationMode(Object mock,
|
||||
VerificationMode mode);
|
||||
public abstract MockAwareVerificationMode createMockAwareVerificationMode(Object mock, VerificationMode mode);
|
||||
|
||||
/**
|
||||
* Return the {@link Answer} for a given {@link Answers} value.
|
||||
@@ -124,23 +122,20 @@ abstract class MockitoApi {
|
||||
MockUtil mockUtil = new MockUtil();
|
||||
InternalMockHandler<?> handler = mockUtil.getMockHandler(mock);
|
||||
InvocationContainer container = handler.getInvocationContainer();
|
||||
Field field = ReflectionUtils.findField(container.getClass(),
|
||||
"mockingProgress");
|
||||
Field field = ReflectionUtils.findField(container.getClass(), "mockingProgress");
|
||||
ReflectionUtils.makeAccessible(field);
|
||||
return (MockingProgress) ReflectionUtils.getField(field, container);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void reportMatchers(ArgumentMatcherStorage storage,
|
||||
List<LocalizedMatcher> matchers) {
|
||||
public void reportMatchers(ArgumentMatcherStorage storage, List<LocalizedMatcher> matchers) {
|
||||
for (LocalizedMatcher matcher : matchers) {
|
||||
storage.reportMatcher(matcher);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public MockAwareVerificationMode createMockAwareVerificationMode(Object mock,
|
||||
VerificationMode mode) {
|
||||
public MockAwareVerificationMode createMockAwareVerificationMode(Object mock, VerificationMode mode) {
|
||||
return new MockAwareVerificationMode(mock, mode);
|
||||
}
|
||||
|
||||
@@ -167,34 +162,27 @@ abstract class MockitoApi {
|
||||
private final Constructor<MockAwareVerificationMode> mockAwareVerificationModeConstructor;
|
||||
|
||||
Mockito2Api() {
|
||||
this.getMockSettingsMethod = ReflectionUtils.findMethod(MockUtil.class,
|
||||
"getMockSettings", Object.class);
|
||||
this.mockingProgressMethod = ReflectionUtils
|
||||
.findMethod(ThreadSafeMockingProgress.class, "mockingProgress");
|
||||
this.reportMatcherMethod = ReflectionUtils.findMethod(
|
||||
ArgumentMatcherStorage.class, "reportMatcher", ArgumentMatcher.class);
|
||||
this.getMatcherMethod = ReflectionUtils.findMethod(LocalizedMatcher.class,
|
||||
"getMatcher");
|
||||
this.mockAwareVerificationModeConstructor = ClassUtils
|
||||
.getConstructorIfAvailable(MockAwareVerificationMode.class,
|
||||
Object.class, VerificationMode.class, Set.class);
|
||||
this.getMockSettingsMethod = ReflectionUtils.findMethod(MockUtil.class, "getMockSettings", Object.class);
|
||||
this.mockingProgressMethod = ReflectionUtils.findMethod(ThreadSafeMockingProgress.class, "mockingProgress");
|
||||
this.reportMatcherMethod = ReflectionUtils.findMethod(ArgumentMatcherStorage.class, "reportMatcher",
|
||||
ArgumentMatcher.class);
|
||||
this.getMatcherMethod = ReflectionUtils.findMethod(LocalizedMatcher.class, "getMatcher");
|
||||
this.mockAwareVerificationModeConstructor = ClassUtils.getConstructorIfAvailable(
|
||||
MockAwareVerificationMode.class, Object.class, VerificationMode.class, Set.class);
|
||||
}
|
||||
|
||||
@Override
|
||||
public MockCreationSettings<?> getMockSettings(Object mock) {
|
||||
return (MockCreationSettings<?>) ReflectionUtils
|
||||
.invokeMethod(this.getMockSettingsMethod, null, mock);
|
||||
return (MockCreationSettings<?>) ReflectionUtils.invokeMethod(this.getMockSettingsMethod, null, mock);
|
||||
}
|
||||
|
||||
@Override
|
||||
public MockingProgress mockingProgress(Object mock) {
|
||||
return (MockingProgress) ReflectionUtils
|
||||
.invokeMethod(this.mockingProgressMethod, null);
|
||||
return (MockingProgress) ReflectionUtils.invokeMethod(this.mockingProgressMethod, null);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void reportMatchers(ArgumentMatcherStorage storage,
|
||||
List<LocalizedMatcher> matchers) {
|
||||
public void reportMatchers(ArgumentMatcherStorage storage, List<LocalizedMatcher> matchers) {
|
||||
for (LocalizedMatcher matcher : matchers) {
|
||||
ReflectionUtils.invokeMethod(this.reportMatcherMethod, storage,
|
||||
ReflectionUtils.invokeMethod(this.getMatcherMethod, matcher));
|
||||
@@ -202,12 +190,10 @@ abstract class MockitoApi {
|
||||
}
|
||||
|
||||
@Override
|
||||
public MockAwareVerificationMode createMockAwareVerificationMode(Object mock,
|
||||
VerificationMode mode) {
|
||||
public MockAwareVerificationMode createMockAwareVerificationMode(Object mock, VerificationMode mode) {
|
||||
if (this.mockAwareVerificationModeConstructor != null) {
|
||||
// Later 2.0 releases include a listener set
|
||||
return BeanUtils.instantiateClass(
|
||||
this.mockAwareVerificationModeConstructor, mock, mode,
|
||||
return BeanUtils.instantiateClass(this.mockAwareVerificationModeConstructor, mock, mode,
|
||||
Collections.emptySet());
|
||||
}
|
||||
return new MockAwareVerificationMode(mock, mode);
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -77,16 +77,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 final Set<Definition> definitions;
|
||||
|
||||
@@ -126,16 +124,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)) {
|
||||
@@ -148,19 +143,15 @@ public class MockitoPostProcessor extends InstantiationAwareBeanPostProcessorAda
|
||||
}
|
||||
}
|
||||
|
||||
private Set<Class<?>> getConfigurationClasses(
|
||||
ConfigurableListableBeanFactory beanFactory) {
|
||||
private Set<Class<?>> getConfigurationClasses(ConfigurableListableBeanFactory beanFactory) {
|
||||
Set<Class<?>> configurationClasses = new LinkedHashSet<Class<?>>();
|
||||
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<String, BeanDefinition>();
|
||||
for (String beanName : beanFactory.getBeanDefinitionNames()) {
|
||||
BeanDefinition definition = beanFactory.getBeanDefinition(beanName);
|
||||
@@ -171,8 +162,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);
|
||||
}
|
||||
@@ -181,13 +172,12 @@ 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);
|
||||
beanDefinition.getConstructorArgumentValues().addIndexedArgumentValue(1,
|
||||
beanName);
|
||||
beanDefinition.getConstructorArgumentValues().addIndexedArgumentValue(1, beanName);
|
||||
if (registry.containsBeanDefinition(transformedBeanName)) {
|
||||
registry.removeBeanDefinition(transformedBeanName);
|
||||
}
|
||||
@@ -202,13 +192,11 @@ 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());
|
||||
definition.setFactoryBeanName(BEAN_NAME);
|
||||
definition.setFactoryMethodName("createMock");
|
||||
definition.getConstructorArgumentValues().addIndexedArgumentValue(0,
|
||||
mockDefinition);
|
||||
definition.getConstructorArgumentValues().addIndexedArgumentValue(0, mockDefinition);
|
||||
if (mockDefinition.getQualifier() != null) {
|
||||
mockDefinition.getQualifier().applyTo(definition);
|
||||
}
|
||||
@@ -225,9 +213,8 @@ public class MockitoPostProcessor extends InstantiationAwareBeanPostProcessorAda
|
||||
return mockDefinition.createMock(name + " bean");
|
||||
}
|
||||
|
||||
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();
|
||||
}
|
||||
@@ -238,14 +225,12 @@ public class MockitoPostProcessor extends InstantiationAwareBeanPostProcessorAda
|
||||
if (existingBeans.size() == 1) {
|
||||
return existingBeans.iterator().next();
|
||||
}
|
||||
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 registerSpy(ConfigurableListableBeanFactory beanFactory,
|
||||
BeanDefinitionRegistry registry, SpyDefinition definition, Field field) {
|
||||
private void registerSpy(ConfigurableListableBeanFactory beanFactory, BeanDefinitionRegistry registry,
|
||||
SpyDefinition definition, Field field) {
|
||||
String[] existingBeans = getExistingBeans(beanFactory, definition.getTypeToSpy());
|
||||
if (ObjectUtils.isEmpty(existingBeans)) {
|
||||
createSpy(registry, definition, field);
|
||||
@@ -255,12 +240,10 @@ public class MockitoPostProcessor extends InstantiationAwareBeanPostProcessorAda
|
||||
}
|
||||
}
|
||||
|
||||
private Set<String> findCandidateBeans(ConfigurableListableBeanFactory beanFactory,
|
||||
MockDefinition mockDefinition) {
|
||||
private Set<String> findCandidateBeans(ConfigurableListableBeanFactory beanFactory, MockDefinition mockDefinition) {
|
||||
QualifierDefinition qualifier = mockDefinition.getQualifier();
|
||||
Set<String> candidates = new TreeSet<String>();
|
||||
for (String candidate : getExistingBeans(beanFactory,
|
||||
mockDefinition.getTypeToMock())) {
|
||||
for (String candidate : getExistingBeans(beanFactory, mockDefinition.getTypeToMock())) {
|
||||
if (qualifier == null || qualifier.matches(beanFactory, candidate)) {
|
||||
candidates.add(candidate);
|
||||
}
|
||||
@@ -268,16 +251,13 @@ public class MockitoPostProcessor extends InstantiationAwareBeanPostProcessorAda
|
||||
return candidates;
|
||||
}
|
||||
|
||||
private String[] getExistingBeans(ConfigurableListableBeanFactory beanFactory,
|
||||
ResolvableType type) {
|
||||
Set<String> beans = new LinkedHashSet<String>(
|
||||
Arrays.asList(beanFactory.getBeanNamesForType(type)));
|
||||
private String[] getExistingBeans(ConfigurableListableBeanFactory beanFactory, ResolvableType type) {
|
||||
Set<String> beans = new LinkedHashSet<String>(Arrays.asList(beanFactory.getBeanNamesForType(type)));
|
||||
String resolvedTypeName = type.resolve(Object.class).getName();
|
||||
for (String beanName : beanFactory.getBeanNamesForType(FactoryBean.class)) {
|
||||
beanName = BeanFactoryUtils.transformedBeanName(beanName);
|
||||
BeanDefinition beanDefinition = beanFactory.getBeanDefinition(beanName);
|
||||
if (resolvedTypeName
|
||||
.equals(beanDefinition.getAttribute(FACTORY_BEAN_OBJECT_TYPE))) {
|
||||
if (resolvedTypeName.equals(beanDefinition.getAttribute(FACTORY_BEAN_OBJECT_TYPE))) {
|
||||
beans.add(beanName);
|
||||
}
|
||||
}
|
||||
@@ -298,25 +278,20 @@ public class MockitoPostProcessor extends InstantiationAwareBeanPostProcessorAda
|
||||
}
|
||||
}
|
||||
|
||||
private void createSpy(BeanDefinitionRegistry registry, SpyDefinition definition,
|
||||
Field field) {
|
||||
RootBeanDefinition beanDefinition = new RootBeanDefinition(
|
||||
definition.getTypeToSpy().resolve());
|
||||
String beanName = this.beanNameGenerator.generateBeanName(beanDefinition,
|
||||
registry);
|
||||
private void createSpy(BeanDefinitionRegistry registry, SpyDefinition definition, Field field) {
|
||||
RootBeanDefinition beanDefinition = new RootBeanDefinition(definition.getTypeToSpy().resolve());
|
||||
String beanName = this.beanNameGenerator.generateBeanName(beanDefinition, registry);
|
||||
registry.registerBeanDefinition(beanName, beanDefinition);
|
||||
registerSpy(definition, field, beanName);
|
||||
}
|
||||
|
||||
private void registerSpies(BeanDefinitionRegistry registry, SpyDefinition definition,
|
||||
Field field, String[] existingBeans) {
|
||||
private void registerSpies(BeanDefinitionRegistry registry, SpyDefinition definition, Field field,
|
||||
String[] existingBeans) {
|
||||
try {
|
||||
registerSpy(definition, field,
|
||||
determineBeanName(existingBeans, definition, registry));
|
||||
registerSpy(definition, field, determineBeanName(existingBeans, definition, registry));
|
||||
}
|
||||
catch (RuntimeException ex) {
|
||||
throw new IllegalStateException(
|
||||
"Unable to register spy bean " + definition.getTypeToSpy(), ex);
|
||||
throw new IllegalStateException("Unable to register spy bean " + definition.getTypeToSpy(), ex);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -328,19 +303,17 @@ public class MockitoPostProcessor extends InstantiationAwareBeanPostProcessorAda
|
||||
if (existingBeans.length == 1) {
|
||||
return existingBeans[0];
|
||||
}
|
||||
return determinePrimaryCandidate(registry, existingBeans,
|
||||
definition.getTypeToSpy());
|
||||
return determinePrimaryCandidate(registry, existingBeans, definition.getTypeToSpy());
|
||||
}
|
||||
|
||||
private String determinePrimaryCandidate(BeanDefinitionRegistry registry,
|
||||
String[] candidateBeanNames, ResolvableType type) {
|
||||
private String determinePrimaryCandidate(BeanDefinitionRegistry registry, 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.length,
|
||||
throw new NoUniqueBeanDefinitionException(type.resolve(), candidateBeanNames.length,
|
||||
"more than one 'primary' bean found among candidates: "
|
||||
+ Arrays.asList(candidateBeanNames));
|
||||
}
|
||||
@@ -358,8 +331,7 @@ public class MockitoPostProcessor extends InstantiationAwareBeanPostProcessorAda
|
||||
}
|
||||
}
|
||||
|
||||
protected Object createSpyIfNecessary(Object bean, String beanName)
|
||||
throws BeansException {
|
||||
protected Object createSpyIfNecessary(Object bean, String beanName) throws BeansException {
|
||||
SpyDefinition definition = this.spies.get(beanName);
|
||||
if (definition != null) {
|
||||
bean = definition.createSpy(beanName, bean);
|
||||
@@ -368,14 +340,12 @@ public class MockitoPostProcessor extends InstantiationAwareBeanPostProcessorAda
|
||||
}
|
||||
|
||||
@Override
|
||||
public PropertyValues postProcessPropertyValues(PropertyValues pvs,
|
||||
PropertyDescriptor[] pds, final Object bean, String beanName)
|
||||
throws BeansException {
|
||||
public PropertyValues postProcessPropertyValues(PropertyValues pvs, PropertyDescriptor[] pds, final Object bean,
|
||||
String beanName) throws BeansException {
|
||||
ReflectionUtils.doWithFields(bean.getClass(), new FieldCallback() {
|
||||
|
||||
@Override
|
||||
public void doWith(Field field)
|
||||
throws IllegalArgumentException, IllegalAccessException {
|
||||
public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException {
|
||||
postProcessField(bean, field);
|
||||
}
|
||||
|
||||
@@ -392,13 +362,11 @@ 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, definition);
|
||||
}
|
||||
|
||||
private void inject(Field field, Object target, String beanName,
|
||||
Definition definition) {
|
||||
private void inject(Field field, Object target, String beanName, Definition definition) {
|
||||
try {
|
||||
field.setAccessible(true);
|
||||
Assert.state(ReflectionUtils.getField(field, target) == null,
|
||||
@@ -443,8 +411,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);
|
||||
}
|
||||
|
||||
@@ -456,13 +423,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);
|
||||
@@ -474,10 +439,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;
|
||||
}
|
||||
@@ -488,8 +451,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();
|
||||
|
||||
@@ -505,14 +467,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 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;
|
||||
}
|
||||
@@ -525,11 +485,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);
|
||||
|
||||
@@ -50,8 +50,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);
|
||||
}
|
||||
@@ -78,10 +78,8 @@ public class MockitoTestExecutionListener extends AbstractTestExecutionListener
|
||||
postProcessFields(testContext, new MockitoFieldHandler() {
|
||||
|
||||
@Override
|
||||
public void handle(MockitoField mockitoField,
|
||||
MockitoPostProcessor postProcessor) {
|
||||
postProcessor.inject(mockitoField.field, mockitoField.target,
|
||||
mockitoField.definition);
|
||||
public void handle(MockitoField mockitoField, MockitoPostProcessor postProcessor) {
|
||||
postProcessor.inject(mockitoField.field, mockitoField.target, mockitoField.definition);
|
||||
}
|
||||
|
||||
});
|
||||
@@ -91,13 +89,10 @@ public class MockitoTestExecutionListener extends AbstractTestExecutionListener
|
||||
postProcessFields(testContext, new MockitoFieldHandler() {
|
||||
|
||||
@Override
|
||||
public void handle(MockitoField mockitoField,
|
||||
MockitoPostProcessor postProcessor) {
|
||||
public void handle(MockitoField mockitoField, MockitoPostProcessor 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);
|
||||
}
|
||||
|
||||
});
|
||||
@@ -112,8 +107,7 @@ public class MockitoTestExecutionListener extends AbstractTestExecutionListener
|
||||
for (Definition definition : parser.getDefinitions()) {
|
||||
Field field = parser.getField(definition);
|
||||
if (field != null) {
|
||||
handler.handle(new MockitoField(field, testContext.getTestInstance(),
|
||||
definition), postProcessor);
|
||||
handler.handle(new MockitoField(field, testContext.getTestInstance(), definition), postProcessor);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -127,8 +121,7 @@ public class MockitoTestExecutionListener extends AbstractTestExecutionListener
|
||||
private final Set<Annotation> annotations = new LinkedHashSet<Annotation>();
|
||||
|
||||
@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);
|
||||
|
||||
@@ -56,12 +56,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<String>(
|
||||
Arrays.asList(beanFactory.getSingletonNames()));
|
||||
Set<String> instantiatedSingletons = new HashSet<String>(Arrays.asList(beanFactory.getSingletonNames()));
|
||||
for (String name : names) {
|
||||
BeanDefinition definition = beanFactory.getBeanDefinition(name);
|
||||
if (definition.isSingleton() && instantiatedSingletons.contains(name)) {
|
||||
|
||||
@@ -36,8 +36,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;
|
||||
@@ -71,9 +71,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) {
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -42,8 +42,7 @@ public abstract class EnvironmentTestUtils {
|
||||
* @param context the context with an environment to modify
|
||||
* @param pairs the name:value pairs
|
||||
*/
|
||||
public static void addEnvironment(ConfigurableApplicationContext context,
|
||||
String... pairs) {
|
||||
public static void addEnvironment(ConfigurableApplicationContext context, String... pairs) {
|
||||
addEnvironment(context.getEnvironment(), pairs);
|
||||
}
|
||||
|
||||
@@ -53,8 +52,7 @@ public abstract class EnvironmentTestUtils {
|
||||
* @param environment the environment to modify
|
||||
* @param pairs the name:value pairs
|
||||
*/
|
||||
public static void addEnvironment(ConfigurableEnvironment environment,
|
||||
String... pairs) {
|
||||
public static void addEnvironment(ConfigurableEnvironment environment, String... pairs) {
|
||||
addEnvironment("test", environment, pairs);
|
||||
}
|
||||
|
||||
@@ -65,8 +63,7 @@ public abstract class EnvironmentTestUtils {
|
||||
* @param name the property source name
|
||||
* @param pairs the name:value pairs
|
||||
*/
|
||||
public static void addEnvironment(String name, ConfigurableEnvironment environment,
|
||||
String... pairs) {
|
||||
public static void addEnvironment(String name, ConfigurableEnvironment environment, String... pairs) {
|
||||
MutablePropertySources sources = environment.getPropertySources();
|
||||
Map<String, Object> map = getOrAdd(sources, name);
|
||||
for (String pair : pairs) {
|
||||
@@ -78,8 +75,7 @@ public abstract class EnvironmentTestUtils {
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
private static Map<String, Object> getOrAdd(MutablePropertySources sources,
|
||||
String name) {
|
||||
private static Map<String, Object> getOrAdd(MutablePropertySources sources, String name) {
|
||||
if (sources.contains(name)) {
|
||||
return (Map<String, Object>) sources.get(name).getSource();
|
||||
}
|
||||
|
||||
@@ -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.size() > 0,
|
||||
"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.size() > 0, "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();
|
||||
}
|
||||
|
||||
|
||||
@@ -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;
|
||||
|
||||
|
||||
@@ -111,8 +111,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 RestTemplate(), username, password, httpClientOptions);
|
||||
}
|
||||
|
||||
@@ -125,22 +124,19 @@ public class TestRestTemplate {
|
||||
Assert.notNull(restTemplate, "RestTemplate must not be null");
|
||||
this.httpClientOptions = httpClientOptions;
|
||||
if (ClassUtils.isPresent("org.apache.http.client.config.RequestConfig", null)) {
|
||||
restTemplate.setRequestFactory(
|
||||
new CustomHttpComponentsClientHttpRequestFactory(httpClientOptions));
|
||||
restTemplate.setRequestFactory(new CustomHttpComponentsClientHttpRequestFactory(httpClientOptions));
|
||||
}
|
||||
addAuthentication(restTemplate, username, password);
|
||||
restTemplate.setErrorHandler(new NoOpResponseErrorHandler());
|
||||
this.restTemplate = restTemplate;
|
||||
}
|
||||
|
||||
private static RestTemplate buildRestTemplate(
|
||||
RestTemplateBuilder restTemplateBuilder) {
|
||||
private static RestTemplate buildRestTemplate(RestTemplateBuilder restTemplateBuilder) {
|
||||
Assert.notNull(restTemplateBuilder, "RestTemplateBuilder must not be null");
|
||||
return restTemplateBuilder.build();
|
||||
}
|
||||
|
||||
private void addAuthentication(RestTemplate restTemplate, String username,
|
||||
String password) {
|
||||
private void addAuthentication(RestTemplate restTemplate, String username, String password) {
|
||||
if (username == null) {
|
||||
return;
|
||||
}
|
||||
@@ -184,8 +180,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);
|
||||
}
|
||||
|
||||
@@ -202,8 +197,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);
|
||||
}
|
||||
|
||||
@@ -235,8 +230,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);
|
||||
}
|
||||
|
||||
@@ -253,8 +248,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);
|
||||
}
|
||||
|
||||
@@ -268,8 +263,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);
|
||||
}
|
||||
|
||||
@@ -283,8 +277,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);
|
||||
}
|
||||
|
||||
@@ -298,8 +291,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);
|
||||
}
|
||||
|
||||
@@ -332,8 +324,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);
|
||||
}
|
||||
|
||||
@@ -355,8 +346,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);
|
||||
}
|
||||
|
||||
@@ -397,8 +387,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);
|
||||
}
|
||||
|
||||
@@ -421,8 +411,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);
|
||||
}
|
||||
|
||||
@@ -441,10 +431,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);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -466,8 +454,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);
|
||||
}
|
||||
|
||||
@@ -490,9 +478,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);
|
||||
}
|
||||
|
||||
@@ -511,10 +498,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);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -531,8 +517,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);
|
||||
}
|
||||
|
||||
@@ -550,8 +535,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);
|
||||
}
|
||||
|
||||
@@ -588,8 +572,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);
|
||||
}
|
||||
|
||||
@@ -611,8 +595,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);
|
||||
}
|
||||
|
||||
@@ -631,10 +615,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);
|
||||
|
||||
}
|
||||
|
||||
@@ -660,8 +642,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);
|
||||
}
|
||||
|
||||
@@ -685,8 +666,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);
|
||||
}
|
||||
|
||||
@@ -700,8 +680,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);
|
||||
}
|
||||
|
||||
@@ -733,11 +712,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);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -757,11 +734,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);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -778,11 +753,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);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -806,11 +779,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);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -834,11 +805,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);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -861,11 +830,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);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -883,10 +850,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);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -906,10 +872,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);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -930,10 +895,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);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -954,10 +917,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);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -976,8 +937,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);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -1004,27 +964,22 @@ public class TestRestTemplate {
|
||||
restTemplate.setInterceptors(getRestTemplate().getInterceptors());
|
||||
restTemplate.setRequestFactory(getRestTemplate().getRequestFactory());
|
||||
restTemplate.setUriTemplateHandler(getRestTemplate().getUriTemplateHandler());
|
||||
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;
|
||||
}
|
||||
|
||||
@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;
|
||||
}
|
||||
@@ -1054,19 +1009,17 @@ 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) {
|
||||
public CustomHttpComponentsClientHttpRequestFactory(HttpClientOption[] httpClientOptions) {
|
||||
Set<HttpClientOption> options = new HashSet<TestRestTemplate.HttpClientOption>(
|
||||
Arrays.asList(httpClientOptions));
|
||||
this.cookieSpec = (options.contains(HttpClientOption.ENABLE_COOKIES)
|
||||
? CookieSpecs.STANDARD : CookieSpecs.IGNORE_COOKIES);
|
||||
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());
|
||||
@@ -1076,9 +1029,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) {
|
||||
@@ -1094,8 +1045,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();
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -71,8 +71,7 @@ public abstract class AbstractSpringBootTestEmbeddedWebEnvironmentTests {
|
||||
@Test
|
||||
public void runAndTestHttpEndpoint() {
|
||||
assertThat(this.port).isNotEqualTo(8080).isNotEqualTo(0);
|
||||
String body = new RestTemplate()
|
||||
.getForObject("http://localhost:" + this.port + "/", String.class);
|
||||
String body = new RestTemplate().getForObject("http://localhost:" + this.port + "/", String.class);
|
||||
assertThat(body).isEqualTo("Hello World");
|
||||
}
|
||||
|
||||
@@ -89,8 +88,7 @@ public abstract class AbstractSpringBootTestEmbeddedWebEnvironmentTests {
|
||||
|
||||
@Test
|
||||
public void validateWebApplicationContextIsSet() {
|
||||
assertThat(this.context).isSameAs(
|
||||
WebApplicationContextUtils.getWebApplicationContext(this.servletContext));
|
||||
assertThat(this.context).isSameAs(WebApplicationContextUtils.getWebApplicationContext(this.servletContext));
|
||||
}
|
||||
|
||||
protected static class AbstractConfig {
|
||||
|
||||
@@ -48,45 +48,37 @@ 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() throws Exception {
|
||||
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()
|
||||
throws Exception {
|
||||
public void getContextCustomizerWhenClassHasBeanMethodsShouldThrowException() throws Exception {
|
||||
this.thrown.expect(IllegalStateException.class);
|
||||
this.thrown.expectMessage("Test classes cannot include @Bean methods");
|
||||
this.factory.createContextCustomizer(TestWithImportAndBeanMethod.class, null);
|
||||
@@ -94,8 +86,7 @@ public class ImportsContextCustomizerFactoryTests {
|
||||
|
||||
@Test
|
||||
public void contextCustomizerImportsBeans() throws Exception {
|
||||
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();
|
||||
@@ -104,8 +95,8 @@ public class ImportsContextCustomizerFactoryTests {
|
||||
|
||||
@Test
|
||||
public void selfAnnotatingAnnotationDoesNotCauseStackOverflow() {
|
||||
assertThat(this.factory.createContextCustomizer(
|
||||
TestWithImportAndSelfAnnotatingAnnotation.class, null)).isNotNull();
|
||||
assertThat(this.factory.createContextCustomizer(TestWithImportAndSelfAnnotatingAnnotation.class, null))
|
||||
.isNotNull();
|
||||
}
|
||||
|
||||
static class TestWithNoImport {
|
||||
|
||||
@@ -45,38 +45,31 @@ public class ImportsContextCustomizerTests {
|
||||
@Test
|
||||
public void importSelectorsCouldUseAnyAnnotations() throws Exception {
|
||||
assertThat(new ImportsContextCustomizer(FirstImportSelectorAnnotatedClass.class))
|
||||
.isNotEqualTo(new ImportsContextCustomizer(
|
||||
SecondImportSelectorAnnotatedClass.class));
|
||||
.isNotEqualTo(new ImportsContextCustomizer(SecondImportSelectorAnnotatedClass.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void determinableImportSelector() throws Exception {
|
||||
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) {
|
||||
|
||||
@@ -65,8 +65,7 @@ public class SpringBootConfigurationFinderTests {
|
||||
|
||||
@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);
|
||||
}
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -74,8 +74,7 @@ public class SpringBootContextLoaderTests {
|
||||
|
||||
@Test
|
||||
public void environmentPropertiesAnotherSeparatorInValue() throws Exception {
|
||||
Map<String, Object> config = getEnvironmentProperties(
|
||||
AnotherSeparatorInValue.class);
|
||||
Map<String, Object> config = getEnvironmentProperties(AnotherSeparatorInValue.class);
|
||||
assertKey(config, "key", "my:Value");
|
||||
assertKey(config, "anotherKey", "another=Value");
|
||||
}
|
||||
@@ -89,14 +88,11 @@ public class SpringBootContextLoaderTests {
|
||||
assertKey(config, "variables", "foo=FOO\n bar=BAR");
|
||||
}
|
||||
|
||||
private Map<String, Object> getEnvironmentProperties(Class<?> testClass)
|
||||
throws Exception {
|
||||
TestContext context = new ExposedTestContextManager(testClass)
|
||||
.getExposedTestContext();
|
||||
MergedContextConfiguration config = (MergedContextConfiguration) ReflectionTestUtils
|
||||
.getField(context, "mergedContextConfiguration");
|
||||
return TestPropertySourceUtils
|
||||
.convertInlinedPropertiesToMap(config.getPropertySourceProperties());
|
||||
private Map<String, Object> getEnvironmentProperties(Class<?> testClass) throws Exception {
|
||||
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) {
|
||||
|
||||
@@ -44,8 +44,7 @@ public class SpringBootTestActiveProfileTests {
|
||||
|
||||
@Test
|
||||
public void profiles() throws Exception {
|
||||
assertThat(this.context.getEnvironment().getActiveProfiles())
|
||||
.containsExactly("override");
|
||||
assertThat(this.context.getEnvironment().getActiveProfiles()).containsExactly("override");
|
||||
}
|
||||
|
||||
@Configuration
|
||||
|
||||
@@ -39,13 +39,11 @@ import static org.assertj.core.api.Assertions.assertThat;
|
||||
@RunWith(SpringRunner.class)
|
||||
@DirtiesContext
|
||||
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, properties = { "value=123" })
|
||||
public class SpringBootTestTestRestTemplateDefinedByUser
|
||||
extends AbstractSpringBootTestEmbeddedWebEnvironmentTests {
|
||||
public class SpringBootTestTestRestTemplateDefinedByUser extends AbstractSpringBootTestEmbeddedWebEnvironmentTests {
|
||||
|
||||
@Test
|
||||
public void restTemplateIsUserDefined() throws Exception {
|
||||
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 AbstractSpringBootTestEmbeddedWebEnvironmentTests {
|
||||
@SpringBootTest(webEnvironment = WebEnvironment.DEFINED_PORT, properties = { "server.port=0", "value=123" })
|
||||
public class SpringBootTestWebEnvironmentDefinedPortTests extends AbstractSpringBootTestEmbeddedWebEnvironmentTests {
|
||||
|
||||
@Configuration
|
||||
@EnableWebMvc
|
||||
|
||||
@@ -78,8 +78,7 @@ public class SpringBootTestWebEnvironmentMockTests {
|
||||
|
||||
@Test
|
||||
public void resourcePath() throws Exception {
|
||||
assertThat(ReflectionTestUtils.getField(this.servletContext, "resourceBasePath"))
|
||||
.isEqualTo("src/main/webapp");
|
||||
assertThat(ReflectionTestUtils.getField(this.servletContext, "resourceBasePath")).isEqualTo("src/main/webapp");
|
||||
}
|
||||
|
||||
@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
|
||||
|
||||
@@ -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 AbstractSpringBootTestEmbeddedWebEnvironmentTests {
|
||||
public class SpringBootTestWebEnvironmentRandomPortTests extends AbstractSpringBootTestEmbeddedWebEnvironmentTests {
|
||||
|
||||
@Test
|
||||
public void testRestTemplateShouldUseBuilder() throws Exception {
|
||||
@@ -56,8 +55,7 @@ public class SpringBootTestWebEnvironmentRandomPortTests
|
||||
|
||||
@Bean
|
||||
public RestTemplateBuilder restTemplateBuilder() {
|
||||
return new RestTemplateBuilder()
|
||||
.additionalMessageConverters(new MyConverter());
|
||||
return new RestTemplateBuilder().additionalMessageConverters(new MyConverter());
|
||||
|
||||
}
|
||||
|
||||
|
||||
@@ -39,8 +39,7 @@ import static org.assertj.core.api.Assertions.assertThat;
|
||||
@RunWith(SpringRunner.class)
|
||||
@DirtiesContext
|
||||
@SpringBootTest
|
||||
@ContextConfiguration(
|
||||
classes = SpringBootTestWithContextConfigurationIntegrationTests.Config.class)
|
||||
@ContextConfiguration(classes = SpringBootTestWithContextConfigurationIntegrationTests.Config.class)
|
||||
public class SpringBootTestWithContextConfigurationIntegrationTests {
|
||||
|
||||
@Rule
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -63,8 +63,7 @@ public class SpringBootTestContextBootstrapperIntegrationTests {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void defaultTestExecutionListenersPostProcessorShouldBeCalled()
|
||||
throws Exception {
|
||||
public void defaultTestExecutionListenersPostProcessorShouldBeCalled() throws Exception {
|
||||
assertThat(this.defaultTestExecutionListenersPostProcessorCalled).isTrue();
|
||||
}
|
||||
|
||||
|
||||
@@ -45,8 +45,7 @@ public class SpringBootTestContextBootstrapperTests {
|
||||
this.thrown.expect(IllegalStateException.class);
|
||||
this.thrown.expectMessage("@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.");
|
||||
buildTestContext(SpringBootTestNonMockWebEnvironmentAndWebAppConfiguration.class);
|
||||
}
|
||||
|
||||
@@ -61,10 +60,8 @@ public class SpringBootTestContextBootstrapperTests {
|
||||
BootstrapContext bootstrapContext = mock(BootstrapContext.class);
|
||||
bootstrapper.setBootstrapContext(bootstrapContext);
|
||||
given((Class) bootstrapContext.getTestClass()).willReturn(testClass);
|
||||
CacheAwareContextLoaderDelegate contextLoaderDelegate = mock(
|
||||
CacheAwareContextLoaderDelegate.class);
|
||||
given(bootstrapContext.getCacheAwareContextLoaderDelegate())
|
||||
.willReturn(contextLoaderDelegate);
|
||||
CacheAwareContextLoaderDelegate contextLoaderDelegate = mock(CacheAwareContextLoaderDelegate.class);
|
||||
given(bootstrapContext.getCacheAwareContextLoaderDelegate()).willReturn(contextLoaderDelegate);
|
||||
bootstrapper.buildTestContext();
|
||||
}
|
||||
|
||||
|
||||
@@ -47,15 +47,13 @@ public class SpringBootTestContextBootstrapperWithInitializersTests {
|
||||
|
||||
@Test
|
||||
public void foundConfiguration() throws Exception {
|
||||
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) {
|
||||
|
||||
@@ -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(
|
||||
|
||||
@@ -40,34 +40,29 @@ public class TestTypeExcludeFilterTests {
|
||||
|
||||
@Test
|
||||
public void matchesTestClass() 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 matchesNestedConfiguration() throws Exception {
|
||||
assertThat(this.filter.match(getMetadataReader(NestedConfig.class),
|
||||
this.metadataReaderFactory)).isTrue();
|
||||
assertThat(this.filter.match(getMetadataReader(NestedConfig.class), this.metadataReaderFactory)).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void matchesNestedConfigurationClassWithoutTestMethodsIfItHasRunWith()
|
||||
throws Exception {
|
||||
assertThat(this.filter.match(
|
||||
getMetadataReader(AbstractTestWithConfigAndRunWith.Config.class),
|
||||
public void matchesNestedConfigurationClassWithoutTestMethodsIfItHasRunWith() throws Exception {
|
||||
assertThat(this.filter.match(getMetadataReader(AbstractTestWithConfigAndRunWith.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 {
|
||||
|
||||
@@ -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 ExpectedException thrown = ExpectedException.none();
|
||||
@@ -188,8 +187,7 @@ public abstract class AbstractJsonMarshalTesterTests {
|
||||
return createTester(AbstractJsonMarshalTesterTests.class, type);
|
||||
}
|
||||
|
||||
protected abstract AbstractJsonMarshalTester<Object> createTester(
|
||||
Class<?> resourceLoadClass, ResolvableType type);
|
||||
protected abstract AbstractJsonMarshalTester<Object> createTester(Class<?> resourceLoadClass, ResolvableType type);
|
||||
|
||||
/**
|
||||
* Access to field backed by {@link ResolvableType}.
|
||||
|
||||
@@ -40,10 +40,10 @@ public class DuplicateJsonObjectContextCustomizerFactoryTests {
|
||||
|
||||
@Test
|
||||
public void warningForMultipleVersions() {
|
||||
new DuplicateJsonObjectContextCustomizerFactory()
|
||||
.createContextCustomizer(null, null).customizeContext(null, null);
|
||||
assertThat(this.output.toString()).contains(
|
||||
"Found multiple occurrences of org.json.JSONObject on the class path:");
|
||||
new DuplicateJsonObjectContextCustomizerFactory().createContextCustomizer(null, null).customizeContext(null,
|
||||
null);
|
||||
assertThat(this.output.toString())
|
||||
.contains("Found multiple occurrences of org.json.JSONObject on the class path:");
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -60,19 +60,16 @@ public class GsonTesterTests extends AbstractJsonMarshalTesterTests {
|
||||
}
|
||||
|
||||
@Override
|
||||
protected AbstractJsonMarshalTester<Object> createTester(Class<?> resourceLoadClass,
|
||||
ResolvableType type) {
|
||||
return new GsonTester<Object>(resourceLoadClass, type,
|
||||
new GsonBuilder().create());
|
||||
protected AbstractJsonMarshalTester<Object> createTester(Class<?> resourceLoadClass, ResolvableType type) {
|
||||
return new GsonTester<Object>(resourceLoadClass, type, new GsonBuilder().create());
|
||||
}
|
||||
|
||||
abstract static class InitFieldsBaseClass {
|
||||
|
||||
public GsonTester<ExampleObject> base;
|
||||
|
||||
public GsonTester<ExampleObject> baseSet = new GsonTester<ExampleObject>(
|
||||
InitFieldsBaseClass.class, ResolvableType.forClass(ExampleObject.class),
|
||||
new GsonBuilder().create());
|
||||
public GsonTester<ExampleObject> baseSet = new GsonTester<ExampleObject>(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<ExampleObject>(
|
||||
InitFieldsBaseClass.class, ResolvableType.forClass(ExampleObject.class),
|
||||
new GsonBuilder().create());
|
||||
public GsonTester<ExampleObject> testSet = new GsonTester<ExampleObject>(InitFieldsBaseClass.class,
|
||||
ResolvableType.forClass(ExampleObject.class), new GsonBuilder().create());
|
||||
|
||||
}
|
||||
|
||||
|
||||
@@ -60,16 +60,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
|
||||
@@ -77,8 +75,7 @@ public class JacksonTesterIntegrationTests {
|
||||
Map<String, Integer> map = new LinkedHashMap<String, Integer>();
|
||||
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
|
||||
@@ -87,8 +84,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");
|
||||
}
|
||||
@@ -97,8 +94,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);
|
||||
}
|
||||
@@ -107,8 +104,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);
|
||||
}
|
||||
|
||||
@@ -59,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<Object>(resourceLoadClass, type, new ObjectMapper());
|
||||
}
|
||||
|
||||
@@ -68,9 +67,8 @@ public class JacksonTesterTests extends AbstractJsonMarshalTesterTests {
|
||||
|
||||
public JacksonTester<ExampleObject> base;
|
||||
|
||||
public JacksonTester<ExampleObject> baseSet = new JacksonTester<ExampleObject>(
|
||||
InitFieldsBaseClass.class, ResolvableType.forClass(ExampleObject.class),
|
||||
new ObjectMapper());
|
||||
public JacksonTester<ExampleObject> baseSet = new JacksonTester<ExampleObject>(InitFieldsBaseClass.class,
|
||||
ResolvableType.forClass(ExampleObject.class), new ObjectMapper());
|
||||
|
||||
}
|
||||
|
||||
@@ -78,9 +76,8 @@ public class JacksonTesterTests extends AbstractJsonMarshalTesterTests {
|
||||
|
||||
public JacksonTester<List<ExampleObject>> test;
|
||||
|
||||
public JacksonTester<ExampleObject> testSet = new JacksonTester<ExampleObject>(
|
||||
InitFieldsBaseClass.class, ResolvableType.forClass(ExampleObject.class),
|
||||
new ObjectMapper());
|
||||
public JacksonTester<ExampleObject> testSet = new JacksonTester<ExampleObject>(InitFieldsBaseClass.class,
|
||||
ResolvableType.forClass(ExampleObject.class), new ObjectMapper());
|
||||
|
||||
}
|
||||
|
||||
|
||||
@@ -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 final ExpectedException thrown = ExpectedException.none();
|
||||
@@ -157,14 +156,12 @@ public class JsonContentAssertTests {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void isEqualToJsonWhenResourcePathAndClassIsMatchingShouldPass()
|
||||
throws Exception {
|
||||
public void isEqualToJsonWhenResourcePathAndClassIsMatchingShouldPass() throws Exception {
|
||||
assertThat(forJson(SOURCE)).isEqualToJson("lenient-same.json", getClass());
|
||||
}
|
||||
|
||||
@Test(expected = AssertionError.class)
|
||||
public void isEqualToJsonWhenResourcePathAndClassIsNotMatchingShouldFail()
|
||||
throws Exception {
|
||||
public void isEqualToJsonWhenResourcePathAndClassIsNotMatchingShouldFail() throws Exception {
|
||||
assertThat(forJson(SOURCE)).isEqualToJson("different.json", getClass());
|
||||
}
|
||||
|
||||
@@ -214,34 +211,28 @@ public class JsonContentAssertTests {
|
||||
}
|
||||
|
||||
@Test(expected = AssertionError.class)
|
||||
public void isStrictlyEqualToJsonWhenStringIsNotMatchingShouldFail()
|
||||
throws Exception {
|
||||
public void isStrictlyEqualToJsonWhenStringIsNotMatchingShouldFail() throws Exception {
|
||||
assertThat(forJson(SOURCE)).isStrictlyEqualToJson(LENIENT_SAME);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void isStrictlyEqualToJsonWhenResourcePathIsMatchingShouldPass()
|
||||
throws Exception {
|
||||
public void isStrictlyEqualToJsonWhenResourcePathIsMatchingShouldPass() throws Exception {
|
||||
assertThat(forJson(SOURCE)).isStrictlyEqualToJson("source.json");
|
||||
}
|
||||
|
||||
@Test(expected = AssertionError.class)
|
||||
public void isStrictlyEqualToJsonWhenResourcePathIsNotMatchingShouldFail()
|
||||
throws Exception {
|
||||
public void isStrictlyEqualToJsonWhenResourcePathIsNotMatchingShouldFail() throws Exception {
|
||||
assertThat(forJson(SOURCE)).isStrictlyEqualToJson("lenient-same.json");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void isStrictlyEqualToJsonWhenResourcePathAndClassIsMatchingShouldPass()
|
||||
throws Exception {
|
||||
public void isStrictlyEqualToJsonWhenResourcePathAndClassIsMatchingShouldPass() throws Exception {
|
||||
assertThat(forJson(SOURCE)).isStrictlyEqualToJson("source.json", getClass());
|
||||
}
|
||||
|
||||
@Test(expected = AssertionError.class)
|
||||
public void isStrictlyEqualToJsonWhenResourcePathAndClassIsNotMatchingShouldFail()
|
||||
throws Exception {
|
||||
assertThat(forJson(SOURCE)).isStrictlyEqualToJson("lenient-same.json",
|
||||
getClass());
|
||||
public void isStrictlyEqualToJsonWhenResourcePathAndClassIsNotMatchingShouldFail() throws Exception {
|
||||
assertThat(forJson(SOURCE)).isStrictlyEqualToJson("lenient-same.json", getClass());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -250,8 +241,7 @@ public class JsonContentAssertTests {
|
||||
}
|
||||
|
||||
@Test(expected = AssertionError.class)
|
||||
public void isStrictlyEqualToJsonWhenBytesAreNotMatchingShouldFail()
|
||||
throws Exception {
|
||||
public void isStrictlyEqualToJsonWhenBytesAreNotMatchingShouldFail() throws Exception {
|
||||
assertThat(forJson(SOURCE)).isStrictlyEqualToJson(LENIENT_SAME.getBytes());
|
||||
}
|
||||
|
||||
@@ -266,16 +256,13 @@ public class JsonContentAssertTests {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void isStrictlyEqualToJsonWhenInputStreamIsMatchingShouldPass()
|
||||
throws Exception {
|
||||
public void isStrictlyEqualToJsonWhenInputStreamIsMatchingShouldPass() throws Exception {
|
||||
assertThat(forJson(SOURCE)).isStrictlyEqualToJson(createInputStream(SOURCE));
|
||||
}
|
||||
|
||||
@Test(expected = AssertionError.class)
|
||||
public void isStrictlyEqualToJsonWhenInputStreamIsNotMatchingShouldFail()
|
||||
throws Exception {
|
||||
assertThat(forJson(SOURCE))
|
||||
.isStrictlyEqualToJson(createInputStream(LENIENT_SAME));
|
||||
public void isStrictlyEqualToJsonWhenInputStreamIsNotMatchingShouldFail() throws Exception {
|
||||
assertThat(forJson(SOURCE)).isStrictlyEqualToJson(createInputStream(LENIENT_SAME));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -284,8 +271,7 @@ public class JsonContentAssertTests {
|
||||
}
|
||||
|
||||
@Test(expected = AssertionError.class)
|
||||
public void isStrictlyEqualToJsonWhenResourceIsNotMatchingShouldFail()
|
||||
throws Exception {
|
||||
public void isStrictlyEqualToJsonWhenResourceIsNotMatchingShouldFail() throws Exception {
|
||||
assertThat(forJson(SOURCE)).isStrictlyEqualToJson(createResource(LENIENT_SAME));
|
||||
}
|
||||
|
||||
@@ -295,179 +281,137 @@ public class JsonContentAssertTests {
|
||||
}
|
||||
|
||||
@Test(expected = AssertionError.class)
|
||||
public void isEqualToJsonWhenStringIsNotMatchingAndLenientShouldFail()
|
||||
throws Exception {
|
||||
public void isEqualToJsonWhenStringIsNotMatchingAndLenientShouldFail() throws Exception {
|
||||
assertThat(forJson(SOURCE)).isEqualToJson(DIFFERENT, JSONCompareMode.LENIENT);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void isEqualToJsonWhenResourcePathIsMatchingAndLenientShouldPass()
|
||||
throws Exception {
|
||||
assertThat(forJson(SOURCE)).isEqualToJson("lenient-same.json",
|
||||
JSONCompareMode.LENIENT);
|
||||
public void isEqualToJsonWhenResourcePathIsMatchingAndLenientShouldPass() throws Exception {
|
||||
assertThat(forJson(SOURCE)).isEqualToJson("lenient-same.json", JSONCompareMode.LENIENT);
|
||||
}
|
||||
|
||||
@Test(expected = AssertionError.class)
|
||||
public void isEqualToJsonWhenResourcePathIsNotMatchingAndLenientShouldFail()
|
||||
throws Exception {
|
||||
assertThat(forJson(SOURCE)).isEqualToJson("different.json",
|
||||
JSONCompareMode.LENIENT);
|
||||
public void isEqualToJsonWhenResourcePathIsNotMatchingAndLenientShouldFail() throws Exception {
|
||||
assertThat(forJson(SOURCE)).isEqualToJson("different.json", JSONCompareMode.LENIENT);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void isEqualToJsonWhenResourcePathAndClassIsMatchingAndLenientShouldPass()
|
||||
throws Exception {
|
||||
assertThat(forJson(SOURCE)).isEqualToJson("lenient-same.json", getClass(),
|
||||
JSONCompareMode.LENIENT);
|
||||
public void isEqualToJsonWhenResourcePathAndClassIsMatchingAndLenientShouldPass() throws Exception {
|
||||
assertThat(forJson(SOURCE)).isEqualToJson("lenient-same.json", getClass(), JSONCompareMode.LENIENT);
|
||||
}
|
||||
|
||||
@Test(expected = AssertionError.class)
|
||||
public void isEqualToJsonWhenResourcePathAndClassIsNotMatchingAndLenientShouldFail()
|
||||
throws Exception {
|
||||
assertThat(forJson(SOURCE)).isEqualToJson("different.json", getClass(),
|
||||
JSONCompareMode.LENIENT);
|
||||
public void isEqualToJsonWhenResourcePathAndClassIsNotMatchingAndLenientShouldFail() throws Exception {
|
||||
assertThat(forJson(SOURCE)).isEqualToJson("different.json", getClass(), JSONCompareMode.LENIENT);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void isEqualToJsonWhenBytesAreMatchingAndLenientShouldPass() throws Exception {
|
||||
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()
|
||||
throws Exception {
|
||||
assertThat(forJson(SOURCE)).isEqualToJson(DIFFERENT.getBytes(),
|
||||
JSONCompareMode.LENIENT);
|
||||
public void isEqualToJsonWhenBytesAreNotMatchingAndLenientShouldFail() throws Exception {
|
||||
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()
|
||||
throws Exception {
|
||||
assertThat(forJson(SOURCE)).isEqualToJson(createInputStream(LENIENT_SAME),
|
||||
JSONCompareMode.LENIENT);
|
||||
public void isEqualToJsonWhenInputStreamIsMatchingAndLenientShouldPass() throws Exception {
|
||||
assertThat(forJson(SOURCE)).isEqualToJson(createInputStream(LENIENT_SAME), JSONCompareMode.LENIENT);
|
||||
}
|
||||
|
||||
@Test(expected = AssertionError.class)
|
||||
public void isEqualToJsonWhenInputStreamIsNotMatchingAndLenientShouldFail()
|
||||
throws Exception {
|
||||
assertThat(forJson(SOURCE)).isEqualToJson(createInputStream(DIFFERENT),
|
||||
JSONCompareMode.LENIENT);
|
||||
public void isEqualToJsonWhenInputStreamIsNotMatchingAndLenientShouldFail() throws Exception {
|
||||
assertThat(forJson(SOURCE)).isEqualToJson(createInputStream(DIFFERENT), JSONCompareMode.LENIENT);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void isEqualToJsonWhenResourceIsMatchingAndLenientShouldPass()
|
||||
throws Exception {
|
||||
assertThat(forJson(SOURCE)).isEqualToJson(createResource(LENIENT_SAME),
|
||||
JSONCompareMode.LENIENT);
|
||||
public void isEqualToJsonWhenResourceIsMatchingAndLenientShouldPass() throws Exception {
|
||||
assertThat(forJson(SOURCE)).isEqualToJson(createResource(LENIENT_SAME), JSONCompareMode.LENIENT);
|
||||
}
|
||||
|
||||
@Test(expected = AssertionError.class)
|
||||
public void isEqualToJsonWhenResourceIsNotMatchingAndLenientShouldFail()
|
||||
throws Exception {
|
||||
assertThat(forJson(SOURCE)).isEqualToJson(createResource(DIFFERENT),
|
||||
JSONCompareMode.LENIENT);
|
||||
public void isEqualToJsonWhenResourceIsNotMatchingAndLenientShouldFail() throws Exception {
|
||||
assertThat(forJson(SOURCE)).isEqualToJson(createResource(DIFFERENT), JSONCompareMode.LENIENT);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void isEqualToJsonWhenStringIsMatchingAndComparatorShouldPass()
|
||||
throws Exception {
|
||||
public void isEqualToJsonWhenStringIsMatchingAndComparatorShouldPass() throws Exception {
|
||||
assertThat(forJson(SOURCE)).isEqualToJson(LENIENT_SAME, COMPARATOR);
|
||||
}
|
||||
|
||||
@Test(expected = AssertionError.class)
|
||||
public void isEqualToJsonWhenStringIsNotMatchingAndComparatorShouldFail()
|
||||
throws Exception {
|
||||
public void isEqualToJsonWhenStringIsNotMatchingAndComparatorShouldFail() throws Exception {
|
||||
assertThat(forJson(SOURCE)).isEqualToJson(DIFFERENT, COMPARATOR);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void isEqualToJsonWhenResourcePathIsMatchingAndComparatorShouldPass()
|
||||
throws Exception {
|
||||
public void isEqualToJsonWhenResourcePathIsMatchingAndComparatorShouldPass() throws Exception {
|
||||
assertThat(forJson(SOURCE)).isEqualToJson("lenient-same.json", COMPARATOR);
|
||||
}
|
||||
|
||||
@Test(expected = AssertionError.class)
|
||||
public void isEqualToJsonWhenResourcePathIsNotMatchingAndComparatorShouldFail()
|
||||
throws Exception {
|
||||
public void isEqualToJsonWhenResourcePathIsNotMatchingAndComparatorShouldFail() throws Exception {
|
||||
assertThat(forJson(SOURCE)).isEqualToJson("different.json", COMPARATOR);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void isEqualToJsonWhenResourcePathAndClassAreMatchingAndComparatorShouldPass()
|
||||
throws Exception {
|
||||
assertThat(forJson(SOURCE)).isEqualToJson("lenient-same.json", getClass(),
|
||||
COMPARATOR);
|
||||
public void isEqualToJsonWhenResourcePathAndClassAreMatchingAndComparatorShouldPass() throws Exception {
|
||||
assertThat(forJson(SOURCE)).isEqualToJson("lenient-same.json", getClass(), COMPARATOR);
|
||||
}
|
||||
|
||||
@Test(expected = AssertionError.class)
|
||||
public void isEqualToJsonWhenResourcePathAndClassAreNotMatchingAndComparatorShouldFail()
|
||||
throws Exception {
|
||||
assertThat(forJson(SOURCE)).isEqualToJson("different.json", getClass(),
|
||||
COMPARATOR);
|
||||
public void isEqualToJsonWhenResourcePathAndClassAreNotMatchingAndComparatorShouldFail() throws Exception {
|
||||
assertThat(forJson(SOURCE)).isEqualToJson("different.json", getClass(), COMPARATOR);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void isEqualToJsonWhenBytesAreMatchingAndComparatorShouldPass()
|
||||
throws Exception {
|
||||
public void isEqualToJsonWhenBytesAreMatchingAndComparatorShouldPass() throws Exception {
|
||||
assertThat(forJson(SOURCE)).isEqualToJson(LENIENT_SAME.getBytes(), COMPARATOR);
|
||||
}
|
||||
|
||||
@Test(expected = AssertionError.class)
|
||||
public void isEqualToJsonWhenBytesAreNotMatchingAndComparatorShouldFail()
|
||||
throws Exception {
|
||||
public void isEqualToJsonWhenBytesAreNotMatchingAndComparatorShouldFail() throws Exception {
|
||||
assertThat(forJson(SOURCE)).isEqualToJson(DIFFERENT.getBytes(), COMPARATOR);
|
||||
}
|
||||
|
||||
@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()
|
||||
throws Exception {
|
||||
assertThat(forJson(SOURCE)).isEqualToJson(createInputStream(LENIENT_SAME),
|
||||
COMPARATOR);
|
||||
public void isEqualToJsonWhenInputStreamIsMatchingAndComparatorShouldPass() throws Exception {
|
||||
assertThat(forJson(SOURCE)).isEqualToJson(createInputStream(LENIENT_SAME), COMPARATOR);
|
||||
}
|
||||
|
||||
@Test(expected = AssertionError.class)
|
||||
public void isEqualToJsonWhenInputStreamIsNotMatchingAndComparatorShouldFail()
|
||||
throws Exception {
|
||||
assertThat(forJson(SOURCE)).isEqualToJson(createInputStream(DIFFERENT),
|
||||
COMPARATOR);
|
||||
public void isEqualToJsonWhenInputStreamIsNotMatchingAndComparatorShouldFail() throws Exception {
|
||||
assertThat(forJson(SOURCE)).isEqualToJson(createInputStream(DIFFERENT), COMPARATOR);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void isEqualToJsonWhenResourceIsMatchingAndComparatorShouldPass()
|
||||
throws Exception {
|
||||
assertThat(forJson(SOURCE)).isEqualToJson(createResource(LENIENT_SAME),
|
||||
COMPARATOR);
|
||||
public void isEqualToJsonWhenResourceIsMatchingAndComparatorShouldPass() throws Exception {
|
||||
assertThat(forJson(SOURCE)).isEqualToJson(createResource(LENIENT_SAME), COMPARATOR);
|
||||
}
|
||||
|
||||
@Test(expected = AssertionError.class)
|
||||
public void isEqualToJsonWhenResourceIsNotMatchingAndComparatorShouldFail()
|
||||
throws Exception {
|
||||
public void isEqualToJsonWhenResourceIsNotMatchingAndComparatorShouldFail() throws Exception {
|
||||
assertThat(forJson(SOURCE)).isEqualToJson(createResource(DIFFERENT), COMPARATOR);
|
||||
}
|
||||
|
||||
@@ -557,20 +501,17 @@ public class JsonContentAssertTests {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void isNotEqualToJsonWhenResourcePathIsNotMatchingShouldPass()
|
||||
throws Exception {
|
||||
public void isNotEqualToJsonWhenResourcePathIsNotMatchingShouldPass() throws Exception {
|
||||
assertThat(forJson(SOURCE)).isNotEqualToJson("different.json");
|
||||
}
|
||||
|
||||
@Test(expected = AssertionError.class)
|
||||
public void isNotEqualToJsonWhenResourcePathAndClassAreMatchingShouldFail()
|
||||
throws Exception {
|
||||
public void isNotEqualToJsonWhenResourcePathAndClassAreMatchingShouldFail() throws Exception {
|
||||
assertThat(forJson(SOURCE)).isNotEqualToJson("lenient-same.json", getClass());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void isNotEqualToJsonWhenResourcePathAndClassAreNotMatchingShouldPass()
|
||||
throws Exception {
|
||||
public void isNotEqualToJsonWhenResourcePathAndClassAreNotMatchingShouldPass() throws Exception {
|
||||
assertThat(forJson(SOURCE)).isNotEqualToJson("different.json", getClass());
|
||||
}
|
||||
|
||||
@@ -600,8 +541,7 @@ public class JsonContentAssertTests {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void isNotEqualToJsonWhenInputStreamIsNotMatchingShouldPass()
|
||||
throws Exception {
|
||||
public void isNotEqualToJsonWhenInputStreamIsNotMatchingShouldPass() throws Exception {
|
||||
assertThat(forJson(SOURCE)).isNotEqualToJson(createInputStream(DIFFERENT));
|
||||
}
|
||||
|
||||
@@ -616,51 +556,42 @@ public class JsonContentAssertTests {
|
||||
}
|
||||
|
||||
@Test(expected = AssertionError.class)
|
||||
public void isNotStrictlyEqualToJsonWhenStringIsMatchingShouldFail()
|
||||
throws Exception {
|
||||
public void isNotStrictlyEqualToJsonWhenStringIsMatchingShouldFail() throws Exception {
|
||||
assertThat(forJson(SOURCE)).isNotStrictlyEqualToJson(SOURCE);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void isNotStrictlyEqualToJsonWhenStringIsNotMatchingShouldPass()
|
||||
throws Exception {
|
||||
public void isNotStrictlyEqualToJsonWhenStringIsNotMatchingShouldPass() throws Exception {
|
||||
assertThat(forJson(SOURCE)).isNotStrictlyEqualToJson(LENIENT_SAME);
|
||||
}
|
||||
|
||||
@Test(expected = AssertionError.class)
|
||||
public void isNotStrictlyEqualToJsonWhenResourcePathIsMatchingShouldFail()
|
||||
throws Exception {
|
||||
public void isNotStrictlyEqualToJsonWhenResourcePathIsMatchingShouldFail() throws Exception {
|
||||
assertThat(forJson(SOURCE)).isNotStrictlyEqualToJson("source.json");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void isNotStrictlyEqualToJsonWhenResourcePathIsNotMatchingShouldPass()
|
||||
throws Exception {
|
||||
public void isNotStrictlyEqualToJsonWhenResourcePathIsNotMatchingShouldPass() throws Exception {
|
||||
assertThat(forJson(SOURCE)).isNotStrictlyEqualToJson("lenient-same.json");
|
||||
}
|
||||
|
||||
@Test(expected = AssertionError.class)
|
||||
public void isNotStrictlyEqualToJsonWhenResourcePathAndClassAreMatchingShouldFail()
|
||||
throws Exception {
|
||||
public void isNotStrictlyEqualToJsonWhenResourcePathAndClassAreMatchingShouldFail() throws Exception {
|
||||
assertThat(forJson(SOURCE)).isNotStrictlyEqualToJson("source.json", getClass());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void isNotStrictlyEqualToJsonWhenResourcePathAndClassAreNotMatchingShouldPass()
|
||||
throws Exception {
|
||||
assertThat(forJson(SOURCE)).isNotStrictlyEqualToJson("lenient-same.json",
|
||||
getClass());
|
||||
public void isNotStrictlyEqualToJsonWhenResourcePathAndClassAreNotMatchingShouldPass() throws Exception {
|
||||
assertThat(forJson(SOURCE)).isNotStrictlyEqualToJson("lenient-same.json", getClass());
|
||||
}
|
||||
|
||||
@Test(expected = AssertionError.class)
|
||||
public void isNotStrictlyEqualToJsonWhenBytesAreMatchingShouldFail()
|
||||
throws Exception {
|
||||
public void isNotStrictlyEqualToJsonWhenBytesAreMatchingShouldFail() throws Exception {
|
||||
assertThat(forJson(SOURCE)).isNotStrictlyEqualToJson(SOURCE.getBytes());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void isNotStrictlyEqualToJsonWhenBytesAreNotMatchingShouldPass()
|
||||
throws Exception {
|
||||
public void isNotStrictlyEqualToJsonWhenBytesAreNotMatchingShouldPass() throws Exception {
|
||||
assertThat(forJson(SOURCE)).isNotStrictlyEqualToJson(LENIENT_SAME.getBytes());
|
||||
}
|
||||
|
||||
@@ -670,223 +601,168 @@ public class JsonContentAssertTests {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void isNotStrictlyEqualToJsonWhenFileIsNotMatchingShouldPass()
|
||||
throws Exception {
|
||||
public void isNotStrictlyEqualToJsonWhenFileIsNotMatchingShouldPass() throws Exception {
|
||||
assertThat(forJson(SOURCE)).isNotStrictlyEqualToJson(createFile(LENIENT_SAME));
|
||||
}
|
||||
|
||||
@Test(expected = AssertionError.class)
|
||||
public void isNotStrictlyEqualToJsonWhenInputStreamIsMatchingShouldFail()
|
||||
throws Exception {
|
||||
public void isNotStrictlyEqualToJsonWhenInputStreamIsMatchingShouldFail() throws Exception {
|
||||
assertThat(forJson(SOURCE)).isNotStrictlyEqualToJson(createInputStream(SOURCE));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void isNotStrictlyEqualToJsonWhenInputStreamIsNotMatchingShouldPass()
|
||||
throws Exception {
|
||||
assertThat(forJson(SOURCE))
|
||||
.isNotStrictlyEqualToJson(createInputStream(LENIENT_SAME));
|
||||
public void isNotStrictlyEqualToJsonWhenInputStreamIsNotMatchingShouldPass() throws Exception {
|
||||
assertThat(forJson(SOURCE)).isNotStrictlyEqualToJson(createInputStream(LENIENT_SAME));
|
||||
}
|
||||
|
||||
@Test(expected = AssertionError.class)
|
||||
public void isNotStrictlyEqualToJsonWhenResourceIsMatchingShouldFail()
|
||||
throws Exception {
|
||||
public void isNotStrictlyEqualToJsonWhenResourceIsMatchingShouldFail() throws Exception {
|
||||
assertThat(forJson(SOURCE)).isNotStrictlyEqualToJson(createResource(SOURCE));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void isNotStrictlyEqualToJsonWhenResourceIsNotMatchingShouldPass()
|
||||
throws Exception {
|
||||
assertThat(forJson(SOURCE))
|
||||
.isNotStrictlyEqualToJson(createResource(LENIENT_SAME));
|
||||
public void isNotStrictlyEqualToJsonWhenResourceIsNotMatchingShouldPass() throws Exception {
|
||||
assertThat(forJson(SOURCE)).isNotStrictlyEqualToJson(createResource(LENIENT_SAME));
|
||||
}
|
||||
|
||||
@Test(expected = AssertionError.class)
|
||||
public void isNotEqualToJsonWhenStringIsMatchingAndLenientShouldFail()
|
||||
throws Exception {
|
||||
assertThat(forJson(SOURCE)).isNotEqualToJson(LENIENT_SAME,
|
||||
JSONCompareMode.LENIENT);
|
||||
public void isNotEqualToJsonWhenStringIsMatchingAndLenientShouldFail() throws Exception {
|
||||
assertThat(forJson(SOURCE)).isNotEqualToJson(LENIENT_SAME, JSONCompareMode.LENIENT);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void isNotEqualToJsonWhenStringIsNotMatchingAndLenientShouldPass()
|
||||
throws Exception {
|
||||
public void isNotEqualToJsonWhenStringIsNotMatchingAndLenientShouldPass() throws Exception {
|
||||
assertThat(forJson(SOURCE)).isNotEqualToJson(DIFFERENT, JSONCompareMode.LENIENT);
|
||||
}
|
||||
|
||||
@Test(expected = AssertionError.class)
|
||||
public void isNotEqualToJsonWhenResourcePathIsMatchingAndLenientShouldFail()
|
||||
throws Exception {
|
||||
assertThat(forJson(SOURCE)).isNotEqualToJson("lenient-same.json",
|
||||
JSONCompareMode.LENIENT);
|
||||
public void isNotEqualToJsonWhenResourcePathIsMatchingAndLenientShouldFail() throws Exception {
|
||||
assertThat(forJson(SOURCE)).isNotEqualToJson("lenient-same.json", JSONCompareMode.LENIENT);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void isNotEqualToJsonWhenResourcePathIsNotMatchingAndLenientShouldPass()
|
||||
throws Exception {
|
||||
assertThat(forJson(SOURCE)).isNotEqualToJson("different.json",
|
||||
JSONCompareMode.LENIENT);
|
||||
public void isNotEqualToJsonWhenResourcePathIsNotMatchingAndLenientShouldPass() throws Exception {
|
||||
assertThat(forJson(SOURCE)).isNotEqualToJson("different.json", JSONCompareMode.LENIENT);
|
||||
}
|
||||
|
||||
@Test(expected = AssertionError.class)
|
||||
public void isNotEqualToJsonWhenResourcePathAndClassAreMatchingAndLenientShouldFail()
|
||||
throws Exception {
|
||||
assertThat(forJson(SOURCE)).isNotEqualToJson("lenient-same.json", getClass(),
|
||||
JSONCompareMode.LENIENT);
|
||||
public void isNotEqualToJsonWhenResourcePathAndClassAreMatchingAndLenientShouldFail() throws Exception {
|
||||
assertThat(forJson(SOURCE)).isNotEqualToJson("lenient-same.json", getClass(), JSONCompareMode.LENIENT);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void isNotEqualToJsonWhenResourcePathAndClassAreNotMatchingAndLenientShouldPass()
|
||||
throws Exception {
|
||||
assertThat(forJson(SOURCE)).isNotEqualToJson("different.json", getClass(),
|
||||
JSONCompareMode.LENIENT);
|
||||
public void isNotEqualToJsonWhenResourcePathAndClassAreNotMatchingAndLenientShouldPass() throws Exception {
|
||||
assertThat(forJson(SOURCE)).isNotEqualToJson("different.json", getClass(), JSONCompareMode.LENIENT);
|
||||
}
|
||||
|
||||
@Test(expected = AssertionError.class)
|
||||
public void isNotEqualToJsonWhenBytesAreMatchingAndLenientShouldFail()
|
||||
throws Exception {
|
||||
assertThat(forJson(SOURCE)).isNotEqualToJson(LENIENT_SAME.getBytes(),
|
||||
JSONCompareMode.LENIENT);
|
||||
public void isNotEqualToJsonWhenBytesAreMatchingAndLenientShouldFail() throws Exception {
|
||||
assertThat(forJson(SOURCE)).isNotEqualToJson(LENIENT_SAME.getBytes(), JSONCompareMode.LENIENT);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void isNotEqualToJsonWhenBytesAreNotMatchingAndLenientShouldPass()
|
||||
throws Exception {
|
||||
assertThat(forJson(SOURCE)).isNotEqualToJson(DIFFERENT.getBytes(),
|
||||
JSONCompareMode.LENIENT);
|
||||
public void isNotEqualToJsonWhenBytesAreNotMatchingAndLenientShouldPass() throws Exception {
|
||||
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()
|
||||
throws Exception {
|
||||
assertThat(forJson(SOURCE)).isNotEqualToJson(createInputStream(LENIENT_SAME),
|
||||
JSONCompareMode.LENIENT);
|
||||
public void isNotEqualToJsonWhenInputStreamIsMatchingAndLenientShouldFail() throws Exception {
|
||||
assertThat(forJson(SOURCE)).isNotEqualToJson(createInputStream(LENIENT_SAME), JSONCompareMode.LENIENT);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void isNotEqualToJsonWhenInputStreamIsNotMatchingAndLenientShouldPass()
|
||||
throws Exception {
|
||||
assertThat(forJson(SOURCE)).isNotEqualToJson(createInputStream(DIFFERENT),
|
||||
JSONCompareMode.LENIENT);
|
||||
public void isNotEqualToJsonWhenInputStreamIsNotMatchingAndLenientShouldPass() throws Exception {
|
||||
assertThat(forJson(SOURCE)).isNotEqualToJson(createInputStream(DIFFERENT), JSONCompareMode.LENIENT);
|
||||
}
|
||||
|
||||
@Test(expected = AssertionError.class)
|
||||
public void isNotEqualToJsonWhenResourceIsMatchingAndLenientShouldFail()
|
||||
throws Exception {
|
||||
assertThat(forJson(SOURCE)).isNotEqualToJson(createResource(LENIENT_SAME),
|
||||
JSONCompareMode.LENIENT);
|
||||
public void isNotEqualToJsonWhenResourceIsMatchingAndLenientShouldFail() throws Exception {
|
||||
assertThat(forJson(SOURCE)).isNotEqualToJson(createResource(LENIENT_SAME), JSONCompareMode.LENIENT);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void isNotEqualToJsonWhenResourceIsNotMatchingAndLenientShouldPass()
|
||||
throws Exception {
|
||||
assertThat(forJson(SOURCE)).isNotEqualToJson(createResource(DIFFERENT),
|
||||
JSONCompareMode.LENIENT);
|
||||
public void isNotEqualToJsonWhenResourceIsNotMatchingAndLenientShouldPass() throws Exception {
|
||||
assertThat(forJson(SOURCE)).isNotEqualToJson(createResource(DIFFERENT), JSONCompareMode.LENIENT);
|
||||
}
|
||||
|
||||
@Test(expected = AssertionError.class)
|
||||
public void isNotEqualToJsonWhenStringIsMatchingAndComparatorShouldFail()
|
||||
throws Exception {
|
||||
public void isNotEqualToJsonWhenStringIsMatchingAndComparatorShouldFail() throws Exception {
|
||||
assertThat(forJson(SOURCE)).isNotEqualToJson(LENIENT_SAME, COMPARATOR);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void isNotEqualToJsonWhenStringIsNotMatchingAndComparatorShouldPass()
|
||||
throws Exception {
|
||||
public void isNotEqualToJsonWhenStringIsNotMatchingAndComparatorShouldPass() throws Exception {
|
||||
assertThat(forJson(SOURCE)).isNotEqualToJson(DIFFERENT, COMPARATOR);
|
||||
}
|
||||
|
||||
@Test(expected = AssertionError.class)
|
||||
public void isNotEqualToJsonWhenResourcePathIsMatchingAndComparatorShouldFail()
|
||||
throws Exception {
|
||||
public void isNotEqualToJsonWhenResourcePathIsMatchingAndComparatorShouldFail() throws Exception {
|
||||
assertThat(forJson(SOURCE)).isNotEqualToJson("lenient-same.json", COMPARATOR);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void isNotEqualToJsonWhenResourcePathIsNotMatchingAndComparatorShouldPass()
|
||||
throws Exception {
|
||||
public void isNotEqualToJsonWhenResourcePathIsNotMatchingAndComparatorShouldPass() throws Exception {
|
||||
assertThat(forJson(SOURCE)).isNotEqualToJson("different.json", COMPARATOR);
|
||||
}
|
||||
|
||||
@Test(expected = AssertionError.class)
|
||||
public void isNotEqualToJsonWhenResourcePathAndClassAreMatchingAndComparatorShouldFail()
|
||||
throws Exception {
|
||||
assertThat(forJson(SOURCE)).isNotEqualToJson("lenient-same.json", getClass(),
|
||||
COMPARATOR);
|
||||
public void isNotEqualToJsonWhenResourcePathAndClassAreMatchingAndComparatorShouldFail() throws Exception {
|
||||
assertThat(forJson(SOURCE)).isNotEqualToJson("lenient-same.json", getClass(), COMPARATOR);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void isNotEqualToJsonWhenResourcePathAndClassAreNotMatchingAndComparatorShouldPass()
|
||||
throws Exception {
|
||||
assertThat(forJson(SOURCE)).isNotEqualToJson("different.json", getClass(),
|
||||
COMPARATOR);
|
||||
public void isNotEqualToJsonWhenResourcePathAndClassAreNotMatchingAndComparatorShouldPass() throws Exception {
|
||||
assertThat(forJson(SOURCE)).isNotEqualToJson("different.json", getClass(), COMPARATOR);
|
||||
}
|
||||
|
||||
@Test(expected = AssertionError.class)
|
||||
public void isNotEqualToJsonWhenBytesAreMatchingAndComparatorShouldFail()
|
||||
throws Exception {
|
||||
public void isNotEqualToJsonWhenBytesAreMatchingAndComparatorShouldFail() throws Exception {
|
||||
assertThat(forJson(SOURCE)).isNotEqualToJson(LENIENT_SAME.getBytes(), COMPARATOR);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void isNotEqualToJsonWhenBytesAreNotMatchingAndComparatorShouldPass()
|
||||
throws Exception {
|
||||
public void isNotEqualToJsonWhenBytesAreNotMatchingAndComparatorShouldPass() throws Exception {
|
||||
assertThat(forJson(SOURCE)).isNotEqualToJson(DIFFERENT.getBytes(), COMPARATOR);
|
||||
}
|
||||
|
||||
@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()
|
||||
throws Exception {
|
||||
assertThat(forJson(SOURCE)).isNotEqualToJson(createInputStream(LENIENT_SAME),
|
||||
COMPARATOR);
|
||||
public void isNotEqualToJsonWhenInputStreamIsMatchingAndComparatorShouldFail() throws Exception {
|
||||
assertThat(forJson(SOURCE)).isNotEqualToJson(createInputStream(LENIENT_SAME), COMPARATOR);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void isNotEqualToJsonWhenInputStreamIsNotMatchingAndComparatorShouldPass()
|
||||
throws Exception {
|
||||
assertThat(forJson(SOURCE)).isNotEqualToJson(createInputStream(DIFFERENT),
|
||||
COMPARATOR);
|
||||
public void isNotEqualToJsonWhenInputStreamIsNotMatchingAndComparatorShouldPass() throws Exception {
|
||||
assertThat(forJson(SOURCE)).isNotEqualToJson(createInputStream(DIFFERENT), COMPARATOR);
|
||||
}
|
||||
|
||||
@Test(expected = AssertionError.class)
|
||||
public void isNotEqualToJsonWhenResourceIsMatchingAndComparatorShouldFail()
|
||||
throws Exception {
|
||||
assertThat(forJson(SOURCE)).isNotEqualToJson(createResource(LENIENT_SAME),
|
||||
COMPARATOR);
|
||||
public void isNotEqualToJsonWhenResourceIsMatchingAndComparatorShouldFail() throws Exception {
|
||||
assertThat(forJson(SOURCE)).isNotEqualToJson(createResource(LENIENT_SAME), COMPARATOR);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void isNotEqualToJsonWhenResourceIsNotMatchingAndComparatorShouldPass()
|
||||
throws Exception {
|
||||
assertThat(forJson(SOURCE)).isNotEqualToJson(createResource(DIFFERENT),
|
||||
COMPARATOR);
|
||||
public void isNotEqualToJsonWhenResourceIsNotMatchingAndComparatorShouldPass() throws Exception {
|
||||
assertThat(forJson(SOURCE)).isNotEqualToJson(createResource(DIFFERENT), COMPARATOR);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -906,8 +782,7 @@ public class JsonContentAssertTests {
|
||||
|
||||
@Test
|
||||
public void hasJsonPathValueForIndefinitePathWithResults() throws Exception {
|
||||
assertThat(forJson(SIMPSONS))
|
||||
.hasJsonPathValue("$.familyMembers[?(@.name == 'Bart')]");
|
||||
assertThat(forJson(SIMPSONS)).hasJsonPathValue("$.familyMembers[?(@.name == 'Bart')]");
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -927,8 +802,7 @@ public class JsonContentAssertTests {
|
||||
public void doesNotHaveJsonPathValueForAnEmptyArray() throws Exception {
|
||||
String expression = "$.emptyArray";
|
||||
this.thrown.expect(AssertionError.class);
|
||||
this.thrown.expectMessage(
|
||||
"Expected no value at JSON path \"" + expression + "\" but found: []");
|
||||
this.thrown.expectMessage("Expected no value at JSON path \"" + expression + "\" but found: []");
|
||||
assertThat(forJson(TYPES)).doesNotHaveJsonPathValue(expression);
|
||||
}
|
||||
|
||||
@@ -936,8 +810,7 @@ public class JsonContentAssertTests {
|
||||
public void doesNotHaveJsonPathValueForAnEmptyMap() throws Exception {
|
||||
String expression = "$.emptyMap";
|
||||
this.thrown.expect(AssertionError.class);
|
||||
this.thrown.expectMessage(
|
||||
"Expected no value at JSON path \"" + expression + "\" but found: {}");
|
||||
this.thrown.expectMessage("Expected no value at JSON path \"" + expression + "\" but found: {}");
|
||||
assertThat(forJson(TYPES)).doesNotHaveJsonPathValue(expression);
|
||||
}
|
||||
|
||||
@@ -945,16 +818,14 @@ public class JsonContentAssertTests {
|
||||
public void doesNotHaveJsonPathValueForIndefinitePathWithResults() throws Exception {
|
||||
String expression = "$.familyMembers[?(@.name == 'Bart')]";
|
||||
this.thrown.expect(AssertionError.class);
|
||||
this.thrown.expectMessage("Expected no value at JSON path \"" + expression
|
||||
+ "\" but found: [{\"name\":\"Bart\"}]");
|
||||
this.thrown.expectMessage(
|
||||
"Expected no value at JSON path \"" + expression + "\" but found: [{\"name\":\"Bart\"}]");
|
||||
assertThat(forJson(SIMPSONS)).doesNotHaveJsonPathValue(expression);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void doesNotHaveJsonPathValueForIndefinitePathWithEmptyResults()
|
||||
throws Exception {
|
||||
assertThat(forJson(SIMPSONS))
|
||||
.doesNotHaveJsonPathValue("$.familyMembers[?(@.name == 'Dilbert')]");
|
||||
public void doesNotHaveJsonPathValueForIndefinitePathWithEmptyResults() throws Exception {
|
||||
assertThat(forJson(SIMPSONS)).doesNotHaveJsonPathValue("$.familyMembers[?(@.name == 'Dilbert')]");
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -973,18 +844,16 @@ public class JsonContentAssertTests {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void hasEmptyJsonPathValueForIndefinitePathWithEmptyResults()
|
||||
throws Exception {
|
||||
assertThat(forJson(SIMPSONS))
|
||||
.hasEmptyJsonPathValue("$.familyMembers[?(@.name == 'Dilbert')]");
|
||||
public void hasEmptyJsonPathValueForIndefinitePathWithEmptyResults() throws Exception {
|
||||
assertThat(forJson(SIMPSONS)).hasEmptyJsonPathValue("$.familyMembers[?(@.name == 'Dilbert')]");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void hasEmptyJsonPathValueForIndefinitePathWithResults() throws Exception {
|
||||
String expression = "$.familyMembers[?(@.name == 'Bart')]";
|
||||
this.thrown.expect(AssertionError.class);
|
||||
this.thrown.expectMessage("Expected an empty value at JSON path \"" + expression
|
||||
+ "\" but found: [{\"name\":\"Bart\"}]");
|
||||
this.thrown.expectMessage(
|
||||
"Expected an empty value at JSON path \"" + expression + "\" but found: [{\"name\":\"Bart\"}]");
|
||||
assertThat(forJson(SIMPSONS)).hasEmptyJsonPathValue(expression);
|
||||
}
|
||||
|
||||
@@ -992,8 +861,7 @@ public class JsonContentAssertTests {
|
||||
public void hasEmptyJsonPathValueForWhitespace() throws Exception {
|
||||
String expression = "$.whitespace";
|
||||
this.thrown.expect(AssertionError.class);
|
||||
this.thrown.expectMessage("Expected an empty value at JSON path \"" + expression
|
||||
+ "\" but found: ' '");
|
||||
this.thrown.expectMessage("Expected an empty value at JSON path \"" + expression + "\" but found: ' '");
|
||||
assertThat(forJson(TYPES)).hasEmptyJsonPathValue(expression);
|
||||
}
|
||||
|
||||
@@ -1023,19 +891,15 @@ public class JsonContentAssertTests {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void doesNotHaveEmptyJsonPathValueForIndefinitePathWithResults()
|
||||
throws Exception {
|
||||
assertThat(forJson(SIMPSONS))
|
||||
.doesNotHaveEmptyJsonPathValue("$.familyMembers[?(@.name == 'Bart')]");
|
||||
public void doesNotHaveEmptyJsonPathValueForIndefinitePathWithResults() throws Exception {
|
||||
assertThat(forJson(SIMPSONS)).doesNotHaveEmptyJsonPathValue("$.familyMembers[?(@.name == 'Bart')]");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void doesNotHaveEmptyJsonPathValueForIndefinitePathWithEmptyResults()
|
||||
throws Exception {
|
||||
public void doesNotHaveEmptyJsonPathValueForIndefinitePathWithEmptyResults() throws Exception {
|
||||
String expression = "$.familyMembers[?(@.name == 'Dilbert')]";
|
||||
this.thrown.expect(AssertionError.class);
|
||||
this.thrown.expectMessage("Expected a non-empty value at JSON path \""
|
||||
+ expression + "\" but found: []");
|
||||
this.thrown.expectMessage("Expected a non-empty value at JSON path \"" + expression + "\" but found: []");
|
||||
assertThat(forJson(SIMPSONS)).doesNotHaveEmptyJsonPathValue(expression);
|
||||
}
|
||||
|
||||
@@ -1043,8 +907,7 @@ public class JsonContentAssertTests {
|
||||
public void doesNotHaveEmptyJsonPathValueForAnEmptyString() throws Exception {
|
||||
String expression = "$.emptyString";
|
||||
this.thrown.expect(AssertionError.class);
|
||||
this.thrown.expectMessage("Expected a non-empty value at JSON path \""
|
||||
+ expression + "\" but found: ''");
|
||||
this.thrown.expectMessage("Expected a non-empty value at JSON path \"" + expression + "\" but found: ''");
|
||||
assertThat(forJson(TYPES)).doesNotHaveEmptyJsonPathValue(expression);
|
||||
}
|
||||
|
||||
@@ -1052,8 +915,7 @@ public class JsonContentAssertTests {
|
||||
public void doesNotHaveEmptyJsonPathValueForForAnEmptyArray() throws Exception {
|
||||
String expression = "$.emptyArray";
|
||||
this.thrown.expect(AssertionError.class);
|
||||
this.thrown.expectMessage("Expected a non-empty value at JSON path \""
|
||||
+ expression + "\" but found: []");
|
||||
this.thrown.expectMessage("Expected a non-empty value at JSON path \"" + expression + "\" but found: []");
|
||||
assertThat(forJson(TYPES)).doesNotHaveEmptyJsonPathValue(expression);
|
||||
}
|
||||
|
||||
@@ -1061,8 +923,7 @@ public class JsonContentAssertTests {
|
||||
public void doesNotHaveEmptyJsonPathValueForAnEmptyMap() throws Exception {
|
||||
String expression = "$.emptyMap";
|
||||
this.thrown.expect(AssertionError.class);
|
||||
this.thrown.expectMessage("Expected a non-empty value at JSON path \""
|
||||
+ expression + "\" but found: {}");
|
||||
this.thrown.expectMessage("Expected a non-empty value at JSON path \"" + expression + "\" but found: {}");
|
||||
assertThat(forJson(TYPES)).doesNotHaveEmptyJsonPathValue(expression);
|
||||
}
|
||||
|
||||
@@ -1080,8 +941,7 @@ public class JsonContentAssertTests {
|
||||
public void hasJsonPathStringValueForNonString() throws Exception {
|
||||
String expression = "$.bool";
|
||||
this.thrown.expect(AssertionError.class);
|
||||
this.thrown.expectMessage(
|
||||
"Expected a string at JSON path \"" + expression + "\" but found: true");
|
||||
this.thrown.expectMessage("Expected a string at JSON path \"" + expression + "\" but found: true");
|
||||
assertThat(forJson(TYPES)).hasJsonPathStringValue(expression);
|
||||
}
|
||||
|
||||
@@ -1094,8 +954,7 @@ public class JsonContentAssertTests {
|
||||
public void hasJsonPathNumberValueForNonNumber() throws Exception {
|
||||
String expression = "$.bool";
|
||||
this.thrown.expect(AssertionError.class);
|
||||
this.thrown.expectMessage(
|
||||
"Expected a number at JSON path \"" + expression + "\" but found: true");
|
||||
this.thrown.expectMessage("Expected a number at JSON path \"" + expression + "\" but found: true");
|
||||
assertThat(forJson(TYPES)).hasJsonPathNumberValue(expression);
|
||||
}
|
||||
|
||||
@@ -1108,8 +967,7 @@ public class JsonContentAssertTests {
|
||||
public void hasJsonPathBooleanValueForNonBoolean() throws Exception {
|
||||
String expression = "$.num";
|
||||
this.thrown.expect(AssertionError.class);
|
||||
this.thrown.expectMessage(
|
||||
"Expected a boolean at JSON path \"" + expression + "\" but found: 5");
|
||||
this.thrown.expectMessage("Expected a boolean at JSON path \"" + expression + "\" but found: 5");
|
||||
assertThat(forJson(TYPES)).hasJsonPathBooleanValue(expression);
|
||||
}
|
||||
|
||||
@@ -1127,8 +985,7 @@ public class JsonContentAssertTests {
|
||||
public void hasJsonPathArrayValueForNonArray() throws Exception {
|
||||
String expression = "$.str";
|
||||
this.thrown.expect(AssertionError.class);
|
||||
this.thrown.expectMessage(
|
||||
"Expected an array at JSON path \"" + expression + "\" but found: 'foo'");
|
||||
this.thrown.expectMessage("Expected an array at JSON path \"" + expression + "\" but found: 'foo'");
|
||||
assertThat(forJson(TYPES)).hasJsonPathArrayValue(expression);
|
||||
}
|
||||
|
||||
@@ -1146,8 +1003,7 @@ public class JsonContentAssertTests {
|
||||
public void hasJsonPathMapValueForNonMap() throws Exception {
|
||||
String expression = "$.str";
|
||||
this.thrown.expect(AssertionError.class);
|
||||
this.thrown.expectMessage(
|
||||
"Expected a map at JSON path \"" + expression + "\" but found: 'foo'");
|
||||
this.thrown.expectMessage("Expected a map at JSON path \"" + expression + "\" but found: 'foo'");
|
||||
assertThat(forJson(TYPES)).hasJsonPathMapValue(expression);
|
||||
}
|
||||
|
||||
@@ -1163,8 +1019,7 @@ public class JsonContentAssertTests {
|
||||
|
||||
@Test
|
||||
public void extractingJsonPathStringValue() throws Exception {
|
||||
assertThat(forJson(TYPES)).extractingJsonPathStringValue("@.str")
|
||||
.isEqualTo("foo");
|
||||
assertThat(forJson(TYPES)).extractingJsonPathStringValue("@.str").isEqualTo("foo");
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -1174,16 +1029,14 @@ public class JsonContentAssertTests {
|
||||
|
||||
@Test
|
||||
public void extractingJsonPathStringValueForEmptyString() throws Exception {
|
||||
assertThat(forJson(TYPES)).extractingJsonPathStringValue("@.emptyString")
|
||||
.isEmpty();
|
||||
assertThat(forJson(TYPES)).extractingJsonPathStringValue("@.emptyString").isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void extractingJsonPathStringValueForWrongType() throws Exception {
|
||||
String expression = "$.num";
|
||||
this.thrown.expect(AssertionError.class);
|
||||
this.thrown.expectMessage(
|
||||
"Expected a string at JSON path \"" + expression + "\" but found: 5");
|
||||
this.thrown.expectMessage("Expected a string at JSON path \"" + expression + "\" but found: 5");
|
||||
assertThat(forJson(TYPES)).extractingJsonPathStringValue(expression);
|
||||
}
|
||||
|
||||
@@ -1201,8 +1054,7 @@ public class JsonContentAssertTests {
|
||||
public void extractingJsonPathNumberValueForWrongType() throws Exception {
|
||||
String expression = "$.str";
|
||||
this.thrown.expect(AssertionError.class);
|
||||
this.thrown.expectMessage(
|
||||
"Expected a number at JSON path \"" + expression + "\" but found: 'foo'");
|
||||
this.thrown.expectMessage("Expected a number at JSON path \"" + expression + "\" but found: 'foo'");
|
||||
assertThat(forJson(TYPES)).extractingJsonPathNumberValue(expression);
|
||||
}
|
||||
|
||||
@@ -1220,15 +1072,13 @@ public class JsonContentAssertTests {
|
||||
public void extractingJsonPathBooleanValueForWrongType() throws Exception {
|
||||
String expression = "$.str";
|
||||
this.thrown.expect(AssertionError.class);
|
||||
this.thrown.expectMessage("Expected a boolean at JSON path \"" + expression
|
||||
+ "\" but found: 'foo'");
|
||||
this.thrown.expectMessage("Expected a boolean at JSON path \"" + expression + "\" but found: 'foo'");
|
||||
assertThat(forJson(TYPES)).extractingJsonPathBooleanValue(expression);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void extractingJsonPathArrayValue() throws Exception {
|
||||
assertThat(forJson(TYPES)).extractingJsonPathArrayValue("@.arr")
|
||||
.containsExactly(42);
|
||||
assertThat(forJson(TYPES)).extractingJsonPathArrayValue("@.arr").containsExactly(42);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -1245,15 +1095,13 @@ public class JsonContentAssertTests {
|
||||
public void extractingJsonPathArrayValueForWrongType() throws Exception {
|
||||
String expression = "$.str";
|
||||
this.thrown.expect(AssertionError.class);
|
||||
this.thrown.expectMessage(
|
||||
"Expected an array at JSON path \"" + expression + "\" but found: 'foo'");
|
||||
this.thrown.expectMessage("Expected an array at JSON path \"" + expression + "\" but found: 'foo'");
|
||||
assertThat(forJson(TYPES)).extractingJsonPathArrayValue(expression);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void extractingJsonPathMapValue() throws Exception {
|
||||
assertThat(forJson(TYPES)).extractingJsonPathMapValue("@.colorMap")
|
||||
.contains(entry("red", "rojo"));
|
||||
assertThat(forJson(TYPES)).extractingJsonPathMapValue("@.colorMap").contains(entry("red", "rojo"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -1270,8 +1118,7 @@ public class JsonContentAssertTests {
|
||||
public void extractingJsonPathMapValueForWrongType() throws Exception {
|
||||
String expression = "$.str";
|
||||
this.thrown.expect(AssertionError.class);
|
||||
this.thrown.expectMessage(
|
||||
"Expected a map at JSON path \"" + expression + "\" but found: 'foo'");
|
||||
this.thrown.expectMessage("Expected a map at JSON path \"" + expression + "\" but found: 'foo'");
|
||||
assertThat(forJson(TYPES)).extractingJsonPathMapValue(expression);
|
||||
}
|
||||
|
||||
@@ -1296,8 +1143,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,8 +33,7 @@ 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);
|
||||
|
||||
@Rule
|
||||
public ExpectedException thrown = ExpectedException.none();
|
||||
@@ -55,39 +54,33 @@ public class JsonContentTests {
|
||||
|
||||
@Test
|
||||
public void createWhenTypeIsNullShouldCreateContent() throws Exception {
|
||||
JsonContent<ExampleObject> content = new JsonContent<ExampleObject>(getClass(),
|
||||
null, JSON);
|
||||
JsonContent<ExampleObject> content = new JsonContent<ExampleObject>(getClass(), null, JSON);
|
||||
assertThat(content).isNotNull();
|
||||
}
|
||||
|
||||
@SuppressWarnings("deprecation")
|
||||
@Test
|
||||
public void assertThatShouldReturnJsonContentAssert() throws Exception {
|
||||
JsonContent<ExampleObject> content = new JsonContent<ExampleObject>(getClass(),
|
||||
TYPE, JSON);
|
||||
JsonContent<ExampleObject> content = new JsonContent<ExampleObject>(getClass(), TYPE, JSON);
|
||||
assertThat(content.assertThat()).isInstanceOf(JsonContentAssert.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void getJsonShouldReturnJson() throws Exception {
|
||||
JsonContent<ExampleObject> content = new JsonContent<ExampleObject>(getClass(),
|
||||
TYPE, JSON);
|
||||
JsonContent<ExampleObject> content = new JsonContent<ExampleObject>(getClass(), TYPE, JSON);
|
||||
assertThat(content.getJson()).isEqualTo(JSON);
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void toStringWhenHasTypeShouldReturnString() throws Exception {
|
||||
JsonContent<ExampleObject> content = new JsonContent<ExampleObject>(getClass(),
|
||||
TYPE, JSON);
|
||||
assertThat(content.toString())
|
||||
.isEqualTo("JsonContent " + JSON + " created from " + TYPE);
|
||||
JsonContent<ExampleObject> content = new JsonContent<ExampleObject>(getClass(), TYPE, JSON);
|
||||
assertThat(content.toString()).isEqualTo("JsonContent " + JSON + " created from " + TYPE);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void toStringWhenHasNoTypeShouldReturnString() throws Exception {
|
||||
JsonContent<ExampleObject> content = new JsonContent<ExampleObject>(getClass(),
|
||||
null, JSON);
|
||||
JsonContent<ExampleObject> content = new JsonContent<ExampleObject>(getClass(), null, JSON);
|
||||
assertThat(content.toString()).isEqualTo("JsonContent " + JSON);
|
||||
}
|
||||
|
||||
|
||||
@@ -33,8 +33,7 @@ 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);
|
||||
|
||||
@Rule
|
||||
public ExpectedException thrown = ExpectedException.none();
|
||||
@@ -48,37 +47,31 @@ public class ObjectContentTests {
|
||||
|
||||
@Test
|
||||
public void createWhenTypeIsNullShouldCreateContent() throws Exception {
|
||||
ObjectContent<ExampleObject> content = new ObjectContent<ExampleObject>(null,
|
||||
OBJECT);
|
||||
ObjectContent<ExampleObject> content = new ObjectContent<ExampleObject>(null, OBJECT);
|
||||
assertThat(content).isNotNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void assertThatShouldReturnObjectContentAssert() throws Exception {
|
||||
ObjectContent<ExampleObject> content = new ObjectContent<ExampleObject>(TYPE,
|
||||
OBJECT);
|
||||
ObjectContent<ExampleObject> content = new ObjectContent<ExampleObject>(TYPE, OBJECT);
|
||||
assertThat(content.assertThat()).isInstanceOf(ObjectContentAssert.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void getObjectShouldReturnObject() throws Exception {
|
||||
ObjectContent<ExampleObject> content = new ObjectContent<ExampleObject>(TYPE,
|
||||
OBJECT);
|
||||
ObjectContent<ExampleObject> content = new ObjectContent<ExampleObject>(TYPE, OBJECT);
|
||||
assertThat(content.getObject()).isEqualTo(OBJECT);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void toStringWhenHasTypeShouldReturnString() throws Exception {
|
||||
ObjectContent<ExampleObject> content = new ObjectContent<ExampleObject>(TYPE,
|
||||
OBJECT);
|
||||
assertThat(content.toString())
|
||||
.isEqualTo("ObjectContent " + OBJECT + " created from " + TYPE);
|
||||
ObjectContent<ExampleObject> content = new ObjectContent<ExampleObject>(TYPE, OBJECT);
|
||||
assertThat(content.toString()).isEqualTo("ObjectContent " + OBJECT + " created from " + TYPE);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void toStringWhenHasNoTypeShouldReturnString() throws Exception {
|
||||
ObjectContent<ExampleObject> content = new ObjectContent<ExampleObject>(null,
|
||||
OBJECT);
|
||||
ObjectContent<ExampleObject> content = new ObjectContent<ExampleObject>(null, OBJECT);
|
||||
assertThat(content.toString()).isEqualTo("ObjectContent " + OBJECT);
|
||||
}
|
||||
|
||||
|
||||
@@ -49,18 +49,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
|
||||
@@ -70,8 +67,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()).isEqualTo(true);
|
||||
assertThat(definition.getReset()).isEqualTo(MockReset.NONE);
|
||||
@@ -83,14 +79,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);
|
||||
}
|
||||
|
||||
@@ -98,8 +92,7 @@ public class DefinitionsParserTests {
|
||||
public void parseMockBeanInferClassToMock() throws Exception {
|
||||
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
|
||||
@@ -113,17 +106,14 @@ public class DefinitionsParserTests {
|
||||
public void parseMockBeanMultipleClasses() throws Exception {
|
||||
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() throws Exception {
|
||||
this.thrown.expect(IllegalStateException.class);
|
||||
this.thrown.expectMessage(
|
||||
"The name attribute can only be used when mocking a single class");
|
||||
this.thrown.expectMessage("The name attribute can only be used when mocking a single class");
|
||||
this.parser.parse(MockBeanMultipleClassesWithName.class);
|
||||
}
|
||||
|
||||
@@ -131,18 +121,15 @@ public class DefinitionsParserTests {
|
||||
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
|
||||
@@ -151,8 +138,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();
|
||||
}
|
||||
@@ -163,22 +149,19 @@ 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() throws Exception {
|
||||
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
|
||||
@@ -192,17 +175,14 @@ public class DefinitionsParserTests {
|
||||
public void parseSpyBeanMultipleClasses() throws Exception {
|
||||
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() throws Exception {
|
||||
this.thrown.expect(IllegalStateException.class);
|
||||
this.thrown.expectMessage(
|
||||
"The name attribute can only be used when spying a single class");
|
||||
this.thrown.expectMessage("The name attribute can only be used when spying a single class");
|
||||
this.parser.parse(SpyBeanMultipleClassesWithName.class);
|
||||
}
|
||||
|
||||
@@ -228,10 +208,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 {
|
||||
|
||||
}
|
||||
@@ -250,8 +228,7 @@ public class DefinitionsParserTests {
|
||||
|
||||
}
|
||||
|
||||
@MockBean(name = "name",
|
||||
classes = { ExampleService.class, ExampleServiceCaller.class })
|
||||
@MockBean(name = "name", classes = { ExampleService.class, ExampleServiceCaller.class })
|
||||
static class MockBeanMultipleClassesWithName {
|
||||
|
||||
}
|
||||
@@ -273,8 +250,7 @@ public class DefinitionsParserTests {
|
||||
|
||||
}
|
||||
|
||||
@SpyBeans({ @SpyBean(RealExampleService.class),
|
||||
@SpyBean(ExampleServiceCaller.class) })
|
||||
@SpyBeans({ @SpyBean(RealExampleService.class), @SpyBean(ExampleServiceCaller.class) })
|
||||
static class RepeatSpyBean {
|
||||
|
||||
}
|
||||
@@ -298,8 +274,7 @@ public class DefinitionsParserTests {
|
||||
|
||||
}
|
||||
|
||||
@SpyBean(name = "name",
|
||||
classes = { RealExampleService.class, ExampleServiceCaller.class })
|
||||
@SpyBean(name = "name", classes = { RealExampleService.class, ExampleServiceCaller.class })
|
||||
static class SpyBeanMultipleClassesWithName {
|
||||
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
|
||||
@@ -62,8 +62,7 @@ public class MockBeanOnTestFieldForExistingBeanWithQualifierIntegrationTests {
|
||||
@Test
|
||||
public void onlyQualifiedBeanIsReplaced() {
|
||||
assertThat(this.applicationContext.getBean("service")).isSameAs(this.service);
|
||||
ExampleService anotherService = this.applicationContext.getBean("anotherService",
|
||||
ExampleService.class);
|
||||
ExampleService anotherService = this.applicationContext.getBean("anotherService", ExampleService.class);
|
||||
assertThat(anotherService.greeting()).isEqualTo("Another");
|
||||
}
|
||||
|
||||
|
||||
@@ -36,8 +36,7 @@ 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);
|
||||
|
||||
@Rule
|
||||
public ExpectedException thrown = ExpectedException.none();
|
||||
@@ -51,8 +50,7 @@ public class MockDefinitionTests {
|
||||
|
||||
@Test
|
||||
public void createWithDefaults() throws Exception {
|
||||
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();
|
||||
@@ -66,12 +64,11 @@ public class MockDefinitionTests {
|
||||
public void createExplicit() throws Exception {
|
||||
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);
|
||||
@@ -82,15 +79,14 @@ public class MockDefinitionTests {
|
||||
@Test
|
||||
public void createMock() throws Exception {
|
||||
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 = MockitoApi.get().getMockSettings(mock);
|
||||
assertThat(mock).isInstanceOf(ExampleService.class);
|
||||
assertThat(mock).isInstanceOf(ExampleExtraInterface.class);
|
||||
assertThat(settings.getMockName().toString()).isEqualTo("name");
|
||||
assertThat(settings.getDefaultAnswer())
|
||||
.isEqualTo(Answers.RETURNS_SMART_NULLS.get());
|
||||
assertThat(settings.getDefaultAnswer()).isEqualTo(Answers.RETURNS_SMART_NULLS.get());
|
||||
assertThat(settings.isSerializable()).isTrue();
|
||||
assertThat(MockReset.get(mock)).isEqualTo(MockReset.BEFORE);
|
||||
}
|
||||
|
||||
@@ -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() throws Exception {
|
||||
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);
|
||||
}
|
||||
|
||||
|
||||
@@ -39,30 +39,24 @@ public class MockitoContextCustomizerFactoryTests {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void getContextCustomizerWithoutAnnotationReturnsCustomizer()
|
||||
throws Exception {
|
||||
ContextCustomizer customizer = this.factory
|
||||
.createContextCustomizer(NoMockBeanAnnotation.class, null);
|
||||
public void getContextCustomizerWithoutAnnotationReturnsCustomizer() throws Exception {
|
||||
ContextCustomizer customizer = this.factory.createContextCustomizer(NoMockBeanAnnotation.class, null);
|
||||
assertThat(customizer).isNotNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void getContextCustomizerWithAnnotationReturnsCustomizer() throws Exception {
|
||||
ContextCustomizer customizer = this.factory
|
||||
.createContextCustomizer(WithMockBeanAnnotation.class, null);
|
||||
ContextCustomizer customizer = this.factory.createContextCustomizer(WithMockBeanAnnotation.class, null);
|
||||
assertThat(customizer).isNotNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void getContextCustomizerUsesMocksAsCacheKey() throws Exception {
|
||||
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());
|
||||
|
||||
@@ -53,8 +53,7 @@ public class MockitoContextCustomizerTests {
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -49,10 +49,8 @@ public class MockitoPostProcessorTests {
|
||||
MockitoPostProcessor.register(context);
|
||||
context.register(MultipleBeans.class);
|
||||
this.thrown.expect(IllegalStateException.class);
|
||||
this.thrown.expectMessage(
|
||||
"Unable to register mock bean " + ExampleService.class.getName()
|
||||
+ " expected a single matching bean to replace "
|
||||
+ "but found [example1, example2]");
|
||||
this.thrown.expectMessage("Unable to register mock bean " + ExampleService.class.getName()
|
||||
+ " expected a single matching bean to replace " + "but found [example1, example2]");
|
||||
context.refresh();
|
||||
}
|
||||
|
||||
@@ -62,10 +60,8 @@ public class MockitoPostProcessorTests {
|
||||
MockitoPostProcessor.register(context);
|
||||
context.register(MultipleQualifiedBeans.class);
|
||||
this.thrown.expect(IllegalStateException.class);
|
||||
this.thrown.expectMessage(
|
||||
"Unable to register mock bean " + ExampleService.class.getName()
|
||||
+ " expected a single matching bean to replace "
|
||||
+ "but found [example1, example3]");
|
||||
this.thrown.expectMessage("Unable to register mock bean " + ExampleService.class.getName()
|
||||
+ " expected a single matching bean to replace " + "but found [example1, example3]");
|
||||
context.refresh();
|
||||
}
|
||||
|
||||
@@ -73,15 +69,12 @@ public class MockitoPostProcessorTests {
|
||||
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();
|
||||
}
|
||||
|
||||
@Configuration
|
||||
|
||||
@@ -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),
|
||||
(MockDefinition) any());
|
||||
verify(this.postProcessor).inject(this.fieldCaptor.capture(), eq(instance), (MockDefinition) any());
|
||||
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");
|
||||
}
|
||||
|
||||
|
||||
@@ -67,16 +67,14 @@ public class QualifierDefinitionTests {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void forElementWhenElementIsFieldWithNoQualifiersShouldReturnNull()
|
||||
throws Exception {
|
||||
public void forElementWhenElementIsFieldWithNoQualifiersShouldReturnNull() throws Exception {
|
||||
QualifierDefinition definition = QualifierDefinition
|
||||
.forElement(ReflectionUtils.findField(ConfigA.class, "noQualifier"));
|
||||
assertThat(definition).isNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void forElementWhenElementIsFieldWithQualifierShouldReturnDefinition()
|
||||
throws Exception {
|
||||
public void forElementWhenElementIsFieldWithQualifierShouldReturnDefinition() throws Exception {
|
||||
QualifierDefinition definition = QualifierDefinition
|
||||
.forElement(ReflectionUtils.findField(ConfigA.class, "directQualifier"));
|
||||
assertThat(definition).isNotNull();
|
||||
@@ -87,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
|
||||
@@ -108,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
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
|
||||
@@ -56,8 +56,7 @@ public class SpyBeanOnTestFieldForExistingGenericBeanIntegrationTests {
|
||||
}
|
||||
|
||||
@Configuration
|
||||
@Import({ ExampleGenericServiceCaller.class,
|
||||
SimpleExampleIntegerGenericService.class })
|
||||
@Import({ ExampleGenericServiceCaller.class, SimpleExampleIntegerGenericService.class })
|
||||
static class SpyBeanOnTestFieldForExistingBeanConfig {
|
||||
|
||||
@Bean
|
||||
|
||||
@@ -37,8 +37,7 @@ import static org.mockito.Mockito.mock;
|
||||
*/
|
||||
public class SpyDefinitionTests {
|
||||
|
||||
private static final ResolvableType REAL_SERVICE_TYPE = ResolvableType
|
||||
.forClass(RealExampleService.class);
|
||||
private static final ResolvableType REAL_SERVICE_TYPE = ResolvableType.forClass(RealExampleService.class);
|
||||
|
||||
@Rule
|
||||
public ExpectedException thrown = ExpectedException.none();
|
||||
@@ -52,8 +51,7 @@ public class SpyDefinitionTests {
|
||||
|
||||
@Test
|
||||
public void createWithDefaults() throws Exception {
|
||||
SpyDefinition definition = new SpyDefinition(null, REAL_SERVICE_TYPE, null, true,
|
||||
null);
|
||||
SpyDefinition definition = new SpyDefinition(null, REAL_SERVICE_TYPE, null, true, null);
|
||||
assertThat(definition.getName()).isNull();
|
||||
assertThat(definition.getTypeToSpy()).isEqualTo(REAL_SERVICE_TYPE);
|
||||
assertThat(definition.getReset()).isEqualTo(MockReset.AFTER);
|
||||
@@ -64,8 +62,7 @@ public class SpyDefinitionTests {
|
||||
@Test
|
||||
public void createExplicit() throws Exception {
|
||||
QualifierDefinition qualifier = mock(QualifierDefinition.class);
|
||||
SpyDefinition definition = new SpyDefinition("name", REAL_SERVICE_TYPE,
|
||||
MockReset.BEFORE, false, qualifier);
|
||||
SpyDefinition definition = new SpyDefinition("name", REAL_SERVICE_TYPE, MockReset.BEFORE, false, qualifier);
|
||||
assertThat(definition.getName()).isEqualTo("name");
|
||||
assertThat(definition.getTypeToSpy()).isEqualTo(REAL_SERVICE_TYPE);
|
||||
assertThat(definition.getReset()).isEqualTo(MockReset.BEFORE);
|
||||
@@ -75,21 +72,18 @@ public class SpyDefinitionTests {
|
||||
|
||||
@Test
|
||||
public void createSpy() throws Exception {
|
||||
SpyDefinition definition = new SpyDefinition("name", REAL_SERVICE_TYPE,
|
||||
MockReset.BEFORE, true, null);
|
||||
SpyDefinition definition = new SpyDefinition("name", REAL_SERVICE_TYPE, MockReset.BEFORE, true, null);
|
||||
RealExampleService spy = definition.createSpy(new RealExampleService("hello"));
|
||||
MockCreationSettings<?> settings = MockitoApi.get().getMockSettings(spy);
|
||||
assertThat(spy).isInstanceOf(ExampleService.class);
|
||||
assertThat(settings.getMockName().toString()).isEqualTo("name");
|
||||
assertThat(settings.getDefaultAnswer())
|
||||
.isEqualTo(Answers.CALLS_REAL_METHODS.get());
|
||||
assertThat(settings.getDefaultAnswer()).isEqualTo(Answers.CALLS_REAL_METHODS.get());
|
||||
assertThat(MockReset.get(spy)).isEqualTo(MockReset.BEFORE);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void createSpyWhenNullInstanceShouldThrowException() throws Exception {
|
||||
SpyDefinition definition = new SpyDefinition("name", REAL_SERVICE_TYPE,
|
||||
MockReset.BEFORE, true, null);
|
||||
SpyDefinition definition = new SpyDefinition("name", REAL_SERVICE_TYPE, MockReset.BEFORE, true, null);
|
||||
this.thrown.expect(IllegalArgumentException.class);
|
||||
this.thrown.expectMessage("Instance must not be null");
|
||||
definition.createSpy(null);
|
||||
@@ -97,8 +91,7 @@ public class SpyDefinitionTests {
|
||||
|
||||
@Test
|
||||
public void createSpyWhenWrongInstanceShouldThrowException() throws Exception {
|
||||
SpyDefinition definition = new SpyDefinition("name", REAL_SERVICE_TYPE,
|
||||
MockReset.BEFORE, true, null);
|
||||
SpyDefinition definition = new SpyDefinition("name", REAL_SERVICE_TYPE, MockReset.BEFORE, true, null);
|
||||
this.thrown.expect(IllegalArgumentException.class);
|
||||
this.thrown.expectMessage("must be an instance of");
|
||||
definition.createSpy(new ExampleServiceCaller(null));
|
||||
@@ -106,8 +99,7 @@ public class SpyDefinitionTests {
|
||||
|
||||
@Test
|
||||
public void createSpyTwice() throws Exception {
|
||||
SpyDefinition definition = new SpyDefinition("name", REAL_SERVICE_TYPE,
|
||||
MockReset.BEFORE, true, null);
|
||||
SpyDefinition definition = new SpyDefinition("name", REAL_SERVICE_TYPE, MockReset.BEFORE, true, null);
|
||||
Object instance = new RealExampleService("hello");
|
||||
instance = definition.createSpy(instance);
|
||||
definition.createSpy(instance);
|
||||
|
||||
@@ -42,8 +42,7 @@ public class ExampleGenericServiceCaller {
|
||||
}
|
||||
|
||||
public String sayGreeting() {
|
||||
return "I say " + this.integerService.greeting() + " "
|
||||
+ this.stringService.greeting();
|
||||
return "I say " + this.integerService.greeting() + " " + this.stringService.greeting();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -25,8 +25,7 @@ public class ExampleGenericStringServiceCaller {
|
||||
|
||||
private final ExampleGenericService<String> stringService;
|
||||
|
||||
public ExampleGenericStringServiceCaller(
|
||||
ExampleGenericService<String> stringService) {
|
||||
public ExampleGenericStringServiceCaller(ExampleGenericService<String> stringService) {
|
||||
this.stringService = stringService;
|
||||
}
|
||||
|
||||
|
||||
@@ -21,8 +21,7 @@ package org.springframework.boot.test.mock.mockito.example;
|
||||
*
|
||||
* @author Phillip Webb
|
||||
*/
|
||||
public class SimpleExampleIntegerGenericService
|
||||
implements ExampleGenericService<Integer> {
|
||||
public class SimpleExampleIntegerGenericService implements ExampleGenericService<Integer> {
|
||||
|
||||
@Override
|
||||
public Integer greeting() {
|
||||
|
||||
@@ -65,8 +65,7 @@ public class SpringBootMockServletContextTests implements ServletContextAware {
|
||||
testResource("/inpublic", "/public");
|
||||
}
|
||||
|
||||
private void testResource(String path, String expectedLocation)
|
||||
throws MalformedURLException {
|
||||
private void testResource(String path, String expectedLocation) throws MalformedURLException {
|
||||
URL resource = this.servletContext.getResource(path);
|
||||
assertThat(resource).isNotNull();
|
||||
assertThat(resource.getPath()).contains(expectedLocation);
|
||||
@@ -75,8 +74,7 @@ public class SpringBootMockServletContextTests implements ServletContextAware {
|
||||
// gh-2654
|
||||
@Test
|
||||
public void getRootUrlExistsAndIsEmpty() throws Exception {
|
||||
SpringBootMockServletContext context = new SpringBootMockServletContext(
|
||||
"src/test/doesntexist") {
|
||||
SpringBootMockServletContext context = new SpringBootMockServletContext("src/test/doesntexist") {
|
||||
@Override
|
||||
protected String getResourceLocation(String path) {
|
||||
// Don't include the Spring Boot defaults for this test
|
||||
|
||||
@@ -42,8 +42,7 @@ public class OutputCaptureTests {
|
||||
System.out.println("Hello");
|
||||
this.outputCapture.reset();
|
||||
System.out.println("World");
|
||||
assertThat(this.outputCapture.toString()).doesNotContain("Hello")
|
||||
.contains("World");
|
||||
assertThat(this.outputCapture.toString()).doesNotContain("Hello").contains("World");
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -50,12 +50,11 @@ public abstract class AbstractConfigurationClassTests {
|
||||
public void allBeanMethodsArePublic() throws IOException, ClassNotFoundException {
|
||||
Set<String> nonPublicBeanMethods = new HashSet<String>();
|
||||
for (AnnotationMetadata configurationClass : findConfigurationClasses()) {
|
||||
Set<MethodMetadata> beanMethods = configurationClass
|
||||
.getAnnotatedMethods(Bean.class.getName());
|
||||
Set<MethodMetadata> beanMethods = configurationClass.getAnnotatedMethods(Bean.class.getName());
|
||||
for (MethodMetadata methodMetadata : beanMethods) {
|
||||
if (!isPublic(methodMetadata)) {
|
||||
nonPublicBeanMethods.add(methodMetadata.getDeclaringClassName() + "."
|
||||
+ methodMetadata.getMethodName());
|
||||
nonPublicBeanMethods
|
||||
.add(methodMetadata.getDeclaringClassName() + "." + methodMetadata.getMethodName());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -64,16 +63,13 @@ public abstract class AbstractConfigurationClassTests {
|
||||
|
||||
private Set<AnnotationMetadata> findConfigurationClasses() throws IOException {
|
||||
Set<AnnotationMetadata> configurationClasses = new HashSet<AnnotationMetadata>();
|
||||
Resource[] resources = this.resolver.getResources("classpath*:"
|
||||
+ getClass().getPackage().getName().replace('.', '/') + "/**/*.class");
|
||||
Resource[] resources = this.resolver
|
||||
.getResources("classpath*:" + getClass().getPackage().getName().replace('.', '/') + "/**/*.class");
|
||||
for (Resource resource : resources) {
|
||||
if (!isTestClass(resource)) {
|
||||
MetadataReader metadataReader = new SimpleMetadataReaderFactory()
|
||||
.getMetadataReader(resource);
|
||||
AnnotationMetadata annotationMetadata = metadataReader
|
||||
.getAnnotationMetadata();
|
||||
if (annotationMetadata.getAnnotationTypes()
|
||||
.contains(Configuration.class.getName())) {
|
||||
MetadataReader metadataReader = new SimpleMetadataReaderFactory().getMetadataReader(resource);
|
||||
AnnotationMetadata annotationMetadata = metadataReader.getAnnotationMetadata();
|
||||
if (annotationMetadata.getAnnotationTypes().contains(Configuration.class.getName())) {
|
||||
configurationClasses.add(annotationMetadata);
|
||||
}
|
||||
}
|
||||
@@ -82,13 +78,11 @@ public abstract class AbstractConfigurationClassTests {
|
||||
}
|
||||
|
||||
private boolean isTestClass(Resource resource) throws IOException {
|
||||
return resource.getFile().getAbsolutePath()
|
||||
.contains("target" + File.separator + "test-classes");
|
||||
return resource.getFile().getAbsolutePath().contains("target" + File.separator + "test-classes");
|
||||
}
|
||||
|
||||
private boolean isPublic(MethodMetadata methodMetadata) {
|
||||
int access = (Integer) new DirectFieldAccessor(methodMetadata)
|
||||
.getPropertyValue("access");
|
||||
int access = (Integer) new DirectFieldAccessor(methodMetadata).getPropertyValue("access");
|
||||
return (access & Opcodes.ACC_PUBLIC) != 0;
|
||||
}
|
||||
|
||||
|
||||
@@ -46,8 +46,7 @@ public class ApplicationContextTestUtilsTests {
|
||||
@Test
|
||||
public void closeContextAndParent() {
|
||||
ConfigurableApplicationContext mock = mock(ConfigurableApplicationContext.class);
|
||||
ConfigurableApplicationContext parent = mock(
|
||||
ConfigurableApplicationContext.class);
|
||||
ConfigurableApplicationContext parent = mock(ConfigurableApplicationContext.class);
|
||||
given(mock.getParent()).willReturn(parent);
|
||||
given(parent.getParent()).willReturn(null);
|
||||
ApplicationContextTestUtils.closeAll(mock);
|
||||
|
||||
@@ -54,24 +54,21 @@ public class LocalHostUriTemplateHandlerTests {
|
||||
public void getRootUriShouldUseLocalServerPort() throws Exception {
|
||||
MockEnvironment environment = new MockEnvironment();
|
||||
environment.setProperty("local.server.port", "1234");
|
||||
LocalHostUriTemplateHandler handler = new LocalHostUriTemplateHandler(
|
||||
environment);
|
||||
LocalHostUriTemplateHandler handler = new LocalHostUriTemplateHandler(environment);
|
||||
assertThat(handler.getRootUri()).isEqualTo("http://localhost:1234");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void getRootUriWhenLocalServerPortMissingShouldUsePort8080() throws Exception {
|
||||
MockEnvironment environment = new MockEnvironment();
|
||||
LocalHostUriTemplateHandler handler = new LocalHostUriTemplateHandler(
|
||||
environment);
|
||||
LocalHostUriTemplateHandler handler = new LocalHostUriTemplateHandler(environment);
|
||||
assertThat(handler.getRootUri()).isEqualTo("http://localhost:8080");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void getRootUriUsesCustomScheme() {
|
||||
MockEnvironment environment = new MockEnvironment();
|
||||
LocalHostUriTemplateHandler handler = new LocalHostUriTemplateHandler(environment,
|
||||
"https");
|
||||
LocalHostUriTemplateHandler handler = new LocalHostUriTemplateHandler(environment, "https");
|
||||
assertThat(handler.getRootUri()).isEqualTo("https://localhost:8080");
|
||||
}
|
||||
|
||||
@@ -79,8 +76,7 @@ public class LocalHostUriTemplateHandlerTests {
|
||||
public void getRootUriShouldUseContextPath() throws Exception {
|
||||
MockEnvironment environment = new MockEnvironment();
|
||||
environment.setProperty("server.contextPath", "/foo");
|
||||
LocalHostUriTemplateHandler handler = new LocalHostUriTemplateHandler(
|
||||
environment);
|
||||
LocalHostUriTemplateHandler handler = new LocalHostUriTemplateHandler(environment);
|
||||
assertThat(handler.getRootUri()).isEqualTo("http://localhost:8080/foo");
|
||||
}
|
||||
|
||||
|
||||
@@ -57,8 +57,7 @@ public class MockServerRestTemplateCustomizerTests {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void createWhenExpectationManagerClassIsNullShouldThrowException()
|
||||
throws Exception {
|
||||
public void createWhenExpectationManagerClassIsNullShouldThrowException() throws Exception {
|
||||
this.thrown.expect(IllegalArgumentException.class);
|
||||
this.thrown.expectMessage("ExpectationManager must not be null");
|
||||
new MockServerRestTemplateCustomizer(null);
|
||||
@@ -77,8 +76,7 @@ public class MockServerRestTemplateCustomizerTests {
|
||||
public void detectRootUriShouldDefaultToTrue() throws Exception {
|
||||
MockServerRestTemplateCustomizer customizer = new MockServerRestTemplateCustomizer(
|
||||
UnorderedRequestExpectationManager.class);
|
||||
customizer.customize(
|
||||
new RestTemplateBuilder().rootUri("https://example.com").build());
|
||||
customizer.customize(new RestTemplateBuilder().rootUri("https://example.com").build());
|
||||
assertThat(customizer.getServer()).extracting("expectationManager")
|
||||
.hasAtLeastOneElementOfType(RootUriRequestExpectationManager.class);
|
||||
}
|
||||
@@ -86,8 +84,7 @@ public class MockServerRestTemplateCustomizerTests {
|
||||
@Test
|
||||
public void setDetectRootUriShouldDisableRootUriDetection() throws Exception {
|
||||
this.customizer.setDetectRootUri(false);
|
||||
this.customizer.customize(
|
||||
new RestTemplateBuilder().rootUri("https://example.com").build());
|
||||
this.customizer.customize(new RestTemplateBuilder().rootUri("https://example.com").build());
|
||||
assertThat(this.customizer.getServer()).extracting("expectationManager")
|
||||
.hasAtLeastOneElementOfType(SimpleRequestExpectationManager.class);
|
||||
|
||||
@@ -110,8 +107,7 @@ public class MockServerRestTemplateCustomizerTests {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void getServerWhenMultipleServersAreBoundShouldThrowException()
|
||||
throws Exception {
|
||||
public void getServerWhenMultipleServersAreBoundShouldThrowException() throws Exception {
|
||||
this.customizer.customize(new RestTemplate());
|
||||
this.customizer.customize(new RestTemplate());
|
||||
this.thrown.expect(IllegalStateException.class);
|
||||
@@ -124,8 +120,7 @@ public class MockServerRestTemplateCustomizerTests {
|
||||
public void getServerWhenSingleServerIsBoundShouldReturnServer() throws Exception {
|
||||
RestTemplate template = new RestTemplate();
|
||||
this.customizer.customize(template);
|
||||
assertThat(this.customizer.getServer())
|
||||
.isEqualTo(this.customizer.getServer(template));
|
||||
assertThat(this.customizer.getServer()).isEqualTo(this.customizer.getServer(template));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -135,8 +130,7 @@ public class MockServerRestTemplateCustomizerTests {
|
||||
this.customizer.customize(template1);
|
||||
this.customizer.customize(template2);
|
||||
assertThat(this.customizer.getServer(template1)).isNotNull();
|
||||
assertThat(this.customizer.getServer(template2)).isNotNull()
|
||||
.isNotSameAs(this.customizer.getServer(template1));
|
||||
assertThat(this.customizer.getServer(template2)).isNotNull().isNotSameAs(this.customizer.getServer(template1));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -163,14 +157,10 @@ public class MockServerRestTemplateCustomizerTests {
|
||||
RestTemplate template2 = new RestTemplate();
|
||||
this.customizer.customize(template1);
|
||||
this.customizer.customize(template2);
|
||||
RequestExpectationManager manager1 = this.customizer.getExpectationManagers()
|
||||
.get(template1);
|
||||
RequestExpectationManager manager2 = this.customizer.getExpectationManagers()
|
||||
.get(template2);
|
||||
assertThat(this.customizer.getServer(template1)).extracting("expectationManager")
|
||||
.containsOnly(manager1);
|
||||
assertThat(this.customizer.getServer(template2)).extracting("expectationManager")
|
||||
.containsOnly(manager2);
|
||||
RequestExpectationManager manager1 = this.customizer.getExpectationManagers().get(template1);
|
||||
RequestExpectationManager manager2 = this.customizer.getExpectationManagers().get(template2);
|
||||
assertThat(this.customizer.getServer(template1)).extracting("expectationManager").containsOnly(manager1);
|
||||
assertThat(this.customizer.getServer(template2)).extracting("expectationManager").containsOnly(manager2);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -78,8 +78,7 @@ public class RootUriRequestExpectationManagerTests {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void createWhenExpectationManagerIsNullShouldThrowException()
|
||||
throws Exception {
|
||||
public void createWhenExpectationManagerIsNullShouldThrowException() throws Exception {
|
||||
this.thrown.expect(IllegalArgumentException.class);
|
||||
this.thrown.expectMessage("ExpectationManager must not be null");
|
||||
new RootUriRequestExpectationManager(this.uri, null);
|
||||
@@ -94,8 +93,7 @@ public class RootUriRequestExpectationManagerTests {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void validateRequestWhenUriDoesNotStartWithRootUriShouldDelegateToExpectationManager()
|
||||
throws Exception {
|
||||
public void validateRequestWhenUriDoesNotStartWithRootUriShouldDelegateToExpectationManager() throws Exception {
|
||||
ClientHttpRequest request = mock(ClientHttpRequest.class);
|
||||
given(request.getURI()).willReturn(new URI("https://spring.io/test"));
|
||||
this.manager.validateRequest(request);
|
||||
@@ -103,8 +101,7 @@ public class RootUriRequestExpectationManagerTests {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void validateRequestWhenUriStartsWithRootUriShouldReplaceUri()
|
||||
throws Exception {
|
||||
public void validateRequestWhenUriStartsWithRootUriShouldReplaceUri() throws Exception {
|
||||
ClientHttpRequest request = mock(ClientHttpRequest.class);
|
||||
given(request.getURI()).willReturn(new URI(this.uri + "/hello"));
|
||||
this.manager.validateRequest(request);
|
||||
@@ -115,13 +112,11 @@ public class RootUriRequestExpectationManagerTests {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void validateRequestWhenRequestUriAssertionIsThrownShouldReplaceUriInMessage()
|
||||
throws Exception {
|
||||
public void validateRequestWhenRequestUriAssertionIsThrownShouldReplaceUriInMessage() throws Exception {
|
||||
ClientHttpRequest request = mock(ClientHttpRequest.class);
|
||||
given(request.getURI()).willReturn(new URI(this.uri + "/hello"));
|
||||
given(this.delegate.validateRequest((ClientHttpRequest) any()))
|
||||
.willThrow(new AssertionError(
|
||||
"Request URI expected:</hello> was:<https://example.com/bad>"));
|
||||
.willThrow(new AssertionError("Request URI expected:</hello> was:<https://example.com/bad>"));
|
||||
this.thrown.expect(AssertionError.class);
|
||||
this.thrown.expectMessage("Request URI expected:<https://example.com/hello>");
|
||||
this.manager.validateRequest(request);
|
||||
@@ -136,17 +131,14 @@ public class RootUriRequestExpectationManagerTests {
|
||||
@Test
|
||||
public void bindToShouldReturnMockRestServiceServer() throws Exception {
|
||||
RestTemplate restTemplate = new RestTemplateBuilder().build();
|
||||
MockRestServiceServer bound = RootUriRequestExpectationManager
|
||||
.bindTo(restTemplate);
|
||||
MockRestServiceServer bound = RootUriRequestExpectationManager.bindTo(restTemplate);
|
||||
assertThat(bound).isNotNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void bindToWithExpectationManagerShouldReturnMockRestServiceServer()
|
||||
throws Exception {
|
||||
public void bindToWithExpectationManagerShouldReturnMockRestServiceServer() throws Exception {
|
||||
RestTemplate restTemplate = new RestTemplateBuilder().build();
|
||||
MockRestServiceServer bound = RootUriRequestExpectationManager
|
||||
.bindTo(restTemplate, this.delegate);
|
||||
MockRestServiceServer bound = RootUriRequestExpectationManager.bindTo(restTemplate, this.delegate);
|
||||
assertThat(bound).isNotNull();
|
||||
}
|
||||
|
||||
@@ -154,8 +146,8 @@ public class RootUriRequestExpectationManagerTests {
|
||||
public void forRestTemplateWhenUsingRootUriTemplateHandlerShouldReturnRootUriRequestExpectationManager()
|
||||
throws Exception {
|
||||
RestTemplate restTemplate = new RestTemplateBuilder().rootUri(this.uri).build();
|
||||
RequestExpectationManager actual = RootUriRequestExpectationManager
|
||||
.forRestTemplate(restTemplate, this.delegate);
|
||||
RequestExpectationManager actual = RootUriRequestExpectationManager.forRestTemplate(restTemplate,
|
||||
this.delegate);
|
||||
assertThat(actual).isInstanceOf(RootUriRequestExpectationManager.class);
|
||||
assertThat(actual).extracting("rootUri").containsExactly(this.uri);
|
||||
}
|
||||
@@ -164,31 +156,26 @@ public class RootUriRequestExpectationManagerTests {
|
||||
public void forRestTemplateWhenNotUsingRootUriTemplateHandlerShouldReturnOriginalRequestExpectationManager()
|
||||
throws Exception {
|
||||
RestTemplate restTemplate = new RestTemplateBuilder().build();
|
||||
RequestExpectationManager actual = RootUriRequestExpectationManager
|
||||
.forRestTemplate(restTemplate, this.delegate);
|
||||
RequestExpectationManager actual = RootUriRequestExpectationManager.forRestTemplate(restTemplate,
|
||||
this.delegate);
|
||||
assertThat(actual).isSameAs(this.delegate);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void boundRestTemplateShouldPrefixRootUri() {
|
||||
RestTemplate restTemplate = new RestTemplateBuilder()
|
||||
.rootUri("https://example.com").build();
|
||||
MockRestServiceServer server = RootUriRequestExpectationManager
|
||||
.bindTo(restTemplate);
|
||||
RestTemplate restTemplate = new RestTemplateBuilder().rootUri("https://example.com").build();
|
||||
MockRestServiceServer server = RootUriRequestExpectationManager.bindTo(restTemplate);
|
||||
server.expect(requestTo("/hello")).andRespond(withSuccess());
|
||||
restTemplate.getForEntity("/hello", String.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void boundRestTemplateWhenUrlIncludesDomainShouldNotPrefixRootUri() {
|
||||
RestTemplate restTemplate = new RestTemplateBuilder()
|
||||
.rootUri("https://example.com").build();
|
||||
MockRestServiceServer server = RootUriRequestExpectationManager
|
||||
.bindTo(restTemplate);
|
||||
RestTemplate restTemplate = new RestTemplateBuilder().rootUri("https://example.com").build();
|
||||
MockRestServiceServer server = RootUriRequestExpectationManager.bindTo(restTemplate);
|
||||
server.expect(requestTo("/hello")).andRespond(withSuccess());
|
||||
this.thrown.expect(AssertionError.class);
|
||||
this.thrown.expectMessage(
|
||||
"expected:<https://example.com/hello> but was:<https://spring.io/hello>");
|
||||
this.thrown.expectMessage("expected:<https://example.com/hello> but was:<https://spring.io/hello>");
|
||||
restTemplate.getForEntity("https://spring.io/hello", String.class);
|
||||
}
|
||||
|
||||
|
||||
@@ -83,15 +83,13 @@ public class TestRestTemplateTests {
|
||||
|
||||
@Test
|
||||
public void authenticated() {
|
||||
assertThat(new TestRestTemplate("user", "password").getRestTemplate()
|
||||
.getRequestFactory())
|
||||
.isInstanceOf(InterceptingClientHttpRequestFactory.class);
|
||||
assertThat(new TestRestTemplate("user", "password").getRestTemplate().getRequestFactory())
|
||||
.isInstanceOf(InterceptingClientHttpRequestFactory.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void options() throws Exception {
|
||||
TestRestTemplate template = new TestRestTemplate(
|
||||
HttpClientOption.ENABLE_REDIRECTS);
|
||||
TestRestTemplate template = new TestRestTemplate(HttpClientOption.ENABLE_REDIRECTS);
|
||||
CustomHttpComponentsClientHttpRequestFactory factory = (CustomHttpComponentsClientHttpRequestFactory) template
|
||||
.getRestTemplate().getRequestFactory();
|
||||
RequestConfig config = factory.getRequestConfig();
|
||||
@@ -101,22 +99,19 @@ public class TestRestTemplateTests {
|
||||
@Test
|
||||
public void restOperationsAreAvailable() throws Exception {
|
||||
RestTemplate delegate = mock(RestTemplate.class);
|
||||
given(delegate.getUriTemplateHandler())
|
||||
.willReturn(new DefaultUriTemplateHandler());
|
||||
given(delegate.getUriTemplateHandler()).willReturn(new DefaultUriTemplateHandler());
|
||||
final TestRestTemplate restTemplate = new TestRestTemplate(delegate);
|
||||
ReflectionUtils.doWithMethods(RestOperations.class, new MethodCallback() {
|
||||
|
||||
@Override
|
||||
public void doWith(Method method)
|
||||
throws IllegalArgumentException, IllegalAccessException {
|
||||
Method equivalent = ReflectionUtils.findMethod(TestRestTemplate.class,
|
||||
method.getName(), method.getParameterTypes());
|
||||
public void doWith(Method method) throws IllegalArgumentException, IllegalAccessException {
|
||||
Method equivalent = ReflectionUtils.findMethod(TestRestTemplate.class, method.getName(),
|
||||
method.getParameterTypes());
|
||||
assertThat(equivalent).as("Method %s not found", method).isNotNull();
|
||||
assertThat(Modifier.isPublic(equivalent.getModifiers()))
|
||||
.as("Method %s should have been public", equivalent).isTrue();
|
||||
try {
|
||||
equivalent.invoke(restTemplate,
|
||||
mockArguments(method.getParameterTypes()));
|
||||
equivalent.invoke(restTemplate, mockArguments(method.getParameterTypes()));
|
||||
}
|
||||
catch (Exception ex) {
|
||||
throw new IllegalStateException(ex);
|
||||
@@ -167,37 +162,30 @@ public class TestRestTemplateTests {
|
||||
@Test
|
||||
public void withBasicAuthAddsBasicAuthInterceptorWhenNotAlreadyPresent() {
|
||||
TestRestTemplate originalTemplate = new TestRestTemplate();
|
||||
TestRestTemplate basicAuthTemplate = originalTemplate.withBasicAuth("user",
|
||||
"password");
|
||||
TestRestTemplate basicAuthTemplate = originalTemplate.withBasicAuth("user", "password");
|
||||
assertThat(basicAuthTemplate.getRestTemplate().getMessageConverters())
|
||||
.containsExactlyElementsOf(
|
||||
originalTemplate.getRestTemplate().getMessageConverters());
|
||||
.containsExactlyElementsOf(originalTemplate.getRestTemplate().getMessageConverters());
|
||||
assertThat(basicAuthTemplate.getRestTemplate().getRequestFactory())
|
||||
.isInstanceOf(InterceptingClientHttpRequestFactory.class);
|
||||
assertThat(ReflectionTestUtils.getField(
|
||||
basicAuthTemplate.getRestTemplate().getRequestFactory(),
|
||||
"requestFactory"))
|
||||
assertThat(
|
||||
ReflectionTestUtils.getField(basicAuthTemplate.getRestTemplate().getRequestFactory(), "requestFactory"))
|
||||
.isInstanceOf(CustomHttpComponentsClientHttpRequestFactory.class);
|
||||
assertThat(basicAuthTemplate.getRestTemplate().getUriTemplateHandler())
|
||||
.isSameAs(originalTemplate.getRestTemplate().getUriTemplateHandler());
|
||||
assertThat(basicAuthTemplate.getRestTemplate().getInterceptors()).hasSize(1);
|
||||
assertBasicAuthorizationInterceptorCredentials(basicAuthTemplate, "user",
|
||||
"password");
|
||||
assertBasicAuthorizationInterceptorCredentials(basicAuthTemplate, "user", "password");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void withBasicAuthReplacesBasicAuthInterceptorWhenAlreadyPresent() {
|
||||
TestRestTemplate original = new TestRestTemplate("foo", "bar")
|
||||
.withBasicAuth("replace", "replace");
|
||||
TestRestTemplate original = new TestRestTemplate("foo", "bar").withBasicAuth("replace", "replace");
|
||||
TestRestTemplate basicAuth = original.withBasicAuth("user", "password");
|
||||
assertThat(basicAuth.getRestTemplate().getMessageConverters())
|
||||
.containsExactlyElementsOf(
|
||||
original.getRestTemplate().getMessageConverters());
|
||||
.containsExactlyElementsOf(original.getRestTemplate().getMessageConverters());
|
||||
assertThat(basicAuth.getRestTemplate().getRequestFactory())
|
||||
.isInstanceOf(InterceptingClientHttpRequestFactory.class);
|
||||
assertThat(ReflectionTestUtils.getField(
|
||||
basicAuth.getRestTemplate().getRequestFactory(), "requestFactory"))
|
||||
.isInstanceOf(CustomHttpComponentsClientHttpRequestFactory.class);
|
||||
assertThat(ReflectionTestUtils.getField(basicAuth.getRestTemplate().getRequestFactory(), "requestFactory"))
|
||||
.isInstanceOf(CustomHttpComponentsClientHttpRequestFactory.class);
|
||||
assertThat(basicAuth.getRestTemplate().getUriTemplateHandler())
|
||||
.isSameAs(original.getRestTemplate().getUriTemplateHandler());
|
||||
assertThat(basicAuth.getRestTemplate().getInterceptors()).hasSize(1);
|
||||
@@ -209,10 +197,8 @@ public class TestRestTemplateTests {
|
||||
TestRestTemplate originalTemplate = new TestRestTemplate("foo", "bar");
|
||||
ResponseErrorHandler errorHandler = mock(ResponseErrorHandler.class);
|
||||
originalTemplate.getRestTemplate().setErrorHandler(errorHandler);
|
||||
TestRestTemplate basicAuthTemplate = originalTemplate.withBasicAuth("user",
|
||||
"password");
|
||||
assertThat(basicAuthTemplate.getRestTemplate().getErrorHandler())
|
||||
.isSameAs(errorHandler);
|
||||
TestRestTemplate basicAuthTemplate = originalTemplate.withBasicAuth("user", "password");
|
||||
assertThat(basicAuthTemplate.getRestTemplate().getErrorHandler()).isSameAs(errorHandler);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -220,8 +206,7 @@ public class TestRestTemplateTests {
|
||||
verifyRelativeUriHandling(new TestRestTemplateCallback() {
|
||||
|
||||
@Override
|
||||
public void doWithTestRestTemplate(TestRestTemplate testRestTemplate,
|
||||
URI relativeUri) {
|
||||
public void doWithTestRestTemplate(TestRestTemplate testRestTemplate, URI relativeUri) {
|
||||
testRestTemplate.delete(relativeUri);
|
||||
}
|
||||
|
||||
@@ -229,31 +214,24 @@ public class TestRestTemplateTests {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void exchangeWithRequestEntityAndClassHandlesRelativeUris()
|
||||
throws IOException {
|
||||
public void exchangeWithRequestEntityAndClassHandlesRelativeUris() throws IOException {
|
||||
verifyRelativeUriHandling(new TestRestTemplateCallback() {
|
||||
|
||||
@Override
|
||||
public void doWithTestRestTemplate(TestRestTemplate testRestTemplate,
|
||||
URI relativeUri) {
|
||||
testRestTemplate.exchange(
|
||||
new RequestEntity<String>(HttpMethod.GET, relativeUri),
|
||||
String.class);
|
||||
public void doWithTestRestTemplate(TestRestTemplate testRestTemplate, URI relativeUri) {
|
||||
testRestTemplate.exchange(new RequestEntity<String>(HttpMethod.GET, relativeUri), String.class);
|
||||
}
|
||||
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
public void exchangeWithRequestEntityAndParameterizedTypeReferenceHandlesRelativeUris()
|
||||
throws IOException {
|
||||
public void exchangeWithRequestEntityAndParameterizedTypeReferenceHandlesRelativeUris() throws IOException {
|
||||
verifyRelativeUriHandling(new TestRestTemplateCallback() {
|
||||
|
||||
@Override
|
||||
public void doWithTestRestTemplate(TestRestTemplate testRestTemplate,
|
||||
URI relativeUri) {
|
||||
testRestTemplate.exchange(
|
||||
new RequestEntity<String>(HttpMethod.GET, relativeUri),
|
||||
public void doWithTestRestTemplate(TestRestTemplate testRestTemplate, URI relativeUri) {
|
||||
testRestTemplate.exchange(new RequestEntity<String>(HttpMethod.GET, relativeUri),
|
||||
new ParameterizedTypeReference<String>() {
|
||||
});
|
||||
}
|
||||
@@ -266,25 +244,21 @@ public class TestRestTemplateTests {
|
||||
verifyRelativeUriHandling(new TestRestTemplateCallback() {
|
||||
|
||||
@Override
|
||||
public void doWithTestRestTemplate(TestRestTemplate testRestTemplate,
|
||||
URI relativeUri) {
|
||||
testRestTemplate.exchange(relativeUri, HttpMethod.GET,
|
||||
new HttpEntity<byte[]>(new byte[0]), String.class);
|
||||
public void doWithTestRestTemplate(TestRestTemplate testRestTemplate, URI relativeUri) {
|
||||
testRestTemplate.exchange(relativeUri, HttpMethod.GET, new HttpEntity<byte[]>(new byte[0]),
|
||||
String.class);
|
||||
}
|
||||
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
public void exchangeWithParameterizedTypeReferenceHandlesRelativeUris()
|
||||
throws IOException {
|
||||
public void exchangeWithParameterizedTypeReferenceHandlesRelativeUris() throws IOException {
|
||||
verifyRelativeUriHandling(new TestRestTemplateCallback() {
|
||||
|
||||
@Override
|
||||
public void doWithTestRestTemplate(TestRestTemplate testRestTemplate,
|
||||
URI relativeUri) {
|
||||
testRestTemplate.exchange(relativeUri, HttpMethod.GET,
|
||||
new HttpEntity<byte[]>(new byte[0]),
|
||||
public void doWithTestRestTemplate(TestRestTemplate testRestTemplate, URI relativeUri) {
|
||||
testRestTemplate.exchange(relativeUri, HttpMethod.GET, new HttpEntity<byte[]>(new byte[0]),
|
||||
new ParameterizedTypeReference<String>() {
|
||||
});
|
||||
}
|
||||
@@ -297,8 +271,7 @@ public class TestRestTemplateTests {
|
||||
verifyRelativeUriHandling(new TestRestTemplateCallback() {
|
||||
|
||||
@Override
|
||||
public void doWithTestRestTemplate(TestRestTemplate testRestTemplate,
|
||||
URI relativeUri) {
|
||||
public void doWithTestRestTemplate(TestRestTemplate testRestTemplate, URI relativeUri) {
|
||||
testRestTemplate.execute(relativeUri, HttpMethod.GET, null, null);
|
||||
}
|
||||
|
||||
@@ -310,8 +283,7 @@ public class TestRestTemplateTests {
|
||||
verifyRelativeUriHandling(new TestRestTemplateCallback() {
|
||||
|
||||
@Override
|
||||
public void doWithTestRestTemplate(TestRestTemplate testRestTemplate,
|
||||
URI relativeUri) {
|
||||
public void doWithTestRestTemplate(TestRestTemplate testRestTemplate, URI relativeUri) {
|
||||
testRestTemplate.getForEntity(relativeUri, String.class);
|
||||
}
|
||||
|
||||
@@ -323,8 +295,7 @@ public class TestRestTemplateTests {
|
||||
verifyRelativeUriHandling(new TestRestTemplateCallback() {
|
||||
|
||||
@Override
|
||||
public void doWithTestRestTemplate(TestRestTemplate testRestTemplate,
|
||||
URI relativeUri) {
|
||||
public void doWithTestRestTemplate(TestRestTemplate testRestTemplate, URI relativeUri) {
|
||||
testRestTemplate.getForObject(relativeUri, String.class);
|
||||
}
|
||||
|
||||
@@ -336,8 +307,7 @@ public class TestRestTemplateTests {
|
||||
verifyRelativeUriHandling(new TestRestTemplateCallback() {
|
||||
|
||||
@Override
|
||||
public void doWithTestRestTemplate(TestRestTemplate testRestTemplate,
|
||||
URI relativeUri) {
|
||||
public void doWithTestRestTemplate(TestRestTemplate testRestTemplate, URI relativeUri) {
|
||||
testRestTemplate.headForHeaders(relativeUri);
|
||||
}
|
||||
|
||||
@@ -349,8 +319,7 @@ public class TestRestTemplateTests {
|
||||
verifyRelativeUriHandling(new TestRestTemplateCallback() {
|
||||
|
||||
@Override
|
||||
public void doWithTestRestTemplate(TestRestTemplate testRestTemplate,
|
||||
URI relativeUri) {
|
||||
public void doWithTestRestTemplate(TestRestTemplate testRestTemplate, URI relativeUri) {
|
||||
testRestTemplate.optionsForAllow(relativeUri);
|
||||
}
|
||||
|
||||
@@ -362,8 +331,7 @@ public class TestRestTemplateTests {
|
||||
verifyRelativeUriHandling(new TestRestTemplateCallback() {
|
||||
|
||||
@Override
|
||||
public void doWithTestRestTemplate(TestRestTemplate testRestTemplate,
|
||||
URI relativeUri) {
|
||||
public void doWithTestRestTemplate(TestRestTemplate testRestTemplate, URI relativeUri) {
|
||||
testRestTemplate.patchForObject(relativeUri, "hello", String.class);
|
||||
}
|
||||
|
||||
@@ -375,8 +343,7 @@ public class TestRestTemplateTests {
|
||||
verifyRelativeUriHandling(new TestRestTemplateCallback() {
|
||||
|
||||
@Override
|
||||
public void doWithTestRestTemplate(TestRestTemplate testRestTemplate,
|
||||
URI relativeUri) {
|
||||
public void doWithTestRestTemplate(TestRestTemplate testRestTemplate, URI relativeUri) {
|
||||
testRestTemplate.postForEntity(relativeUri, "hello", String.class);
|
||||
}
|
||||
|
||||
@@ -388,8 +355,7 @@ public class TestRestTemplateTests {
|
||||
verifyRelativeUriHandling(new TestRestTemplateCallback() {
|
||||
|
||||
@Override
|
||||
public void doWithTestRestTemplate(TestRestTemplate testRestTemplate,
|
||||
URI relativeUri) {
|
||||
public void doWithTestRestTemplate(TestRestTemplate testRestTemplate, URI relativeUri) {
|
||||
testRestTemplate.postForLocation(relativeUri, "hello");
|
||||
}
|
||||
|
||||
@@ -401,8 +367,7 @@ public class TestRestTemplateTests {
|
||||
verifyRelativeUriHandling(new TestRestTemplateCallback() {
|
||||
|
||||
@Override
|
||||
public void doWithTestRestTemplate(TestRestTemplate testRestTemplate,
|
||||
URI relativeUri) {
|
||||
public void doWithTestRestTemplate(TestRestTemplate testRestTemplate, URI relativeUri) {
|
||||
testRestTemplate.postForObject(relativeUri, "hello", String.class);
|
||||
}
|
||||
|
||||
@@ -414,47 +379,38 @@ public class TestRestTemplateTests {
|
||||
verifyRelativeUriHandling(new TestRestTemplateCallback() {
|
||||
|
||||
@Override
|
||||
public void doWithTestRestTemplate(TestRestTemplate testRestTemplate,
|
||||
URI relativeUri) {
|
||||
public void doWithTestRestTemplate(TestRestTemplate testRestTemplate, URI relativeUri) {
|
||||
testRestTemplate.put(relativeUri, "hello");
|
||||
}
|
||||
|
||||
});
|
||||
}
|
||||
|
||||
private void verifyRelativeUriHandling(TestRestTemplateCallback callback)
|
||||
throws IOException {
|
||||
private void verifyRelativeUriHandling(TestRestTemplateCallback callback) throws IOException {
|
||||
ClientHttpRequestFactory requestFactory = mock(ClientHttpRequestFactory.class);
|
||||
MockClientHttpRequest request = new MockClientHttpRequest();
|
||||
request.setResponse(new MockClientHttpResponse(new byte[0], HttpStatus.OK));
|
||||
URI absoluteUri = URI
|
||||
.create("http://localhost:8080/a/b/c.txt?param=%7Bsomething%7D");
|
||||
given(requestFactory.createRequest(eq(absoluteUri), (HttpMethod) any()))
|
||||
.willReturn(request);
|
||||
URI absoluteUri = URI.create("http://localhost:8080/a/b/c.txt?param=%7Bsomething%7D");
|
||||
given(requestFactory.createRequest(eq(absoluteUri), (HttpMethod) any())).willReturn(request);
|
||||
RestTemplate delegate = new RestTemplate();
|
||||
TestRestTemplate template = new TestRestTemplate(delegate);
|
||||
delegate.setRequestFactory(requestFactory);
|
||||
LocalHostUriTemplateHandler uriTemplateHandler = new LocalHostUriTemplateHandler(
|
||||
new MockEnvironment());
|
||||
LocalHostUriTemplateHandler uriTemplateHandler = new LocalHostUriTemplateHandler(new MockEnvironment());
|
||||
template.setUriTemplateHandler(uriTemplateHandler);
|
||||
callback.doWithTestRestTemplate(template,
|
||||
URI.create("/a/b/c.txt?param=%7Bsomething%7D"));
|
||||
callback.doWithTestRestTemplate(template, URI.create("/a/b/c.txt?param=%7Bsomething%7D"));
|
||||
verify(requestFactory).createRequest(eq(absoluteUri), (HttpMethod) any());
|
||||
}
|
||||
|
||||
private void assertBasicAuthorizationInterceptorCredentials(
|
||||
TestRestTemplate testRestTemplate, String username, String password) {
|
||||
private void assertBasicAuthorizationInterceptorCredentials(TestRestTemplate testRestTemplate, String username,
|
||||
String password) {
|
||||
@SuppressWarnings("unchecked")
|
||||
List<ClientHttpRequestInterceptor> requestFactoryInterceptors = (List<ClientHttpRequestInterceptor>) ReflectionTestUtils
|
||||
.getField(testRestTemplate.getRestTemplate().getRequestFactory(),
|
||||
"interceptors");
|
||||
.getField(testRestTemplate.getRestTemplate().getRequestFactory(), "interceptors");
|
||||
assertThat(requestFactoryInterceptors).hasSize(1);
|
||||
ClientHttpRequestInterceptor interceptor = requestFactoryInterceptors.get(0);
|
||||
assertThat(interceptor).isInstanceOf(BasicAuthorizationInterceptor.class);
|
||||
assertThat(ReflectionTestUtils.getField(interceptor, "username"))
|
||||
.isEqualTo(username);
|
||||
assertThat(ReflectionTestUtils.getField(interceptor, "password"))
|
||||
.isEqualTo(password);
|
||||
assertThat(ReflectionTestUtils.getField(interceptor, "username")).isEqualTo(username);
|
||||
assertThat(ReflectionTestUtils.getField(interceptor, "password")).isEqualTo(password);
|
||||
|
||||
}
|
||||
|
||||
|
||||
@@ -73,13 +73,11 @@ public class LocalHostWebClientTests {
|
||||
client.setWebConnection(connection);
|
||||
client.getPage("/test");
|
||||
verify(connection).getResponse(this.requestCaptor.capture());
|
||||
assertThat(this.requestCaptor.getValue().getUrl())
|
||||
.isEqualTo(new URL("http://localhost:8080/test"));
|
||||
assertThat(this.requestCaptor.getValue().getUrl()).isEqualTo(new URL("http://localhost:8080/test"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void getPageWhenUrlIsRelativeAndHasPortWillUseLocalhostPort()
|
||||
throws Exception {
|
||||
public void getPageWhenUrlIsRelativeAndHasPortWillUseLocalhostPort() throws Exception {
|
||||
MockEnvironment environment = new MockEnvironment();
|
||||
environment.setProperty("local.server.port", "8181");
|
||||
WebClient client = new LocalHostWebClient(environment);
|
||||
@@ -87,8 +85,7 @@ public class LocalHostWebClientTests {
|
||||
client.setWebConnection(connection);
|
||||
client.getPage("/test");
|
||||
verify(connection).getResponse(this.requestCaptor.capture());
|
||||
assertThat(this.requestCaptor.getValue().getUrl())
|
||||
.isEqualTo(new URL("http://localhost:8181/test"));
|
||||
assertThat(this.requestCaptor.getValue().getUrl()).isEqualTo(new URL("http://localhost:8181/test"));
|
||||
}
|
||||
|
||||
private WebConnection mockConnection() throws MalformedURLException, IOException {
|
||||
|
||||
@@ -61,24 +61,21 @@ public class LocalHostWebConnectionHtmlUnitDriverTests {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void createWithJavascriptFlagWhenEnvironmentIsNullWillThrowException()
|
||||
throws Exception {
|
||||
public void createWithJavascriptFlagWhenEnvironmentIsNullWillThrowException() throws Exception {
|
||||
this.thrown.expect(IllegalArgumentException.class);
|
||||
this.thrown.expectMessage("Environment must not be null");
|
||||
new LocalHostWebConnectionHtmlUnitDriver(null, true);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void createWithBrowserVersionWhenEnvironmentIsNullWillThrowException()
|
||||
throws Exception {
|
||||
public void createWithBrowserVersionWhenEnvironmentIsNullWillThrowException() throws Exception {
|
||||
this.thrown.expect(IllegalArgumentException.class);
|
||||
this.thrown.expectMessage("Environment must not be null");
|
||||
new LocalHostWebConnectionHtmlUnitDriver(null, BrowserVersion.CHROME);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void createWithCapabilitiesWhenEnvironmentIsNullWillThrowException()
|
||||
throws Exception {
|
||||
public void createWithCapabilitiesWhenEnvironmentIsNullWillThrowException() throws Exception {
|
||||
this.thrown.expect(IllegalArgumentException.class);
|
||||
this.thrown.expectMessage("Environment must not be null");
|
||||
Capabilities capabilities = mock(Capabilities.class);
|
||||
@@ -89,8 +86,7 @@ public class LocalHostWebConnectionHtmlUnitDriverTests {
|
||||
@Test
|
||||
public void getWhenUrlIsRelativeAndNoPortWillUseLocalhost8080() throws Exception {
|
||||
MockEnvironment environment = new MockEnvironment();
|
||||
LocalHostWebConnectionHtmlUnitDriver driver = new TestLocalHostWebConnectionHtmlUnitDriver(
|
||||
environment);
|
||||
LocalHostWebConnectionHtmlUnitDriver driver = new TestLocalHostWebConnectionHtmlUnitDriver(environment);
|
||||
driver.get("/test");
|
||||
verify(this.webClient).getPage(new URL("http://localhost:8080/test"));
|
||||
}
|
||||
@@ -99,14 +95,12 @@ public class LocalHostWebConnectionHtmlUnitDriverTests {
|
||||
public void getWhenUrlIsRelativeAndHasPortWillUseLocalhostPort() throws Exception {
|
||||
MockEnvironment environment = new MockEnvironment();
|
||||
environment.setProperty("local.server.port", "8181");
|
||||
LocalHostWebConnectionHtmlUnitDriver driver = new TestLocalHostWebConnectionHtmlUnitDriver(
|
||||
environment);
|
||||
LocalHostWebConnectionHtmlUnitDriver driver = new TestLocalHostWebConnectionHtmlUnitDriver(environment);
|
||||
driver.get("/test");
|
||||
verify(this.webClient).getPage(new URL("http://localhost:8181/test"));
|
||||
}
|
||||
|
||||
public class TestLocalHostWebConnectionHtmlUnitDriver
|
||||
extends LocalHostWebConnectionHtmlUnitDriver {
|
||||
public class TestLocalHostWebConnectionHtmlUnitDriver extends LocalHostWebConnectionHtmlUnitDriver {
|
||||
|
||||
public TestLocalHostWebConnectionHtmlUnitDriver(Environment environment) {
|
||||
super(environment);
|
||||
|
||||
Reference in New Issue
Block a user