Merge branch '1.5.x' into 2.0.x

This commit is contained in:
Andy Wilkinson
2019-06-07 10:46:31 +01:00
2320 changed files with 23858 additions and 39476 deletions

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -66,15 +66,13 @@ public abstract class AbstractSpringBootTestEmbeddedReactiveWebEnvironmentTests
@Test
public void runAndTestHttpEndpoint() {
assertThat(this.port).isNotEqualTo(8080).isNotEqualTo(0);
WebTestClient.bindToServer().baseUrl("http://localhost:" + this.port).build()
.get().uri("/").exchange().expectBody(String.class)
.isEqualTo("Hello World");
WebTestClient.bindToServer().baseUrl("http://localhost:" + this.port).build().get().uri("/").exchange()
.expectBody(String.class).isEqualTo("Hello World");
}
@Test
public void injectWebTestClient() {
this.webClient.get().uri("/").exchange().expectBody(String.class)
.isEqualTo("Hello World");
this.webClient.get().uri("/").exchange().expectBody(String.class).isEqualTo("Hello World");
}
@Test

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -70,8 +70,7 @@ public abstract class AbstractSpringBootTestWebServerWebEnvironmentTests {
@Test
public void runAndTestHttpEndpoint() {
assertThat(this.port).isNotEqualTo(8080).isNotEqualTo(0);
String body = new RestTemplate()
.getForObject("http://localhost:" + this.port + "/", String.class);
String body = new RestTemplate().getForObject("http://localhost:" + this.port + "/", String.class);
assertThat(body).isEqualTo("Hello World");
}
@@ -88,8 +87,7 @@ public abstract class AbstractSpringBootTestWebServerWebEnvironmentTests {
@Test
public void validateWebApplicationContextIsSet() {
assertThat(this.context).isSameAs(
WebApplicationContextUtils.getWebApplicationContext(this.servletContext));
assertThat(this.context).isSameAs(WebApplicationContextUtils.getWebApplicationContext(this.servletContext));
}
protected abstract static class AbstractConfig {

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -33,8 +33,7 @@ public class FilteredClassLoaderTests {
public ExpectedException thrown = ExpectedException.none();
@Test
public void loadClassWhenFilteredOnPackageShouldThrowClassNotFound()
throws Exception {
public void loadClassWhenFilteredOnPackageShouldThrowClassNotFound() throws Exception {
FilteredClassLoader classLoader = new FilteredClassLoader(
FilteredClassLoaderTests.class.getPackage().getName());
this.thrown.expect(ClassNotFoundException.class);
@@ -44,8 +43,7 @@ public class FilteredClassLoaderTests {
@Test
public void loadClassWhenFilteredOnClassShouldThrowClassNotFound() throws Exception {
try (FilteredClassLoader classLoader = new FilteredClassLoader(
FilteredClassLoaderTests.class)) {
try (FilteredClassLoader classLoader = new FilteredClassLoader(FilteredClassLoaderTests.class)) {
this.thrown.expect(ClassNotFoundException.class);
classLoader.loadClass(getClass().getName());
}

View File

@@ -49,39 +49,32 @@ public class ImportsContextCustomizerFactoryTests {
@Test
public void getContextCustomizerWhenHasNoImportAnnotationShouldReturnNull() {
ContextCustomizer customizer = this.factory
.createContextCustomizer(TestWithNoImport.class, null);
ContextCustomizer customizer = this.factory.createContextCustomizer(TestWithNoImport.class, null);
assertThat(customizer).isNull();
}
@Test
public void getContextCustomizerWhenHasImportAnnotationShouldReturnCustomizer() {
ContextCustomizer customizer = this.factory
.createContextCustomizer(TestWithImport.class, null);
ContextCustomizer customizer = this.factory.createContextCustomizer(TestWithImport.class, null);
assertThat(customizer).isNotNull();
}
@Test
public void getContextCustomizerWhenHasMetaImportAnnotationShouldReturnCustomizer() {
ContextCustomizer customizer = this.factory
.createContextCustomizer(TestWithMetaImport.class, null);
ContextCustomizer customizer = this.factory.createContextCustomizer(TestWithMetaImport.class, null);
assertThat(customizer).isNotNull();
}
@Test
public void contextCustomizerEqualsAndHashCode() {
ContextCustomizer customizer1 = this.factory
.createContextCustomizer(TestWithImport.class, null);
ContextCustomizer customizer2 = this.factory
.createContextCustomizer(TestWithImport.class, null);
ContextCustomizer customizer3 = this.factory
.createContextCustomizer(TestWithImportAndMetaImport.class, null);
ContextCustomizer customizer4 = this.factory
.createContextCustomizer(TestWithSameImportAndMetaImport.class, null);
ContextCustomizer customizer1 = this.factory.createContextCustomizer(TestWithImport.class, null);
ContextCustomizer customizer2 = this.factory.createContextCustomizer(TestWithImport.class, null);
ContextCustomizer customizer3 = this.factory.createContextCustomizer(TestWithImportAndMetaImport.class, null);
ContextCustomizer customizer4 = this.factory.createContextCustomizer(TestWithSameImportAndMetaImport.class,
null);
assertThat(customizer1.hashCode()).isEqualTo(customizer1.hashCode());
assertThat(customizer1.hashCode()).isEqualTo(customizer2.hashCode());
assertThat(customizer1).isEqualTo(customizer1).isEqualTo(customizer2)
.isNotEqualTo(customizer3);
assertThat(customizer1).isEqualTo(customizer1).isEqualTo(customizer2).isNotEqualTo(customizer3);
assertThat(customizer3).isEqualTo(customizer4);
}
@@ -94,8 +87,7 @@ public class ImportsContextCustomizerFactoryTests {
@Test
public void contextCustomizerImportsBeans() {
ContextCustomizer customizer = this.factory
.createContextCustomizer(TestWithImport.class, null);
ContextCustomizer customizer = this.factory.createContextCustomizer(TestWithImport.class, null);
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
customizer.customizeContext(context, mock(MergedContextConfiguration.class));
context.refresh();
@@ -104,8 +96,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 {

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2017 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -45,38 +45,31 @@ public class ImportsContextCustomizerTests {
@Test
public void importSelectorsCouldUseAnyAnnotations() {
assertThat(new ImportsContextCustomizer(FirstImportSelectorAnnotatedClass.class))
.isNotEqualTo(new ImportsContextCustomizer(
SecondImportSelectorAnnotatedClass.class));
.isNotEqualTo(new ImportsContextCustomizer(SecondImportSelectorAnnotatedClass.class));
}
@Test
public void determinableImportSelector() {
assertThat(new ImportsContextCustomizer(
FirstDeterminableImportSelectorAnnotatedClass.class))
.isEqualTo(new ImportsContextCustomizer(
SecondDeterminableImportSelectorAnnotatedClass.class));
assertThat(new ImportsContextCustomizer(FirstDeterminableImportSelectorAnnotatedClass.class))
.isEqualTo(new ImportsContextCustomizer(SecondDeterminableImportSelectorAnnotatedClass.class));
}
@Test
public void customizersForTestClassesWithDifferentKotlinMetadataAreEqual() {
assertThat(new ImportsContextCustomizer(FirstKotlinAnnotatedTestClass.class))
.isEqualTo(new ImportsContextCustomizer(
SecondKotlinAnnotatedTestClass.class));
.isEqualTo(new ImportsContextCustomizer(SecondKotlinAnnotatedTestClass.class));
}
@Test
public void customizersForTestClassesWithDifferentSpockFrameworkAnnotationsAreEqual() {
assertThat(
new ImportsContextCustomizer(FirstSpockFrameworkAnnotatedTestClass.class))
.isEqualTo(new ImportsContextCustomizer(
SecondSpockFrameworkAnnotatedTestClass.class));
assertThat(new ImportsContextCustomizer(FirstSpockFrameworkAnnotatedTestClass.class))
.isEqualTo(new ImportsContextCustomizer(SecondSpockFrameworkAnnotatedTestClass.class));
}
@Test
public void customizersForTestClassesWithDifferentSpockLangAnnotationsAreEqual() {
assertThat(new ImportsContextCustomizer(FirstSpockLangAnnotatedTestClass.class))
.isEqualTo(new ImportsContextCustomizer(
SecondSpockLangAnnotatedTestClass.class));
.isEqualTo(new ImportsContextCustomizer(SecondSpockLangAnnotatedTestClass.class));
}
@Import(TestImportSelector.class)
@@ -152,8 +145,7 @@ public class ImportsContextCustomizerTests {
}
static class TestDeterminableImportSelector
implements ImportSelector, DeterminableImports {
static class TestDeterminableImportSelector implements ImportSelector, DeterminableImports {
@Override
public String[] selectImports(AnnotationMetadata arg0) {

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2017 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -65,8 +65,7 @@ public class 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);
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2017 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -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

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2017 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -74,8 +74,7 @@ public class SpringBootContextLoaderTests {
@Test
public void environmentPropertiesAnotherSeparatorInValue() {
Map<String, Object> config = getEnvironmentProperties(
AnotherSeparatorInValue.class);
Map<String, Object> config = getEnvironmentProperties(AnotherSeparatorInValue.class);
assertKey(config, "key", "my:Value");
assertKey(config, "anotherKey", "another=Value");
}
@@ -90,12 +89,10 @@ public class SpringBootContextLoaderTests {
}
private Map<String, Object> getEnvironmentProperties(Class<?> testClass) {
TestContext context = new ExposedTestContextManager(testClass)
.getExposedTestContext();
MergedContextConfiguration config = (MergedContextConfiguration) ReflectionTestUtils
.getField(context, "mergedContextConfiguration");
return TestPropertySourceUtils
.convertInlinedPropertiesToMap(config.getPropertySourceProperties());
TestContext context = new ExposedTestContextManager(testClass).getExposedTestContext();
MergedContextConfiguration config = (MergedContextConfiguration) ReflectionTestUtils.getField(context,
"mergedContextConfiguration");
return TestPropertySourceUtils.convertInlinedPropertiesToMap(config.getPropertySourceProperties());
}
private void assertKey(Map<String, Object> actual, String key, Object value) {

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2017 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -44,8 +44,7 @@ public class SpringBootTestActiveProfileTests {
@Test
public void profiles() {
assertThat(this.context.getEnvironment().getActiveProfiles())
.containsExactly("override");
assertThat(this.context.getEnvironment().getActiveProfiles()).containsExactly("override");
}
@Configuration

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2017 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -33,8 +33,8 @@ import org.springframework.web.reactive.config.EnableWebFlux;
*/
@RunWith(SpringRunner.class)
@DirtiesContext
@SpringBootTest(webEnvironment = WebEnvironment.DEFINED_PORT, properties = {
"spring.main.web-application-type=reactive", "server.port=0", "value=123" })
@SpringBootTest(webEnvironment = WebEnvironment.DEFINED_PORT,
properties = { "spring.main.web-application-type=reactive", "server.port=0", "value=123" })
public class SpringBootTestReactiveWebEnvironmentDefinedPortTests
extends AbstractSpringBootTestEmbeddedReactiveWebEnvironmentTests {

View File

@@ -45,8 +45,7 @@ public class SpringBootTestReactiveWebEnvironmentUserDefinedTestRestTemplateTest
@Test
public void restTemplateIsUserDefined() {
assertThat(getContext().getBean("testRestTemplate"))
.isInstanceOf(RestTemplate.class);
assertThat(getContext().getBean("testRestTemplate")).isInstanceOf(RestTemplate.class);
}
@Configuration

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2017 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -40,13 +40,11 @@ import static org.assertj.core.api.Assertions.assertThat;
@RunWith(SpringRunner.class)
@DirtiesContext
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, properties = { "value=123" })
public class SpringBootTestUserDefinedTestRestTemplateTests
extends AbstractSpringBootTestWebServerWebEnvironmentTests {
public class SpringBootTestUserDefinedTestRestTemplateTests extends AbstractSpringBootTestWebServerWebEnvironmentTests {
@Test
public void restTemplateIsUserDefined() {
assertThat(getContext().getBean("testRestTemplate"))
.isInstanceOf(RestTemplate.class);
assertThat(getContext().getBean("testRestTemplate")).isInstanceOf(RestTemplate.class);
}
// gh-7711

View File

@@ -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 {

View File

@@ -33,10 +33,8 @@ import org.springframework.web.servlet.config.annotation.EnableWebMvc;
*/
@RunWith(SpringRunner.class)
@DirtiesContext
@SpringBootTest(webEnvironment = WebEnvironment.DEFINED_PORT,
properties = { "server.port=0", "value=123" })
public class SpringBootTestWebEnvironmentDefinedPortTests
extends AbstractSpringBootTestWebServerWebEnvironmentTests {
@SpringBootTest(webEnvironment = WebEnvironment.DEFINED_PORT, properties = { "server.port=0", "value=123" })
public class SpringBootTestWebEnvironmentDefinedPortTests extends AbstractSpringBootTestWebServerWebEnvironmentTests {
@Configuration
@EnableWebMvc

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2017 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -78,8 +78,7 @@ public class SpringBootTestWebEnvironmentMockTests {
@Test
public void resourcePath() {
assertThat(ReflectionTestUtils.getField(this.servletContext, "resourceBasePath"))
.isEqualTo("src/main/webapp");
assertThat(ReflectionTestUtils.getField(this.servletContext, "resourceBasePath")).isEqualTo("src/main/webapp");
}
@Configuration

View File

@@ -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

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2017 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -40,8 +40,7 @@ import static org.assertj.core.api.Assertions.assertThat;
@RunWith(SpringRunner.class)
@DirtiesContext
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, properties = { "value=123" })
public class SpringBootTestWebEnvironmentRandomPortTests
extends AbstractSpringBootTestWebServerWebEnvironmentTests {
public class SpringBootTestWebEnvironmentRandomPortTests extends AbstractSpringBootTestWebServerWebEnvironmentTests {
@Test
public void testRestTemplateShouldUseBuilder() {
@@ -56,8 +55,7 @@ public class SpringBootTestWebEnvironmentRandomPortTests
@Bean
public RestTemplateBuilder restTemplateBuilder() {
return new RestTemplateBuilder()
.additionalMessageConverters(new MyConverter());
return new RestTemplateBuilder().additionalMessageConverters(new MyConverter());
}

View File

@@ -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

View File

@@ -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

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2017 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -67,24 +67,21 @@ public class ApplicationContextAssertProviderTests {
public void getWhenTypeIsNullShouldThrowException() {
this.thrown.expect(IllegalArgumentException.class);
this.thrown.expectMessage("Type must not be null");
ApplicationContextAssertProvider.get(null, ApplicationContext.class,
this.mockContextSupplier);
ApplicationContextAssertProvider.get(null, ApplicationContext.class, this.mockContextSupplier);
}
@Test
public void getWhenTypeIsClassShouldThrowException() {
this.thrown.expect(IllegalArgumentException.class);
this.thrown.expectMessage("Type must not be null");
ApplicationContextAssertProvider.get(null, ApplicationContext.class,
this.mockContextSupplier);
ApplicationContextAssertProvider.get(null, ApplicationContext.class, this.mockContextSupplier);
}
@Test
public void getWhenContextTypeIsNullShouldThrowException() {
this.thrown.expect(IllegalArgumentException.class);
this.thrown.expectMessage("Type must be an interface");
ApplicationContextAssertProvider.get(
TestAssertProviderApplicationContextClass.class, ApplicationContext.class,
ApplicationContextAssertProvider.get(TestAssertProviderApplicationContextClass.class, ApplicationContext.class,
this.mockContextSupplier);
}
@@ -92,22 +89,21 @@ public class ApplicationContextAssertProviderTests {
public void getWhenContextTypeIsClassShouldThrowException() {
this.thrown.expect(IllegalArgumentException.class);
this.thrown.expectMessage("ContextType must not be null");
ApplicationContextAssertProvider.get(TestAssertProviderApplicationContext.class,
null, this.mockContextSupplier);
ApplicationContextAssertProvider.get(TestAssertProviderApplicationContext.class, null,
this.mockContextSupplier);
}
@Test
public void getWhenSupplierIsNullShouldThrowException() {
this.thrown.expect(IllegalArgumentException.class);
this.thrown.expectMessage("ContextType must be an interface");
ApplicationContextAssertProvider.get(TestAssertProviderApplicationContext.class,
StaticApplicationContext.class, this.mockContextSupplier);
ApplicationContextAssertProvider.get(TestAssertProviderApplicationContext.class, StaticApplicationContext.class,
this.mockContextSupplier);
}
@Test
public void getWhenContextStartsShouldReturnProxyThatCallsRealMethods() {
ApplicationContextAssertProvider<ApplicationContext> context = get(
this.mockContextSupplier);
ApplicationContextAssertProvider<ApplicationContext> context = get(this.mockContextSupplier);
assertThat((Object) context).isNotNull();
context.getBean("foo");
verify(this.mockContext).getBean("foo");
@@ -115,8 +111,7 @@ public class ApplicationContextAssertProviderTests {
@Test
public void getWhenContextFailsShouldReturnProxyThatThrowsExceptions() {
ApplicationContextAssertProvider<ApplicationContext> context = get(
this.startupFailureSupplier);
ApplicationContextAssertProvider<ApplicationContext> context = get(this.startupFailureSupplier);
assertThat((Object) context).isNotNull();
expectStartupFailure();
context.getBean("foo");
@@ -124,53 +119,45 @@ public class ApplicationContextAssertProviderTests {
@Test
public void getSourceContextWhenContextStartsShouldReturnSourceContext() {
ApplicationContextAssertProvider<ApplicationContext> context = get(
this.mockContextSupplier);
ApplicationContextAssertProvider<ApplicationContext> context = get(this.mockContextSupplier);
assertThat(context.getSourceApplicationContext()).isSameAs(this.mockContext);
}
@Test
public void getSourceContextWhenContextFailsShouldThrowException() {
ApplicationContextAssertProvider<ApplicationContext> context = get(
this.startupFailureSupplier);
ApplicationContextAssertProvider<ApplicationContext> context = get(this.startupFailureSupplier);
expectStartupFailure();
context.getSourceApplicationContext();
}
@Test
public void getSourceContextOfTypeWhenContextStartsShouldReturnSourceContext() {
ApplicationContextAssertProvider<ApplicationContext> context = get(
this.mockContextSupplier);
assertThat(context.getSourceApplicationContext(ApplicationContext.class))
.isSameAs(this.mockContext);
ApplicationContextAssertProvider<ApplicationContext> context = get(this.mockContextSupplier);
assertThat(context.getSourceApplicationContext(ApplicationContext.class)).isSameAs(this.mockContext);
}
@Test
public void getSourceContextOfTypeWhenContextFailsToStartShouldThrowException() {
ApplicationContextAssertProvider<ApplicationContext> context = get(
this.startupFailureSupplier);
ApplicationContextAssertProvider<ApplicationContext> context = get(this.startupFailureSupplier);
expectStartupFailure();
context.getSourceApplicationContext(ApplicationContext.class);
}
@Test
public void getStartupFailureWhenContextStartsShouldReturnNull() {
ApplicationContextAssertProvider<ApplicationContext> context = get(
this.mockContextSupplier);
ApplicationContextAssertProvider<ApplicationContext> context = get(this.mockContextSupplier);
assertThat(context.getStartupFailure()).isNull();
}
@Test
public void getStartupFailureWhenContextFailsToStartShouldReturnException() {
ApplicationContextAssertProvider<ApplicationContext> context = get(
this.startupFailureSupplier);
ApplicationContextAssertProvider<ApplicationContext> context = get(this.startupFailureSupplier);
assertThat(context.getStartupFailure()).isEqualTo(this.startupFailure);
}
@Test
public void assertThatWhenContextStartsShouldReturnAssertions() {
ApplicationContextAssertProvider<ApplicationContext> context = get(
this.mockContextSupplier);
ApplicationContextAssertProvider<ApplicationContext> context = get(this.mockContextSupplier);
ApplicationContextAssert<ApplicationContext> contextAssert = assertThat(context);
assertThat(contextAssert.getApplicationContext()).isSameAs(context);
assertThat(contextAssert.getStartupFailure()).isNull();
@@ -178,8 +165,7 @@ public class ApplicationContextAssertProviderTests {
@Test
public void assertThatWhenContextFailsShouldReturnAssertions() {
ApplicationContextAssertProvider<ApplicationContext> context = get(
this.startupFailureSupplier);
ApplicationContextAssertProvider<ApplicationContext> context = get(this.startupFailureSupplier);
ApplicationContextAssert<ApplicationContext> contextAssert = assertThat(context);
assertThat(contextAssert.getApplicationContext()).isSameAs(context);
assertThat(contextAssert.getStartupFailure()).isSameAs(this.startupFailure);
@@ -187,28 +173,21 @@ public class ApplicationContextAssertProviderTests {
@Test
public void toStringWhenContextStartsShouldReturnSimpleString() {
ApplicationContextAssertProvider<ApplicationContext> context = get(
this.mockContextSupplier);
assertThat(context.toString())
.startsWith(
"Started application [ConfigurableApplicationContext.MockitoMock")
.endsWith(
"id = [null], applicationName = [null], beanDefinitionCount = 0]");
ApplicationContextAssertProvider<ApplicationContext> context = get(this.mockContextSupplier);
assertThat(context.toString()).startsWith("Started application [ConfigurableApplicationContext.MockitoMock")
.endsWith("id = [null], applicationName = [null], beanDefinitionCount = 0]");
}
@Test
public void toStringWhenContextFailsToStartShouldReturnSimpleString() {
ApplicationContextAssertProvider<ApplicationContext> context = get(
this.startupFailureSupplier);
ApplicationContextAssertProvider<ApplicationContext> context = get(this.startupFailureSupplier);
assertThat(context.toString()).isEqualTo("Unstarted application context "
+ "org.springframework.context.ApplicationContext"
+ "[startupFailure=java.lang.RuntimeException]");
+ "org.springframework.context.ApplicationContext" + "[startupFailure=java.lang.RuntimeException]");
}
@Test
public void closeShouldCloseContext() {
ApplicationContextAssertProvider<ApplicationContext> context = get(
this.mockContextSupplier);
ApplicationContextAssertProvider<ApplicationContext> context = get(this.mockContextSupplier);
context.close();
verify(this.mockContext).close();
}
@@ -219,11 +198,9 @@ public class ApplicationContextAssertProviderTests {
this.thrown.expectCause(equalTo(this.startupFailure));
}
private ApplicationContextAssertProvider<ApplicationContext> get(
Supplier<ApplicationContext> contextSupplier) {
return ApplicationContextAssertProvider.get(
TestAssertProviderApplicationContext.class, ApplicationContext.class,
contextSupplier);
private ApplicationContextAssertProvider<ApplicationContext> get(Supplier<ApplicationContext> contextSupplier) {
return ApplicationContextAssertProvider.get(TestAssertProviderApplicationContext.class,
ApplicationContext.class, contextSupplier);
}
private interface TestAssertProviderApplicationContext

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -67,8 +67,7 @@ public class ApplicationContextAssertTests {
@Test
public void createWhenHasApplicationContextShouldSetActual() {
assertThat(getAssert(this.context).getSourceApplicationContext())
.isSameAs(this.context);
assertThat(getAssert(this.context).getSourceApplicationContext()).isSameAs(this.context);
}
@Test
@@ -92,8 +91,7 @@ public class ApplicationContextAssertTests {
@Test
public void hasBeanWhenNotStartedShouldFail() {
this.thrown.expect(AssertionError.class);
this.thrown.expectMessage(String
.format("but context failed to start:%n java.lang.RuntimeException"));
this.thrown.expectMessage(String.format("but context failed to start:%n java.lang.RuntimeException"));
assertThat(getAssert(this.failure)).hasBean("foo");
}
@@ -123,8 +121,7 @@ public class ApplicationContextAssertTests {
public void hasSingleBeanWhenFailedToStartShouldFail() {
this.thrown.expect(AssertionError.class);
this.thrown.expectMessage("to have a single bean of type");
this.thrown.expectMessage(String
.format("but context failed to start:%n java.lang.RuntimeException"));
this.thrown.expectMessage(String.format("but context failed to start:%n java.lang.RuntimeException"));
assertThat(getAssert(this.failure)).hasSingleBean(Foo.class);
}
@@ -161,8 +158,7 @@ public class ApplicationContextAssertTests {
public void doesNotHaveBeanOfTypeWhenFailedToStartShouldFail() {
this.thrown.expect(AssertionError.class);
this.thrown.expectMessage("not to have any beans of type");
this.thrown.expectMessage(String
.format("but context failed to start:%n java.lang.RuntimeException"));
this.thrown.expectMessage(String.format("but context failed to start:%n java.lang.RuntimeException"));
assertThat(getAssert(this.failure)).doesNotHaveBean(Foo.class);
}
@@ -177,8 +173,7 @@ public class ApplicationContextAssertTests {
@Test
public void doesNotHaveBeanOfTypeWithLimitedScopeWhenInParentShouldPass() {
this.parent.registerSingleton("foo", Foo.class);
assertThat(getAssert(this.context)).doesNotHaveBean(Foo.class,
Scope.NO_ANCESTORS);
assertThat(getAssert(this.context)).doesNotHaveBean(Foo.class, Scope.NO_ANCESTORS);
}
@Test
@@ -206,8 +201,7 @@ public class ApplicationContextAssertTests {
public void getBeanNamesWhenHasNamesShouldReturnNamesAssert() {
this.context.registerSingleton("foo", Foo.class);
this.context.registerSingleton("bar", Foo.class);
assertThat(getAssert(this.context)).getBeanNames(Foo.class).containsOnly("foo",
"bar");
assertThat(getAssert(this.context)).getBeanNames(Foo.class).containsOnly("foo", "bar");
}
@Test
@@ -219,8 +213,7 @@ public class ApplicationContextAssertTests {
public void getBeanNamesWhenFailedToStartShouldFail() {
this.thrown.expect(AssertionError.class);
this.thrown.expectMessage("not to have any beans of name");
this.thrown.expectMessage(String
.format("but context failed to start:%n java.lang.RuntimeException"));
this.thrown.expectMessage(String.format("but context failed to start:%n java.lang.RuntimeException"));
assertThat(getAssert(this.failure)).doesNotHaveBean("foo");
}
@@ -248,8 +241,7 @@ public class ApplicationContextAssertTests {
public void getBeanOfTypeWhenFailedToStartShouldFail() {
this.thrown.expect(AssertionError.class);
this.thrown.expectMessage("to contain bean of type");
this.thrown.expectMessage(String
.format("but context failed to start:%n java.lang.RuntimeException"));
this.thrown.expectMessage(String.format("but context failed to start:%n java.lang.RuntimeException"));
assertThat(getAssert(this.failure)).getBean(Foo.class);
}
@@ -262,8 +254,7 @@ public class ApplicationContextAssertTests {
@Test
public void getBeanOfTypeWhenInParentWithLimitedScopeShouldReturnNullAssert() {
this.parent.registerSingleton("foo", Foo.class);
assertThat(getAssert(this.context)).getBean(Foo.class, Scope.NO_ANCESTORS)
.isNull();
assertThat(getAssert(this.context)).getBean(Foo.class, Scope.NO_ANCESTORS).isNull();
}
@Test
@@ -279,8 +270,7 @@ public class ApplicationContextAssertTests {
public void getBeanOfTypeWithLimitedScopeWhenHasMultipleBeansIncludingParentShouldReturnBeanAssert() {
this.parent.registerSingleton("foo", Foo.class);
this.context.registerSingleton("bar", Foo.class);
assertThat(getAssert(this.context)).getBean(Foo.class, Scope.NO_ANCESTORS)
.isNotNull();
assertThat(getAssert(this.context)).getBean(Foo.class, Scope.NO_ANCESTORS).isNotNull();
}
@Test
@@ -298,8 +288,7 @@ public class ApplicationContextAssertTests {
public void getBeanOfNameWhenFailedToStartShouldFail() {
this.thrown.expect(AssertionError.class);
this.thrown.expectMessage("to contain a bean of name");
this.thrown.expectMessage(String
.format("but context failed to start:%n java.lang.RuntimeException"));
this.thrown.expectMessage(String.format("but context failed to start:%n java.lang.RuntimeException"));
assertThat(getAssert(this.failure)).getBean("foo");
}
@@ -326,8 +315,7 @@ public class ApplicationContextAssertTests {
public void getBeanOfNameAndTypeWhenFailedToStartShouldFail() {
this.thrown.expect(AssertionError.class);
this.thrown.expectMessage("to contain a bean of name");
this.thrown.expectMessage(String
.format("but context failed to start:%n java.lang.RuntimeException"));
this.thrown.expectMessage(String.format("but context failed to start:%n java.lang.RuntimeException"));
assertThat(getAssert(this.failure)).getBean("foo", Foo.class);
}
@@ -335,8 +323,7 @@ public class ApplicationContextAssertTests {
public void getBeansWhenHasBeansShouldReturnMapAssert() {
this.context.registerSingleton("foo", Foo.class);
this.context.registerSingleton("bar", Foo.class);
assertThat(getAssert(this.context)).getBeans(Foo.class).hasSize(2)
.containsKeys("foo", "bar");
assertThat(getAssert(this.context)).getBeans(Foo.class).hasSize(2).containsKeys("foo", "bar");
}
@Test
@@ -348,8 +335,7 @@ public class ApplicationContextAssertTests {
public void getBeansWhenFailedToStartShouldFail() {
this.thrown.expect(AssertionError.class);
this.thrown.expectMessage("to get beans of type");
this.thrown.expectMessage(String
.format("but context failed to start:%n java.lang.RuntimeException"));
this.thrown.expectMessage(String.format("but context failed to start:%n java.lang.RuntimeException"));
assertThat(getAssert(this.failure)).getBeans(Foo.class);
}
@@ -357,16 +343,14 @@ public class ApplicationContextAssertTests {
public void getBeansShouldIncludeBeansFromParentScope() {
this.parent.registerSingleton("foo", Foo.class);
this.context.registerSingleton("bar", Foo.class);
assertThat(getAssert(this.context)).getBeans(Foo.class).hasSize(2)
.containsKeys("foo", "bar");
assertThat(getAssert(this.context)).getBeans(Foo.class).hasSize(2).containsKeys("foo", "bar");
}
@Test
public void getBeansWithLimitedScopeShouldNotIncludeBeansFromParentScope() {
this.parent.registerSingleton("foo", Foo.class);
this.context.registerSingleton("bar", Foo.class);
assertThat(getAssert(this.context)).getBeans(Foo.class, Scope.NO_ANCESTORS)
.hasSize(1).containsKeys("bar");
assertThat(getAssert(this.context)).getBeans(Foo.class, Scope.NO_ANCESTORS).hasSize(1).containsKeys("bar");
}
@Test
@@ -397,8 +381,7 @@ public class ApplicationContextAssertTests {
public void hasNotFailedWhenFailedShouldFail() {
this.thrown.expect(AssertionError.class);
this.thrown.expectMessage("to have not failed");
this.thrown.expectMessage(String
.format("but context failed to start:%n java.lang.RuntimeException"));
this.thrown.expectMessage(String.format("but context failed to start:%n java.lang.RuntimeException"));
assertThat(getAssert(this.failure)).hasNotFailed();
}
@@ -407,8 +390,7 @@ public class ApplicationContextAssertTests {
assertThat(getAssert(this.context)).hasNotFailed();
}
private AssertableApplicationContext getAssert(
ConfigurableApplicationContext applicationContext) {
private AssertableApplicationContext getAssert(ConfigurableApplicationContext applicationContext) {
return AssertableApplicationContext.get(() -> applicationContext);
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2017 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -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();
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2017 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -47,15 +47,13 @@ public class SpringBootTestContextBootstrapperWithInitializersTests {
@Test
public void foundConfiguration() {
Object bean = this.context
.getBean(SpringBootTestContextBootstrapperExampleConfig.class);
Object bean = this.context.getBean(SpringBootTestContextBootstrapperExampleConfig.class);
assertThat(bean).isNotNull();
}
// gh-8483
public static class CustomInitializer
implements ApplicationContextInitializer<ConfigurableApplicationContext> {
public static class CustomInitializer implements ApplicationContextInitializer<ConfigurableApplicationContext> {
@Override
public void initialize(ConfigurableApplicationContext applicationContext) {

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2017 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -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(

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2017 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -41,61 +41,52 @@ public class TestTypeExcludeFilterTests {
@Test
public void matchesJUnit4TestClass() throws Exception {
assertThat(this.filter.match(getMetadataReader(TestTypeExcludeFilterTests.class),
this.metadataReaderFactory)).isTrue();
assertThat(this.filter.match(getMetadataReader(TestTypeExcludeFilterTests.class), this.metadataReaderFactory))
.isTrue();
}
@Test
public void matchesJUnitJupiterTestClass() throws Exception {
assertThat(this.filter.match(getMetadataReader(JupiterTestExample.class),
this.metadataReaderFactory)).isTrue();
assertThat(this.filter.match(getMetadataReader(JupiterTestExample.class), this.metadataReaderFactory)).isTrue();
}
@Test
public void matchesJUnitJupiterRepeatedTestClass() throws Exception {
assertThat(this.filter.match(getMetadataReader(JupiterRepeatedTestExample.class),
this.metadataReaderFactory)).isTrue();
assertThat(this.filter.match(getMetadataReader(JupiterRepeatedTestExample.class), this.metadataReaderFactory))
.isTrue();
}
@Test
public void matchesJUnitJupiterTestFactoryClass() throws Exception {
assertThat(this.filter.match(getMetadataReader(JupiterTestFactoryExample.class),
this.metadataReaderFactory)).isTrue();
assertThat(this.filter.match(getMetadataReader(JupiterTestFactoryExample.class), this.metadataReaderFactory))
.isTrue();
}
@Test
public void matchesNestedConfiguration() throws Exception {
assertThat(this.filter.match(getMetadataReader(NestedConfig.class),
assertThat(this.filter.match(getMetadataReader(NestedConfig.class), this.metadataReaderFactory)).isTrue();
}
@Test
public void matchesNestedConfigurationClassWithoutTestMethodsIfItHasRunWith() throws Exception {
assertThat(this.filter.match(getMetadataReader(AbstractTestWithConfigAndRunWith.Config.class),
this.metadataReaderFactory)).isTrue();
}
@Test
public void matchesNestedConfigurationClassWithoutTestMethodsIfItHasRunWith()
throws Exception {
assertThat(this.filter.match(
getMetadataReader(AbstractTestWithConfigAndRunWith.Config.class),
this.metadataReaderFactory)).isTrue();
}
@Test
public void matchesNestedConfigurationClassWithoutTestMethodsIfItHasExtendWith()
throws Exception {
assertThat(this.filter.match(
getMetadataReader(
AbstractJupiterTestWithConfigAndExtendWith.Config.class),
public void matchesNestedConfigurationClassWithoutTestMethodsIfItHasExtendWith() throws Exception {
assertThat(this.filter.match(getMetadataReader(AbstractJupiterTestWithConfigAndExtendWith.Config.class),
this.metadataReaderFactory)).isTrue();
}
@Test
public void matchesTestConfiguration() throws Exception {
assertThat(this.filter.match(getMetadataReader(SampleTestConfig.class),
this.metadataReaderFactory)).isTrue();
assertThat(this.filter.match(getMetadataReader(SampleTestConfig.class), this.metadataReaderFactory)).isTrue();
}
@Test
public void doesNotMatchRegularConfiguration() throws Exception {
assertThat(this.filter.match(getMetadataReader(SampleConfig.class),
this.metadataReaderFactory)).isFalse();
assertThat(this.filter.match(getMetadataReader(SampleConfig.class), this.metadataReaderFactory)).isFalse();
}
private MetadataReader getMetadataReader(Class<?> source) throws IOException {

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -68,8 +68,7 @@ public abstract class AbstractApplicationContextRunnerTests<T extends AbstractAp
String key = "test." + UUID.randomUUID();
assertThat(System.getProperties().containsKey(key)).isFalse();
get().withSystemProperties(key + "=value")
.run((context) -> assertThat(System.getProperties()).containsEntry(key,
"value"));
.run((context) -> assertThat(System.getProperties()).containsEntry(key, "value"));
assertThat(System.getProperties().containsKey(key)).isFalse();
}
@@ -77,8 +76,7 @@ public abstract class AbstractApplicationContextRunnerTests<T extends AbstractAp
public void runWithSystemPropertiesWhenContextFailsShouldRemoveProperties() {
String key = "test." + UUID.randomUUID();
assertThat(System.getProperties().containsKey(key)).isFalse();
get().withSystemProperties(key + "=value")
.withUserConfiguration(FailingConfig.class)
get().withSystemProperties(key + "=value").withUserConfiguration(FailingConfig.class)
.run((context) -> assertThat(context).hasFailed());
assertThat(System.getProperties().containsKey(key)).isFalse();
}
@@ -90,8 +88,7 @@ public abstract class AbstractApplicationContextRunnerTests<T extends AbstractAp
try {
assertThat(System.getProperties().getProperty(key)).isEqualTo("value");
get().withSystemProperties(key + "=newValue")
.run((context) -> assertThat(System.getProperties())
.containsEntry(key, "newValue"));
.run((context) -> assertThat(System.getProperties()).containsEntry(key, "newValue"));
assertThat(System.getProperties().getProperty(key)).isEqualTo("value");
}
finally {
@@ -106,8 +103,7 @@ public abstract class AbstractApplicationContextRunnerTests<T extends AbstractAp
try {
assertThat(System.getProperties().getProperty(key)).isEqualTo("value");
get().withSystemProperties(key + "=")
.run((context) -> assertThat(System.getProperties())
.doesNotContainKey(key));
.run((context) -> assertThat(System.getProperties()).doesNotContainKey(key));
assertThat(System.getProperties().getProperty(key)).isEqualTo("value");
}
finally {
@@ -117,63 +113,55 @@ public abstract class AbstractApplicationContextRunnerTests<T extends AbstractAp
@Test
public void runWithMultiplePropertyValuesShouldAllAllValues() {
get().withPropertyValues("test.foo=1").withPropertyValues("test.bar=2")
.run((context) -> {
Environment environment = context.getEnvironment();
assertThat(environment.getProperty("test.foo")).isEqualTo("1");
assertThat(environment.getProperty("test.bar")).isEqualTo("2");
});
get().withPropertyValues("test.foo=1").withPropertyValues("test.bar=2").run((context) -> {
Environment environment = context.getEnvironment();
assertThat(environment.getProperty("test.foo")).isEqualTo("1");
assertThat(environment.getProperty("test.bar")).isEqualTo("2");
});
}
@Test
public void runWithPropertyValuesWhenHasExistingShouldReplaceValue() {
get().withPropertyValues("test.foo=1").withPropertyValues("test.foo=2")
.run((context) -> {
Environment environment = context.getEnvironment();
assertThat(environment.getProperty("test.foo")).isEqualTo("2");
});
get().withPropertyValues("test.foo=1").withPropertyValues("test.foo=2").run((context) -> {
Environment environment = context.getEnvironment();
assertThat(environment.getProperty("test.foo")).isEqualTo("2");
});
}
@Test
public void runWithConfigurationsShouldRegisterConfigurations() {
get().withUserConfiguration(FooConfig.class)
.run((context) -> assertThat(context).hasBean("foo"));
get().withUserConfiguration(FooConfig.class).run((context) -> assertThat(context).hasBean("foo"));
}
@Test
public void runWithMultipleConfigurationsShouldRegisterAllConfigurations() {
get().withUserConfiguration(FooConfig.class)
.withConfiguration(UserConfigurations.of(BarConfig.class))
get().withUserConfiguration(FooConfig.class).withConfiguration(UserConfigurations.of(BarConfig.class))
.run((context) -> assertThat(context).hasBean("foo").hasBean("bar"));
}
@Test
public void runWithFailedContextShouldReturnFailedAssertableContext() {
get().withUserConfiguration(FailingConfig.class)
.run((context) -> assertThat(context).hasFailed());
get().withUserConfiguration(FailingConfig.class).run((context) -> assertThat(context).hasFailed());
}
@Test
public void runWithClassLoaderShouldSetClassLoaderOnContext() {
get().withClassLoader(new FilteredClassLoader(Gson.class.getPackage().getName()))
.run((context) -> {
try {
ClassUtils.forName(Gson.class.getName(),
context.getClassLoader());
fail("Should have thrown a ClassNotFoundException");
}
catch (ClassNotFoundException ex) {
// expected
}
});
get().withClassLoader(new FilteredClassLoader(Gson.class.getPackage().getName())).run((context) -> {
try {
ClassUtils.forName(Gson.class.getName(), context.getClassLoader());
fail("Should have thrown a ClassNotFoundException");
}
catch (ClassNotFoundException ex) {
// expected
}
});
}
@Test
public void runWithClassLoaderShouldSetClassLoaderOnConditionContext() {
get().withClassLoader(new FilteredClassLoader(Gson.class.getPackage().getName()))
.withUserConfiguration(ConditionalConfig.class)
.run((context) -> assertThat(context)
.hasSingleBean(ConditionalConfig.class));
.run((context) -> assertThat(context).hasSingleBean(ConditionalConfig.class));
}
@Test

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2017 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -35,8 +35,7 @@ public class WebApplicationContextRunnerTests extends
@Test
public void contextShouldHaveMockServletContext() {
get().run((context) -> assertThat(context.getServletContext())
.isInstanceOf(MockServletContext.class));
get().run((context) -> assertThat(context.getServletContext()).isInstanceOf(MockServletContext.class));
}
@Override

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2017 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -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}.

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2017 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -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:");
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -49,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

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -54,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

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -60,8 +60,7 @@ public class GsonTesterTests extends AbstractJsonMarshalTesterTests {
}
@Override
protected AbstractJsonMarshalTester<Object> createTester(Class<?> resourceLoadClass,
ResolvableType type) {
protected AbstractJsonMarshalTester<Object> createTester(Class<?> resourceLoadClass, ResolvableType type) {
return new GsonTester<>(resourceLoadClass, type, new GsonBuilder().create());
}
@@ -69,9 +68,8 @@ public class GsonTesterTests extends AbstractJsonMarshalTesterTests {
public GsonTester<ExampleObject> base;
public GsonTester<ExampleObject> baseSet = new GsonTester<>(
InitFieldsBaseClass.class, ResolvableType.forClass(ExampleObject.class),
new GsonBuilder().create());
public GsonTester<ExampleObject> baseSet = new GsonTester<>(InitFieldsBaseClass.class,
ResolvableType.forClass(ExampleObject.class), new GsonBuilder().create());
}
@@ -79,9 +77,8 @@ public class GsonTesterTests extends AbstractJsonMarshalTesterTests {
public GsonTester<List<ExampleObject>> test;
public GsonTester<ExampleObject> testSet = new GsonTester<>(
InitFieldsBaseClass.class, ResolvableType.forClass(ExampleObject.class),
new GsonBuilder().create());
public GsonTester<ExampleObject> testSet = new GsonTester<>(InitFieldsBaseClass.class,
ResolvableType.forClass(ExampleObject.class), new GsonBuilder().create());
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2017 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -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<>();
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);
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -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<>(resourceLoadClass, type, new ObjectMapper());
}
@@ -68,9 +67,8 @@ public class JacksonTesterTests extends AbstractJsonMarshalTesterTests {
public JacksonTester<ExampleObject> base;
public JacksonTester<ExampleObject> baseSet = new JacksonTester<>(
InitFieldsBaseClass.class, ResolvableType.forClass(ExampleObject.class),
new ObjectMapper());
public JacksonTester<ExampleObject> baseSet = new JacksonTester<>(InitFieldsBaseClass.class,
ResolvableType.forClass(ExampleObject.class), new ObjectMapper());
}
@@ -78,9 +76,8 @@ public class JacksonTesterTests extends AbstractJsonMarshalTesterTests {
public JacksonTester<List<ExampleObject>> test;
public JacksonTester<ExampleObject> testSet = new JacksonTester<>(
InitFieldsBaseClass.class, ResolvableType.forClass(ExampleObject.class),
new ObjectMapper());
public JacksonTester<ExampleObject> testSet = new JacksonTester<>(InitFieldsBaseClass.class,
ResolvableType.forClass(ExampleObject.class), new ObjectMapper());
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2017 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -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();
@@ -233,8 +232,7 @@ public class JsonContentAssertTests {
@Test(expected = AssertionError.class)
public void isStrictlyEqualToJsonWhenResourcePathAndClassIsNotMatchingShouldFail() {
assertThat(forJson(SOURCE)).isStrictlyEqualToJson("lenient-same.json",
getClass());
assertThat(forJson(SOURCE)).isStrictlyEqualToJson("lenient-same.json", getClass());
}
@Test
@@ -264,8 +262,7 @@ public class JsonContentAssertTests {
@Test(expected = AssertionError.class)
public void isStrictlyEqualToJsonWhenInputStreamIsNotMatchingShouldFail() {
assertThat(forJson(SOURCE))
.isStrictlyEqualToJson(createInputStream(LENIENT_SAME));
assertThat(forJson(SOURCE)).isStrictlyEqualToJson(createInputStream(LENIENT_SAME));
}
@Test
@@ -290,75 +287,62 @@ public class JsonContentAssertTests {
@Test
public void isEqualToJsonWhenResourcePathIsMatchingAndLenientShouldPass() {
assertThat(forJson(SOURCE)).isEqualToJson("lenient-same.json",
JSONCompareMode.LENIENT);
assertThat(forJson(SOURCE)).isEqualToJson("lenient-same.json", JSONCompareMode.LENIENT);
}
@Test(expected = AssertionError.class)
public void isEqualToJsonWhenResourcePathIsNotMatchingAndLenientShouldFail() {
assertThat(forJson(SOURCE)).isEqualToJson("different.json",
JSONCompareMode.LENIENT);
assertThat(forJson(SOURCE)).isEqualToJson("different.json", JSONCompareMode.LENIENT);
}
@Test
public void isEqualToJsonWhenResourcePathAndClassIsMatchingAndLenientShouldPass() {
assertThat(forJson(SOURCE)).isEqualToJson("lenient-same.json", getClass(),
JSONCompareMode.LENIENT);
assertThat(forJson(SOURCE)).isEqualToJson("lenient-same.json", getClass(), JSONCompareMode.LENIENT);
}
@Test(expected = AssertionError.class)
public void isEqualToJsonWhenResourcePathAndClassIsNotMatchingAndLenientShouldFail() {
assertThat(forJson(SOURCE)).isEqualToJson("different.json", getClass(),
JSONCompareMode.LENIENT);
assertThat(forJson(SOURCE)).isEqualToJson("different.json", getClass(), JSONCompareMode.LENIENT);
}
@Test
public void isEqualToJsonWhenBytesAreMatchingAndLenientShouldPass() {
assertThat(forJson(SOURCE)).isEqualToJson(LENIENT_SAME.getBytes(),
JSONCompareMode.LENIENT);
assertThat(forJson(SOURCE)).isEqualToJson(LENIENT_SAME.getBytes(), JSONCompareMode.LENIENT);
}
@Test(expected = AssertionError.class)
public void isEqualToJsonWhenBytesAreNotMatchingAndLenientShouldFail() {
assertThat(forJson(SOURCE)).isEqualToJson(DIFFERENT.getBytes(),
JSONCompareMode.LENIENT);
assertThat(forJson(SOURCE)).isEqualToJson(DIFFERENT.getBytes(), JSONCompareMode.LENIENT);
}
@Test
public void isEqualToJsonWhenFileIsMatchingAndLenientShouldPass() throws Exception {
assertThat(forJson(SOURCE)).isEqualToJson(createFile(LENIENT_SAME),
JSONCompareMode.LENIENT);
assertThat(forJson(SOURCE)).isEqualToJson(createFile(LENIENT_SAME), JSONCompareMode.LENIENT);
}
@Test(expected = AssertionError.class)
public void isEqualToJsonWhenFileIsNotMatchingAndLenientShouldFail()
throws Exception {
assertThat(forJson(SOURCE)).isEqualToJson(createFile(DIFFERENT),
JSONCompareMode.LENIENT);
public void isEqualToJsonWhenFileIsNotMatchingAndLenientShouldFail() throws Exception {
assertThat(forJson(SOURCE)).isEqualToJson(createFile(DIFFERENT), JSONCompareMode.LENIENT);
}
@Test
public void isEqualToJsonWhenInputStreamIsMatchingAndLenientShouldPass() {
assertThat(forJson(SOURCE)).isEqualToJson(createInputStream(LENIENT_SAME),
JSONCompareMode.LENIENT);
assertThat(forJson(SOURCE)).isEqualToJson(createInputStream(LENIENT_SAME), JSONCompareMode.LENIENT);
}
@Test(expected = AssertionError.class)
public void isEqualToJsonWhenInputStreamIsNotMatchingAndLenientShouldFail() {
assertThat(forJson(SOURCE)).isEqualToJson(createInputStream(DIFFERENT),
JSONCompareMode.LENIENT);
assertThat(forJson(SOURCE)).isEqualToJson(createInputStream(DIFFERENT), JSONCompareMode.LENIENT);
}
@Test
public void isEqualToJsonWhenResourceIsMatchingAndLenientShouldPass() {
assertThat(forJson(SOURCE)).isEqualToJson(createResource(LENIENT_SAME),
JSONCompareMode.LENIENT);
assertThat(forJson(SOURCE)).isEqualToJson(createResource(LENIENT_SAME), JSONCompareMode.LENIENT);
}
@Test(expected = AssertionError.class)
public void isEqualToJsonWhenResourceIsNotMatchingAndLenientShouldFail() {
assertThat(forJson(SOURCE)).isEqualToJson(createResource(DIFFERENT),
JSONCompareMode.LENIENT);
assertThat(forJson(SOURCE)).isEqualToJson(createResource(DIFFERENT), JSONCompareMode.LENIENT);
}
@Test
@@ -383,14 +367,12 @@ public class JsonContentAssertTests {
@Test
public void isEqualToJsonWhenResourcePathAndClassAreMatchingAndComparatorShouldPass() {
assertThat(forJson(SOURCE)).isEqualToJson("lenient-same.json", getClass(),
COMPARATOR);
assertThat(forJson(SOURCE)).isEqualToJson("lenient-same.json", getClass(), COMPARATOR);
}
@Test(expected = AssertionError.class)
public void isEqualToJsonWhenResourcePathAndClassAreNotMatchingAndComparatorShouldFail() {
assertThat(forJson(SOURCE)).isEqualToJson("different.json", getClass(),
COMPARATOR);
assertThat(forJson(SOURCE)).isEqualToJson("different.json", getClass(), COMPARATOR);
}
@Test
@@ -404,33 +386,28 @@ public class JsonContentAssertTests {
}
@Test
public void isEqualToJsonWhenFileIsMatchingAndComparatorShouldPass()
throws Exception {
public void isEqualToJsonWhenFileIsMatchingAndComparatorShouldPass() throws Exception {
assertThat(forJson(SOURCE)).isEqualToJson(createFile(LENIENT_SAME), COMPARATOR);
}
@Test(expected = AssertionError.class)
public void isEqualToJsonWhenFileIsNotMatchingAndComparatorShouldFail()
throws Exception {
public void isEqualToJsonWhenFileIsNotMatchingAndComparatorShouldFail() throws Exception {
assertThat(forJson(SOURCE)).isEqualToJson(createFile(DIFFERENT), COMPARATOR);
}
@Test
public void isEqualToJsonWhenInputStreamIsMatchingAndComparatorShouldPass() {
assertThat(forJson(SOURCE)).isEqualToJson(createInputStream(LENIENT_SAME),
COMPARATOR);
assertThat(forJson(SOURCE)).isEqualToJson(createInputStream(LENIENT_SAME), COMPARATOR);
}
@Test(expected = AssertionError.class)
public void isEqualToJsonWhenInputStreamIsNotMatchingAndComparatorShouldFail() {
assertThat(forJson(SOURCE)).isEqualToJson(createInputStream(DIFFERENT),
COMPARATOR);
assertThat(forJson(SOURCE)).isEqualToJson(createInputStream(DIFFERENT), COMPARATOR);
}
@Test
public void isEqualToJsonWhenResourceIsMatchingAndComparatorShouldPass() {
assertThat(forJson(SOURCE)).isEqualToJson(createResource(LENIENT_SAME),
COMPARATOR);
assertThat(forJson(SOURCE)).isEqualToJson(createResource(LENIENT_SAME), COMPARATOR);
}
@Test(expected = AssertionError.class)
@@ -605,8 +582,7 @@ public class JsonContentAssertTests {
@Test
public void isNotStrictlyEqualToJsonWhenResourcePathAndClassAreNotMatchingShouldPass() {
assertThat(forJson(SOURCE)).isNotStrictlyEqualToJson("lenient-same.json",
getClass());
assertThat(forJson(SOURCE)).isNotStrictlyEqualToJson("lenient-same.json", getClass());
}
@Test(expected = AssertionError.class)
@@ -625,8 +601,7 @@ public class JsonContentAssertTests {
}
@Test
public void isNotStrictlyEqualToJsonWhenFileIsNotMatchingShouldPass()
throws Exception {
public void isNotStrictlyEqualToJsonWhenFileIsNotMatchingShouldPass() throws Exception {
assertThat(forJson(SOURCE)).isNotStrictlyEqualToJson(createFile(LENIENT_SAME));
}
@@ -637,8 +612,7 @@ public class JsonContentAssertTests {
@Test
public void isNotStrictlyEqualToJsonWhenInputStreamIsNotMatchingShouldPass() {
assertThat(forJson(SOURCE))
.isNotStrictlyEqualToJson(createInputStream(LENIENT_SAME));
assertThat(forJson(SOURCE)).isNotStrictlyEqualToJson(createInputStream(LENIENT_SAME));
}
@Test(expected = AssertionError.class)
@@ -648,14 +622,12 @@ public class JsonContentAssertTests {
@Test
public void isNotStrictlyEqualToJsonWhenResourceIsNotMatchingShouldPass() {
assertThat(forJson(SOURCE))
.isNotStrictlyEqualToJson(createResource(LENIENT_SAME));
assertThat(forJson(SOURCE)).isNotStrictlyEqualToJson(createResource(LENIENT_SAME));
}
@Test(expected = AssertionError.class)
public void isNotEqualToJsonWhenStringIsMatchingAndLenientShouldFail() {
assertThat(forJson(SOURCE)).isNotEqualToJson(LENIENT_SAME,
JSONCompareMode.LENIENT);
assertThat(forJson(SOURCE)).isNotEqualToJson(LENIENT_SAME, JSONCompareMode.LENIENT);
}
@Test
@@ -665,76 +637,62 @@ public class JsonContentAssertTests {
@Test(expected = AssertionError.class)
public void isNotEqualToJsonWhenResourcePathIsMatchingAndLenientShouldFail() {
assertThat(forJson(SOURCE)).isNotEqualToJson("lenient-same.json",
JSONCompareMode.LENIENT);
assertThat(forJson(SOURCE)).isNotEqualToJson("lenient-same.json", JSONCompareMode.LENIENT);
}
@Test
public void isNotEqualToJsonWhenResourcePathIsNotMatchingAndLenientShouldPass() {
assertThat(forJson(SOURCE)).isNotEqualToJson("different.json",
JSONCompareMode.LENIENT);
assertThat(forJson(SOURCE)).isNotEqualToJson("different.json", JSONCompareMode.LENIENT);
}
@Test(expected = AssertionError.class)
public void isNotEqualToJsonWhenResourcePathAndClassAreMatchingAndLenientShouldFail() {
assertThat(forJson(SOURCE)).isNotEqualToJson("lenient-same.json", getClass(),
JSONCompareMode.LENIENT);
assertThat(forJson(SOURCE)).isNotEqualToJson("lenient-same.json", getClass(), JSONCompareMode.LENIENT);
}
@Test
public void isNotEqualToJsonWhenResourcePathAndClassAreNotMatchingAndLenientShouldPass() {
assertThat(forJson(SOURCE)).isNotEqualToJson("different.json", getClass(),
JSONCompareMode.LENIENT);
assertThat(forJson(SOURCE)).isNotEqualToJson("different.json", getClass(), JSONCompareMode.LENIENT);
}
@Test(expected = AssertionError.class)
public void isNotEqualToJsonWhenBytesAreMatchingAndLenientShouldFail() {
assertThat(forJson(SOURCE)).isNotEqualToJson(LENIENT_SAME.getBytes(),
JSONCompareMode.LENIENT);
assertThat(forJson(SOURCE)).isNotEqualToJson(LENIENT_SAME.getBytes(), JSONCompareMode.LENIENT);
}
@Test
public void isNotEqualToJsonWhenBytesAreNotMatchingAndLenientShouldPass() {
assertThat(forJson(SOURCE)).isNotEqualToJson(DIFFERENT.getBytes(),
JSONCompareMode.LENIENT);
assertThat(forJson(SOURCE)).isNotEqualToJson(DIFFERENT.getBytes(), JSONCompareMode.LENIENT);
}
@Test(expected = AssertionError.class)
public void isNotEqualToJsonWhenFileIsMatchingAndLenientShouldFail()
throws Exception {
assertThat(forJson(SOURCE)).isNotEqualToJson(createFile(LENIENT_SAME),
JSONCompareMode.LENIENT);
public void isNotEqualToJsonWhenFileIsMatchingAndLenientShouldFail() throws Exception {
assertThat(forJson(SOURCE)).isNotEqualToJson(createFile(LENIENT_SAME), JSONCompareMode.LENIENT);
}
@Test
public void isNotEqualToJsonWhenFileIsNotMatchingAndLenientShouldPass()
throws Exception {
assertThat(forJson(SOURCE)).isNotEqualToJson(createFile(DIFFERENT),
JSONCompareMode.LENIENT);
public void isNotEqualToJsonWhenFileIsNotMatchingAndLenientShouldPass() throws Exception {
assertThat(forJson(SOURCE)).isNotEqualToJson(createFile(DIFFERENT), JSONCompareMode.LENIENT);
}
@Test(expected = AssertionError.class)
public void isNotEqualToJsonWhenInputStreamIsMatchingAndLenientShouldFail() {
assertThat(forJson(SOURCE)).isNotEqualToJson(createInputStream(LENIENT_SAME),
JSONCompareMode.LENIENT);
assertThat(forJson(SOURCE)).isNotEqualToJson(createInputStream(LENIENT_SAME), JSONCompareMode.LENIENT);
}
@Test
public void isNotEqualToJsonWhenInputStreamIsNotMatchingAndLenientShouldPass() {
assertThat(forJson(SOURCE)).isNotEqualToJson(createInputStream(DIFFERENT),
JSONCompareMode.LENIENT);
assertThat(forJson(SOURCE)).isNotEqualToJson(createInputStream(DIFFERENT), JSONCompareMode.LENIENT);
}
@Test(expected = AssertionError.class)
public void isNotEqualToJsonWhenResourceIsMatchingAndLenientShouldFail() {
assertThat(forJson(SOURCE)).isNotEqualToJson(createResource(LENIENT_SAME),
JSONCompareMode.LENIENT);
assertThat(forJson(SOURCE)).isNotEqualToJson(createResource(LENIENT_SAME), JSONCompareMode.LENIENT);
}
@Test
public void isNotEqualToJsonWhenResourceIsNotMatchingAndLenientShouldPass() {
assertThat(forJson(SOURCE)).isNotEqualToJson(createResource(DIFFERENT),
JSONCompareMode.LENIENT);
assertThat(forJson(SOURCE)).isNotEqualToJson(createResource(DIFFERENT), JSONCompareMode.LENIENT);
}
@Test(expected = AssertionError.class)
@@ -759,14 +717,12 @@ public class JsonContentAssertTests {
@Test(expected = AssertionError.class)
public void isNotEqualToJsonWhenResourcePathAndClassAreMatchingAndComparatorShouldFail() {
assertThat(forJson(SOURCE)).isNotEqualToJson("lenient-same.json", getClass(),
COMPARATOR);
assertThat(forJson(SOURCE)).isNotEqualToJson("lenient-same.json", getClass(), COMPARATOR);
}
@Test
public void isNotEqualToJsonWhenResourcePathAndClassAreNotMatchingAndComparatorShouldPass() {
assertThat(forJson(SOURCE)).isNotEqualToJson("different.json", getClass(),
COMPARATOR);
assertThat(forJson(SOURCE)).isNotEqualToJson("different.json", getClass(), COMPARATOR);
}
@Test(expected = AssertionError.class)
@@ -780,40 +736,33 @@ public class JsonContentAssertTests {
}
@Test(expected = AssertionError.class)
public void isNotEqualToJsonWhenFileIsMatchingAndComparatorShouldFail()
throws Exception {
assertThat(forJson(SOURCE)).isNotEqualToJson(createFile(LENIENT_SAME),
COMPARATOR);
public void isNotEqualToJsonWhenFileIsMatchingAndComparatorShouldFail() throws Exception {
assertThat(forJson(SOURCE)).isNotEqualToJson(createFile(LENIENT_SAME), COMPARATOR);
}
@Test
public void isNotEqualToJsonWhenFileIsNotMatchingAndComparatorShouldPass()
throws Exception {
public void isNotEqualToJsonWhenFileIsNotMatchingAndComparatorShouldPass() throws Exception {
assertThat(forJson(SOURCE)).isNotEqualToJson(createFile(DIFFERENT), COMPARATOR);
}
@Test(expected = AssertionError.class)
public void isNotEqualToJsonWhenInputStreamIsMatchingAndComparatorShouldFail() {
assertThat(forJson(SOURCE)).isNotEqualToJson(createInputStream(LENIENT_SAME),
COMPARATOR);
assertThat(forJson(SOURCE)).isNotEqualToJson(createInputStream(LENIENT_SAME), COMPARATOR);
}
@Test
public void isNotEqualToJsonWhenInputStreamIsNotMatchingAndComparatorShouldPass() {
assertThat(forJson(SOURCE)).isNotEqualToJson(createInputStream(DIFFERENT),
COMPARATOR);
assertThat(forJson(SOURCE)).isNotEqualToJson(createInputStream(DIFFERENT), COMPARATOR);
}
@Test(expected = AssertionError.class)
public void isNotEqualToJsonWhenResourceIsMatchingAndComparatorShouldFail() {
assertThat(forJson(SOURCE)).isNotEqualToJson(createResource(LENIENT_SAME),
COMPARATOR);
assertThat(forJson(SOURCE)).isNotEqualToJson(createResource(LENIENT_SAME), COMPARATOR);
}
@Test
public void isNotEqualToJsonWhenResourceIsNotMatchingAndComparatorShouldPass() {
assertThat(forJson(SOURCE)).isNotEqualToJson(createResource(DIFFERENT),
COMPARATOR);
assertThat(forJson(SOURCE)).isNotEqualToJson(createResource(DIFFERENT), COMPARATOR);
}
@Test
@@ -833,8 +782,7 @@ public class JsonContentAssertTests {
@Test
public void hasJsonPathValueForIndefinitePathWithResults() {
assertThat(forJson(SIMPSONS))
.hasJsonPathValue("$.familyMembers[?(@.name == 'Bart')]");
assertThat(forJson(SIMPSONS)).hasJsonPathValue("$.familyMembers[?(@.name == 'Bart')]");
}
@Test
@@ -854,8 +802,7 @@ public class JsonContentAssertTests {
public void doesNotHaveJsonPathValueForAnEmptyArray() {
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);
}
@@ -863,8 +810,7 @@ public class JsonContentAssertTests {
public void doesNotHaveJsonPathValueForAnEmptyMap() {
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);
}
@@ -872,15 +818,14 @@ public class JsonContentAssertTests {
public void doesNotHaveJsonPathValueForIndefinitePathWithResults() {
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() {
assertThat(forJson(SIMPSONS))
.doesNotHaveJsonPathValue("$.familyMembers[?(@.name == 'Dilbert')]");
assertThat(forJson(SIMPSONS)).doesNotHaveJsonPathValue("$.familyMembers[?(@.name == 'Dilbert')]");
}
@Test
@@ -900,16 +845,15 @@ public class JsonContentAssertTests {
@Test
public void hasEmptyJsonPathValueForIndefinitePathWithEmptyResults() {
assertThat(forJson(SIMPSONS))
.hasEmptyJsonPathValue("$.familyMembers[?(@.name == 'Dilbert')]");
assertThat(forJson(SIMPSONS)).hasEmptyJsonPathValue("$.familyMembers[?(@.name == 'Dilbert')]");
}
@Test
public void hasEmptyJsonPathValueForIndefinitePathWithResults() {
String expression = "$.familyMembers[?(@.name == 'Bart')]";
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);
}
@@ -917,8 +861,7 @@ public class JsonContentAssertTests {
public void hasEmptyJsonPathValueForWhitespace() {
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);
}
@@ -949,16 +892,14 @@ public class JsonContentAssertTests {
@Test
public void doesNotHaveEmptyJsonPathValueForIndefinitePathWithResults() {
assertThat(forJson(SIMPSONS))
.doesNotHaveEmptyJsonPathValue("$.familyMembers[?(@.name == 'Bart')]");
assertThat(forJson(SIMPSONS)).doesNotHaveEmptyJsonPathValue("$.familyMembers[?(@.name == 'Bart')]");
}
@Test
public void doesNotHaveEmptyJsonPathValueForIndefinitePathWithEmptyResults() {
String expression = "$.familyMembers[?(@.name == 'Dilbert')]";
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);
}
@@ -966,8 +907,7 @@ public class JsonContentAssertTests {
public void doesNotHaveEmptyJsonPathValueForAnEmptyString() {
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);
}
@@ -975,8 +915,7 @@ public class JsonContentAssertTests {
public void doesNotHaveEmptyJsonPathValueForForAnEmptyArray() {
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);
}
@@ -984,8 +923,7 @@ public class JsonContentAssertTests {
public void doesNotHaveEmptyJsonPathValueForAnEmptyMap() {
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);
}
@@ -1003,8 +941,7 @@ public class JsonContentAssertTests {
public void hasJsonPathStringValueForNonString() {
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);
}
@@ -1017,8 +954,7 @@ public class JsonContentAssertTests {
public void hasJsonPathNumberValueForNonNumber() {
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);
}
@@ -1031,8 +967,7 @@ public class JsonContentAssertTests {
public void hasJsonPathBooleanValueForNonBoolean() {
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);
}
@@ -1050,8 +985,7 @@ public class JsonContentAssertTests {
public void hasJsonPathArrayValueForNonArray() {
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);
}
@@ -1069,8 +1003,7 @@ public class JsonContentAssertTests {
public void hasJsonPathMapValueForNonMap() {
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);
}
@@ -1086,8 +1019,7 @@ public class JsonContentAssertTests {
@Test
public void extractingJsonPathStringValue() {
assertThat(forJson(TYPES)).extractingJsonPathStringValue("@.str")
.isEqualTo("foo");
assertThat(forJson(TYPES)).extractingJsonPathStringValue("@.str").isEqualTo("foo");
}
@Test
@@ -1097,16 +1029,14 @@ public class JsonContentAssertTests {
@Test
public void extractingJsonPathStringValueForEmptyString() {
assertThat(forJson(TYPES)).extractingJsonPathStringValue("@.emptyString")
.isEmpty();
assertThat(forJson(TYPES)).extractingJsonPathStringValue("@.emptyString").isEmpty();
}
@Test
public void extractingJsonPathStringValueForWrongType() {
String expression = "$.num";
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);
}
@@ -1124,8 +1054,7 @@ public class JsonContentAssertTests {
public void extractingJsonPathNumberValueForWrongType() {
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);
}
@@ -1143,15 +1072,13 @@ public class JsonContentAssertTests {
public void extractingJsonPathBooleanValueForWrongType() {
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() {
assertThat(forJson(TYPES)).extractingJsonPathArrayValue("@.arr")
.containsExactly(42);
assertThat(forJson(TYPES)).extractingJsonPathArrayValue("@.arr").containsExactly(42);
}
@Test
@@ -1168,15 +1095,13 @@ public class JsonContentAssertTests {
public void extractingJsonPathArrayValueForWrongType() {
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() {
assertThat(forJson(TYPES)).extractingJsonPathMapValue("@.colorMap")
.contains(entry("red", "rojo"));
assertThat(forJson(TYPES)).extractingJsonPathMapValue("@.colorMap").contains(entry("red", "rojo"));
}
@Test
@@ -1193,8 +1118,7 @@ public class JsonContentAssertTests {
public void extractingJsonPathMapValueForWrongType() {
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);
}
@@ -1219,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) {

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2017 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -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();
@@ -76,8 +75,7 @@ public class JsonContentTests {
@Test
public void toStringWhenHasTypeShouldReturnString() {
JsonContent<ExampleObject> content = new JsonContent<>(getClass(), TYPE, JSON);
assertThat(content.toString())
.isEqualTo("JsonContent " + JSON + " created from " + TYPE);
assertThat(content.toString()).isEqualTo("JsonContent " + JSON + " created from " + TYPE);
}
@Test

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -61,8 +61,7 @@ public class JsonbTesterTests extends AbstractJsonMarshalTesterTests {
}
@Override
protected AbstractJsonMarshalTester<Object> createTester(Class<?> resourceLoadClass,
ResolvableType type) {
protected AbstractJsonMarshalTester<Object> createTester(Class<?> resourceLoadClass, ResolvableType type) {
return new JsonbTester<>(resourceLoadClass, type, JsonbBuilder.create());
}
@@ -70,9 +69,8 @@ public class JsonbTesterTests extends AbstractJsonMarshalTesterTests {
public JsonbTester<ExampleObject> base;
public JsonbTester<ExampleObject> baseSet = new JsonbTester<>(
InitFieldsBaseClass.class, ResolvableType.forClass(ExampleObject.class),
JsonbBuilder.create());
public JsonbTester<ExampleObject> baseSet = new JsonbTester<>(InitFieldsBaseClass.class,
ResolvableType.forClass(ExampleObject.class), JsonbBuilder.create());
}
@@ -80,9 +78,8 @@ public class JsonbTesterTests extends AbstractJsonMarshalTesterTests {
public JsonbTester<List<ExampleObject>> test;
public JsonbTester<ExampleObject> testSet = new JsonbTester<>(
InitFieldsBaseClass.class, ResolvableType.forClass(ExampleObject.class),
JsonbBuilder.create());
public JsonbTester<ExampleObject> testSet = new JsonbTester<>(InitFieldsBaseClass.class,
ResolvableType.forClass(ExampleObject.class), JsonbBuilder.create());
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2017 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -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();
@@ -67,8 +66,7 @@ public class ObjectContentTests {
@Test
public void toStringWhenHasTypeShouldReturnString() {
ObjectContent<ExampleObject> content = new ObjectContent<>(TYPE, OBJECT);
assertThat(content.toString())
.isEqualTo("ObjectContent " + OBJECT + " created from " + TYPE);
assertThat(content.toString()).isEqualTo("ObjectContent " + OBJECT + " created from " + TYPE);
}
@Test

View File

@@ -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()).isTrue();
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() {
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() {
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() {
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() {
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() {
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() {
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 {
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2017 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -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;
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2017 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -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");
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2017 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -37,8 +37,7 @@ 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();
@@ -52,8 +51,7 @@ public class MockDefinitionTests {
@Test
public void createWithDefaults() {
MockDefinition definition = new MockDefinition(null, EXAMPLE_SERVICE_TYPE, null,
null, false, null, null);
MockDefinition definition = new MockDefinition(null, EXAMPLE_SERVICE_TYPE, null, null, false, null, null);
assertThat(definition.getName()).isNull();
assertThat(definition.getTypeToMock()).isEqualTo(EXAMPLE_SERVICE_TYPE);
assertThat(definition.getExtraInterfaces()).isEmpty();
@@ -67,12 +65,11 @@ public class MockDefinitionTests {
public void createExplicit() {
QualifierDefinition qualifier = mock(QualifierDefinition.class);
MockDefinition definition = new MockDefinition("name", EXAMPLE_SERVICE_TYPE,
new Class<?>[] { ExampleExtraInterface.class },
Answers.RETURNS_SMART_NULLS, true, MockReset.BEFORE, qualifier);
new Class<?>[] { ExampleExtraInterface.class }, Answers.RETURNS_SMART_NULLS, true, MockReset.BEFORE,
qualifier);
assertThat(definition.getName()).isEqualTo("name");
assertThat(definition.getTypeToMock()).isEqualTo(EXAMPLE_SERVICE_TYPE);
assertThat(definition.getExtraInterfaces())
.containsExactly(ExampleExtraInterface.class);
assertThat(definition.getExtraInterfaces()).containsExactly(ExampleExtraInterface.class);
assertThat(definition.getAnswer()).isEqualTo(Answers.RETURNS_SMART_NULLS);
assertThat(definition.isSerializable()).isTrue();
assertThat(definition.getReset()).isEqualTo(MockReset.BEFORE);
@@ -83,11 +80,10 @@ public class MockDefinitionTests {
@Test
public void createMock() {
MockDefinition definition = new MockDefinition("name", EXAMPLE_SERVICE_TYPE,
new Class<?>[] { ExampleExtraInterface.class },
Answers.RETURNS_SMART_NULLS, true, MockReset.BEFORE, null);
new Class<?>[] { ExampleExtraInterface.class }, Answers.RETURNS_SMART_NULLS, true, MockReset.BEFORE,
null);
ExampleService mock = definition.createMock();
MockCreationSettings<?> settings = Mockito.mockingDetails(mock)
.getMockCreationSettings();
MockCreationSettings<?> settings = Mockito.mockingDetails(mock).getMockCreationSettings();
assertThat(mock).isInstanceOf(ExampleService.class);
assertThat(mock).isInstanceOf(ExampleExtraInterface.class);
assertThat(settings.getMockName().toString()).isEqualTo("name");

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2017 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -39,8 +39,7 @@ public class MockResetTests {
@Test
public void withSettingsOfNoneAttachesReset() {
ExampleService mock = mock(ExampleService.class,
MockReset.withSettings(MockReset.NONE));
ExampleService mock = mock(ExampleService.class, MockReset.withSettings(MockReset.NONE));
assertThat(MockReset.get(mock)).isEqualTo(MockReset.NONE);
}
@@ -58,15 +57,13 @@ public class MockResetTests {
@Test
public void withSettingsAttachesReset() {
ExampleService mock = mock(ExampleService.class,
MockReset.withSettings(MockReset.BEFORE));
ExampleService mock = mock(ExampleService.class, MockReset.withSettings(MockReset.BEFORE));
assertThat(MockReset.get(mock)).isEqualTo(MockReset.BEFORE);
}
@Test
public void apply() {
ExampleService mock = mock(ExampleService.class,
MockReset.apply(MockReset.AFTER, withSettings()));
ExampleService mock = mock(ExampleService.class, MockReset.apply(MockReset.AFTER, withSettings()));
assertThat(MockReset.get(mock)).isEqualTo(MockReset.AFTER);
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2017 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -40,28 +40,23 @@ public class MockitoContextCustomizerFactoryTests {
@Test
public void getContextCustomizerWithoutAnnotationReturnsCustomizer() {
ContextCustomizer customizer = this.factory
.createContextCustomizer(NoMockBeanAnnotation.class, null);
ContextCustomizer customizer = this.factory.createContextCustomizer(NoMockBeanAnnotation.class, null);
assertThat(customizer).isNotNull();
}
@Test
public void getContextCustomizerWithAnnotationReturnsCustomizer() {
ContextCustomizer customizer = this.factory
.createContextCustomizer(WithMockBeanAnnotation.class, null);
ContextCustomizer customizer = this.factory.createContextCustomizer(WithMockBeanAnnotation.class, null);
assertThat(customizer).isNotNull();
}
@Test
public void getContextCustomizerUsesMocksAsCacheKey() {
ContextCustomizer customizer = this.factory
.createContextCustomizer(WithMockBeanAnnotation.class, null);
ContextCustomizer customizer = this.factory.createContextCustomizer(WithMockBeanAnnotation.class, null);
assertThat(customizer).isNotNull();
ContextCustomizer same = this.factory
.createContextCustomizer(WithSameMockBeanAnnotation.class, null);
ContextCustomizer same = this.factory.createContextCustomizer(WithSameMockBeanAnnotation.class, null);
assertThat(customizer).isNotNull();
ContextCustomizer different = this.factory
.createContextCustomizer(WithDifferentMockBeanAnnotation.class, null);
ContextCustomizer different = this.factory.createContextCustomizer(WithDifferentMockBeanAnnotation.class, null);
assertThat(different).isNotNull();
assertThat(customizer.hashCode()).isEqualTo(same.hashCode());
assertThat(customizer.hashCode()).isNotEqualTo(different.hashCode());

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2017 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -43,18 +43,15 @@ public class MockitoContextCustomizerTests {
MockDefinition d1 = createTestMockDefinition(ExampleService.class);
MockDefinition d2 = createTestMockDefinition(ExampleServiceCaller.class);
MockitoContextCustomizer c1 = new MockitoContextCustomizer(NO_DEFINITIONS);
MockitoContextCustomizer c2 = new MockitoContextCustomizer(
new LinkedHashSet<>(Arrays.asList(d1, d2)));
MockitoContextCustomizer c3 = new MockitoContextCustomizer(
new LinkedHashSet<>(Arrays.asList(d2, d1)));
MockitoContextCustomizer c2 = new MockitoContextCustomizer(new LinkedHashSet<>(Arrays.asList(d1, d2)));
MockitoContextCustomizer c3 = new MockitoContextCustomizer(new LinkedHashSet<>(Arrays.asList(d2, d1)));
assertThat(c2.hashCode()).isEqualTo(c3.hashCode());
assertThat(c1).isEqualTo(c1).isNotEqualTo(c2);
assertThat(c2).isEqualTo(c2).isEqualTo(c3).isNotEqualTo(c1);
}
private MockDefinition createTestMockDefinition(Class<?> typeToMock) {
return new MockDefinition(null, ResolvableType.forClass(typeToMock), null, null,
false, null, null);
return new MockDefinition(null, ResolvableType.forClass(typeToMock), null, null, false, null, null);
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2017 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -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

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -59,8 +59,7 @@ public class MockitoTestExecutionListenerTests {
@Before
public void setup() {
MockitoAnnotations.initMocks(this);
given(this.applicationContext.getBean(MockitoPostProcessor.class))
.willReturn(this.postProcessor);
given(this.applicationContext.getBean(MockitoPostProcessor.class)).willReturn(this.postProcessor);
}
@Test
@@ -75,30 +74,25 @@ public class MockitoTestExecutionListenerTests {
public void prepareTestInstanceShouldInjectMockBean() throws Exception {
WithMockBean instance = new WithMockBean();
this.listener.prepareTestInstance(mockTestContext(instance));
verify(this.postProcessor).inject(this.fieldCaptor.capture(), eq(instance),
any(MockDefinition.class));
verify(this.postProcessor).inject(this.fieldCaptor.capture(), eq(instance), any(MockDefinition.class));
assertThat(this.fieldCaptor.getValue().getName()).isEqualTo("mockBean");
}
@Test
public void beforeTestMethodShouldDoNothingWhenDirtiesContextAttributeIsNotSet()
throws Exception {
public void beforeTestMethodShouldDoNothingWhenDirtiesContextAttributeIsNotSet() throws Exception {
WithMockBean instance = new WithMockBean();
this.listener.beforeTestMethod(mockTestContext(instance));
verifyNoMoreInteractions(this.postProcessor);
}
@Test
public void beforeTestMethodShouldInjectMockBeanWhenDirtiesContextAttributeIsSet()
throws Exception {
public void beforeTestMethodShouldInjectMockBeanWhenDirtiesContextAttributeIsSet() throws Exception {
WithMockBean instance = new WithMockBean();
TestContext mockTestContext = mockTestContext(instance);
given(mockTestContext.getAttribute(
DependencyInjectionTestExecutionListener.REINJECT_DEPENDENCIES_ATTRIBUTE))
.willReturn(Boolean.TRUE);
given(mockTestContext.getAttribute(DependencyInjectionTestExecutionListener.REINJECT_DEPENDENCIES_ATTRIBUTE))
.willReturn(Boolean.TRUE);
this.listener.beforeTestMethod(mockTestContext);
verify(this.postProcessor).inject(this.fieldCaptor.capture(), eq(instance),
(MockDefinition) any());
verify(this.postProcessor).inject(this.fieldCaptor.capture(), eq(instance), (MockDefinition) any());
assertThat(this.fieldCaptor.getValue().getName()).isEqualTo("mockBean");
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2017 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -85,10 +85,8 @@ public class QualifierDefinitionTests {
Field field = ReflectionUtils.findField(ConfigA.class, "directQualifier");
QualifierDefinition qualifierDefinition = QualifierDefinition.forElement(field);
qualifierDefinition.matches(this.beanFactory, "bean");
verify(this.beanFactory).isAutowireCandidate(eq("bean"),
this.descriptorCaptor.capture());
assertThat(this.descriptorCaptor.getValue().getAnnotatedElement())
.isEqualTo(field);
verify(this.beanFactory).isAutowireCandidate(eq("bean"), this.descriptorCaptor.capture());
assertThat(this.descriptorCaptor.getValue().getAnnotatedElement()).isEqualTo(field);
}
@Test
@@ -106,24 +104,23 @@ public class QualifierDefinitionTests {
.forElement(ReflectionUtils.findField(ConfigA.class, "directQualifier"));
QualifierDefinition directQualifier2 = QualifierDefinition
.forElement(ReflectionUtils.findField(ConfigB.class, "directQualifier"));
QualifierDefinition differentDirectQualifier1 = QualifierDefinition.forElement(
ReflectionUtils.findField(ConfigA.class, "differentDirectQualifier"));
QualifierDefinition differentDirectQualifier2 = QualifierDefinition.forElement(
ReflectionUtils.findField(ConfigB.class, "differentDirectQualifier"));
QualifierDefinition differentDirectQualifier1 = QualifierDefinition
.forElement(ReflectionUtils.findField(ConfigA.class, "differentDirectQualifier"));
QualifierDefinition differentDirectQualifier2 = QualifierDefinition
.forElement(ReflectionUtils.findField(ConfigB.class, "differentDirectQualifier"));
QualifierDefinition customQualifier1 = QualifierDefinition
.forElement(ReflectionUtils.findField(ConfigA.class, "customQualifier"));
QualifierDefinition customQualifier2 = QualifierDefinition
.forElement(ReflectionUtils.findField(ConfigB.class, "customQualifier"));
assertThat(directQualifier1.hashCode()).isEqualTo(directQualifier2.hashCode());
assertThat(differentDirectQualifier1.hashCode())
.isEqualTo(differentDirectQualifier2.hashCode());
assertThat(differentDirectQualifier1.hashCode()).isEqualTo(differentDirectQualifier2.hashCode());
assertThat(customQualifier1.hashCode()).isEqualTo(customQualifier2.hashCode());
assertThat(differentDirectQualifier1).isEqualTo(differentDirectQualifier1)
.isEqualTo(differentDirectQualifier2).isNotEqualTo(directQualifier2);
assertThat(directQualifier1).isEqualTo(directQualifier1)
.isEqualTo(directQualifier2).isNotEqualTo(differentDirectQualifier1);
assertThat(customQualifier1).isEqualTo(customQualifier1)
.isEqualTo(customQualifier2).isNotEqualTo(differentDirectQualifier1);
assertThat(differentDirectQualifier1).isEqualTo(differentDirectQualifier1).isEqualTo(differentDirectQualifier2)
.isNotEqualTo(directQualifier2);
assertThat(directQualifier1).isEqualTo(directQualifier1).isEqualTo(directQualifier2)
.isNotEqualTo(differentDirectQualifier1);
assertThat(customQualifier1).isEqualTo(customQualifier1).isEqualTo(customQualifier2)
.isNotEqualTo(differentDirectQualifier1);
}
@Configuration

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2017 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -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;
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2017 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -56,8 +56,7 @@ public class SpyBeanOnTestFieldForExistingGenericBeanIntegrationTests {
}
@Configuration
@Import({ ExampleGenericServiceCaller.class,
SimpleExampleIntegerGenericService.class })
@Import({ ExampleGenericServiceCaller.class, SimpleExampleIntegerGenericService.class })
static class SpyBeanOnTestFieldForExistingBeanConfig {
@Bean

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2017 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -50,8 +50,8 @@ public class SpyBeanOnTestFieldForMultipleExistingBeansWithOnePrimaryIntegration
@Test
public void testSpying() {
assertThat(this.caller.sayGreeting()).isEqualTo("I say two");
assertThat(Mockito.mockingDetails(this.spy).getMockCreationSettings()
.getMockName().toString()).isEqualTo("two");
assertThat(Mockito.mockingDetails(this.spy).getMockCreationSettings().getMockName().toString())
.isEqualTo("two");
verify(this.spy).greeting();
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2017 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -45,8 +45,7 @@ public class SpyBeanWithNameOnTestFieldForMultipleExistingBeansTests {
public void testSpying() {
MockingDetails mockingDetails = Mockito.mockingDetails(this.spy);
assertThat(mockingDetails.isSpy()).isTrue();
assertThat(mockingDetails.getMockCreationSettings().getMockName().toString())
.isEqualTo("two");
assertThat(mockingDetails.getMockCreationSettings().getMockName().toString()).isEqualTo("two");
}
@Configuration

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2017 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -38,8 +38,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();
@@ -53,8 +52,7 @@ public class SpyDefinitionTests {
@Test
public void createWithDefaults() {
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);
@@ -65,8 +63,7 @@ public class SpyDefinitionTests {
@Test
public void createExplicit() {
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);
@@ -76,11 +73,9 @@ public class SpyDefinitionTests {
@Test
public void createSpy() {
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 = Mockito.mockingDetails(spy)
.getMockCreationSettings();
MockCreationSettings<?> settings = Mockito.mockingDetails(spy).getMockCreationSettings();
assertThat(spy).isInstanceOf(ExampleService.class);
assertThat(settings.getMockName().toString()).isEqualTo("name");
assertThat(settings.getDefaultAnswer()).isEqualTo(Answers.CALLS_REAL_METHODS);
@@ -89,8 +84,7 @@ public class SpyDefinitionTests {
@Test
public void createSpyWhenNullInstanceShouldThrowException() {
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);
@@ -98,8 +92,7 @@ public class SpyDefinitionTests {
@Test
public void createSpyWhenWrongInstanceShouldThrowException() {
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));
@@ -107,8 +100,7 @@ public class SpyDefinitionTests {
@Test
public void createSpyTwice() {
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);

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2017 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -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();
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2017 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -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;
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2017 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -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() {

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2017 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -64,8 +64,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);
@@ -74,8 +73,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
@@ -86,8 +84,7 @@ public class SpringBootMockServletContextTests implements ServletContextAware {
assertThat(resource).isNotEqualTo(nullValue());
File file = new File(URLDecoder.decode(resource.getPath(), "UTF-8"));
assertThat(file).exists().isDirectory();
String[] contents = file
.list((dir, name) -> !(".".equals(name) || "..".equals(name)));
String[] contents = file.list((dir, name) -> !(".".equals(name) || "..".equals(name)));
assertThat(contents).isNotEqualTo(nullValue());
assertThat(contents.length).isEqualTo(0);
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2017 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -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");
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2017 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -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);

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2017 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -39,8 +39,7 @@ public class TestPropertyValuesTests {
@Test
public void applyToEnvironmentShouldAttachConfigurationPropertySource() {
TestPropertyValues.of("foo.bar=baz").applyTo(this.environment);
PropertySource<?> source = this.environment.getPropertySources()
.get("configurationProperties");
PropertySource<?> source = this.environment.getPropertySources().get("configurationProperties");
assertThat(source).isNotNull();
}
@@ -53,12 +52,10 @@ public class TestPropertyValuesTests {
@Test
public void applyToSystemPropertySource() {
TestPropertyValues.of("FOO_BAR=BAZ").applyTo(this.environment,
Type.SYSTEM_ENVIRONMENT);
TestPropertyValues.of("FOO_BAR=BAZ").applyTo(this.environment, Type.SYSTEM_ENVIRONMENT);
assertThat(this.environment.getProperty("foo.bar")).isEqualTo("BAZ");
assertThat(this.environment.getPropertySources().contains(
"test-" + StandardEnvironment.SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME))
.isTrue();
assertThat(this.environment.getPropertySources()
.contains("test-" + StandardEnvironment.SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME)).isTrue();
}
@Test
@@ -70,10 +67,8 @@ public class TestPropertyValuesTests {
@Test
public void applyToExistingNameAndDifferentTypeShouldOverrideExistingOne() {
TestPropertyValues.of("foo.bar=baz", "hello.world=hi").applyTo(this.environment,
Type.MAP, "other");
TestPropertyValues.of("FOO_BAR=BAZ").applyTo(this.environment,
Type.SYSTEM_ENVIRONMENT, "other");
TestPropertyValues.of("foo.bar=baz", "hello.world=hi").applyTo(this.environment, Type.MAP, "other");
TestPropertyValues.of("FOO_BAR=BAZ").applyTo(this.environment, Type.SYSTEM_ENVIRONMENT, "other");
assertThat(this.environment.getPropertySources().get("other"))
.isInstanceOf(SystemEnvironmentPropertySource.class);
assertThat(this.environment.getProperty("foo.bar")).isEqualTo("BAZ");
@@ -82,8 +77,7 @@ public class TestPropertyValuesTests {
@Test
public void applyToExistingNameAndSameTypeShouldMerge() {
TestPropertyValues.of("foo.bar=baz", "hello.world=hi").applyTo(this.environment,
Type.MAP);
TestPropertyValues.of("foo.bar=baz", "hello.world=hi").applyTo(this.environment, Type.MAP);
TestPropertyValues.of("foo.bar=new").applyTo(this.environment, Type.MAP);
assertThat(this.environment.getProperty("foo.bar")).isEqualTo("new");
assertThat(this.environment.getProperty("hello.world")).isEqualTo("hi");
@@ -91,8 +85,8 @@ public class TestPropertyValuesTests {
@Test
public void andShouldChainAndAddSingleKeyValue() {
TestPropertyValues.of("foo.bar=baz").and("hello.world=hi").and("bling.blah=bing")
.applyTo(this.environment, Type.MAP);
TestPropertyValues.of("foo.bar=baz").and("hello.world=hi").and("bling.blah=bing").applyTo(this.environment,
Type.MAP);
assertThat(this.environment.getProperty("foo.bar")).isEqualTo("baz");
assertThat(this.environment.getProperty("hello.world")).isEqualTo("hi");
assertThat(this.environment.getProperty("bling.blah")).isEqualTo("bing");

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -69,24 +69,21 @@ public class LocalHostUriTemplateHandlerTests {
public void getRootUriShouldUseLocalServerPort() {
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() {
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");
}
@@ -94,8 +91,7 @@ public class LocalHostUriTemplateHandlerTests {
public void getRootUriShouldUseContextPath() {
MockEnvironment environment = new MockEnvironment();
environment.setProperty("server.servlet.context-path", "/foo");
LocalHostUriTemplateHandler handler = new LocalHostUriTemplateHandler(
environment);
LocalHostUriTemplateHandler handler = new LocalHostUriTemplateHandler(environment);
assertThat(handler.getRootUri()).isEqualTo("http://localhost:8080/foo");
}
@@ -105,10 +101,8 @@ public class LocalHostUriTemplateHandlerTests {
UriTemplateHandler uriTemplateHandler = mock(UriTemplateHandler.class);
Map<String, ?> uriVariables = new HashMap<>();
URI uri = URI.create("https://www.example.com");
given(uriTemplateHandler.expand("https://localhost:8080/", uriVariables))
.willReturn(uri);
LocalHostUriTemplateHandler handler = new LocalHostUriTemplateHandler(environment,
"https", uriTemplateHandler);
given(uriTemplateHandler.expand("https://localhost:8080/", uriVariables)).willReturn(uri);
LocalHostUriTemplateHandler handler = new LocalHostUriTemplateHandler(environment, "https", uriTemplateHandler);
assertThat(handler.expand("/", uriVariables)).isEqualTo(uri);
verify(uriTemplateHandler).expand("https://localhost:8080/", uriVariables);
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2017 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -76,8 +76,7 @@ public class MockServerRestTemplateCustomizerTests {
public void detectRootUriShouldDefaultToTrue() {
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);
}
@@ -85,8 +84,7 @@ public class MockServerRestTemplateCustomizerTests {
@Test
public void setDetectRootUriShouldDisableRootUriDetection() {
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);
@@ -122,8 +120,7 @@ public class MockServerRestTemplateCustomizerTests {
public void getServerWhenSingleServerIsBoundShouldReturnServer() {
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
@@ -133,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
@@ -161,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);
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -34,8 +34,8 @@ class NoTestRestTemplateBeanChecker implements ImportSelector, BeanFactoryAware
@Override
public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
assertThat(BeanFactoryUtils.beanNamesForTypeIncludingAncestors(
(ListableBeanFactory) beanFactory, TestRestTemplate.class)).isEmpty();
assertThat(BeanFactoryUtils.beanNamesForTypeIncludingAncestors((ListableBeanFactory) beanFactory,
TestRestTemplate.class)).isEmpty();
}
@Override

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -93,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);
@@ -102,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);
@@ -114,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(any(ClientHttpRequest.class)))
.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);
@@ -135,24 +131,22 @@ public class RootUriRequestExpectationManagerTests {
@Test
public void bindToShouldReturnMockRestServiceServer() {
RestTemplate restTemplate = new RestTemplateBuilder().build();
MockRestServiceServer bound = RootUriRequestExpectationManager
.bindTo(restTemplate);
MockRestServiceServer bound = RootUriRequestExpectationManager.bindTo(restTemplate);
assertThat(bound).isNotNull();
}
@Test
public void bindToWithExpectationManagerShouldReturnMockRestServiceServer() {
RestTemplate restTemplate = new RestTemplateBuilder().build();
MockRestServiceServer bound = RootUriRequestExpectationManager
.bindTo(restTemplate, this.delegate);
MockRestServiceServer bound = RootUriRequestExpectationManager.bindTo(restTemplate, this.delegate);
assertThat(bound).isNotNull();
}
@Test
public void forRestTemplateWhenUsingRootUriTemplateHandlerShouldReturnRootUriRequestExpectationManager() {
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);
}
@@ -160,31 +154,26 @@ public class RootUriRequestExpectationManagerTests {
@Test
public void forRestTemplateWhenNotUsingRootUriTemplateHandlerShouldReturnOriginalRequestExpectationManager() {
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);
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -71,8 +71,7 @@ public class TestRestTemplateContextCustomizerIntegrationTests {
static class TestServlet extends GenericServlet {
@Override
public void service(ServletRequest request, ServletResponse response)
throws ServletException, IOException {
public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException {
try (PrintWriter writer = response.getWriter()) {
writer.println("hello");
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -77,8 +77,7 @@ public class TestRestTemplateContextCustomizerWithOverrideIntegrationTests {
static class TestServlet extends GenericServlet {
@Override
public void service(ServletRequest request, ServletResponse response)
throws ServletException, IOException {
public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException {
try (PrintWriter writer = response.getWriter()) {
writer.println("hello");
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -86,8 +86,7 @@ public class TestRestTemplateTests {
@Test
public void doNotReplaceCustomRequestFactory() {
RestTemplateBuilder builder = new RestTemplateBuilder()
.requestFactory(OkHttp3ClientHttpRequestFactory.class);
RestTemplateBuilder builder = new RestTemplateBuilder().requestFactory(OkHttp3ClientHttpRequestFactory.class);
TestRestTemplate testRestTemplate = new TestRestTemplate(builder);
assertThat(testRestTemplate.getRestTemplate().getRequestFactory())
.isInstanceOf(OkHttp3ClientHttpRequestFactory.class);
@@ -104,8 +103,7 @@ public class TestRestTemplateTests {
public void getRootUriRootUriSetViaLocalHostUriTemplateHandler() {
String rootUri = "https://example.com";
TestRestTemplate template = new TestRestTemplate();
LocalHostUriTemplateHandler templateHandler = mock(
LocalHostUriTemplateHandler.class);
LocalHostUriTemplateHandler templateHandler = mock(LocalHostUriTemplateHandler.class);
given(templateHandler.getRootUri()).willReturn(rootUri);
template.setUriTemplateHandler(templateHandler);
assertThat(template.getRootUri()).isEqualTo(rootUri);
@@ -118,15 +116,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() {
TestRestTemplate template = new TestRestTemplate(
HttpClientOption.ENABLE_REDIRECTS);
TestRestTemplate template = new TestRestTemplate(HttpClientOption.ENABLE_REDIRECTS);
CustomHttpComponentsClientHttpRequestFactory factory = (CustomHttpComponentsClientHttpRequestFactory) template
.getRestTemplate().getRequestFactory();
RequestConfig config = factory.getRequestConfig();
@@ -136,10 +132,8 @@ public class TestRestTemplateTests {
@Test
public void restOperationsAreAvailable() {
RestTemplate delegate = mock(RestTemplate.class);
given(delegate.getRequestFactory())
.willReturn(new SimpleClientHttpRequestFactory());
given(delegate.getUriTemplateHandler())
.willReturn(new DefaultUriBuilderFactory());
given(delegate.getRequestFactory()).willReturn(new SimpleClientHttpRequestFactory());
given(delegate.getUriTemplateHandler()).willReturn(new DefaultUriBuilderFactory());
RestTemplateBuilder builder = mock(RestTemplateBuilder.class);
given(builder.build()).willReturn(delegate);
TestRestTemplate restTemplate = new TestRestTemplate(builder);
@@ -147,14 +141,13 @@ public class TestRestTemplateTests {
@Override
public void doWith(Method method) throws IllegalArgumentException {
Method equivalent = ReflectionUtils.findMethod(TestRestTemplate.class,
method.getName(), method.getParameterTypes());
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);
@@ -199,37 +192,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);
@@ -241,10 +227,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
@@ -253,55 +237,47 @@ public class TestRestTemplateTests {
}
@Test
public void exchangeWithRequestEntityAndClassHandlesRelativeUris()
throws IOException {
public void exchangeWithRequestEntityAndClassHandlesRelativeUris() throws IOException {
verifyRelativeUriHandling((testRestTemplate, relativeUri) -> testRestTemplate
.exchange(new RequestEntity<String>(HttpMethod.GET, relativeUri),
String.class));
.exchange(new RequestEntity<String>(HttpMethod.GET, relativeUri), String.class));
}
@Test
public void exchangeWithRequestEntityAndParameterizedTypeReferenceHandlesRelativeUris()
throws IOException {
verifyRelativeUriHandling((testRestTemplate, relativeUri) -> testRestTemplate
.exchange(new RequestEntity<String>(HttpMethod.GET, relativeUri),
new ParameterizedTypeReference<String>() {
}));
public void exchangeWithRequestEntityAndParameterizedTypeReferenceHandlesRelativeUris() throws IOException {
verifyRelativeUriHandling((testRestTemplate, relativeUri) -> testRestTemplate.exchange(
new RequestEntity<String>(HttpMethod.GET, relativeUri), new ParameterizedTypeReference<String>() {
}));
}
@Test
public void exchangeHandlesRelativeUris() throws IOException {
verifyRelativeUriHandling(
(testRestTemplate, relativeUri) -> testRestTemplate.exchange(relativeUri,
HttpMethod.GET, new HttpEntity<>(new byte[0]), String.class));
verifyRelativeUriHandling((testRestTemplate, relativeUri) -> testRestTemplate.exchange(relativeUri,
HttpMethod.GET, new HttpEntity<>(new byte[0]), String.class));
}
@Test
public void exchangeWithParameterizedTypeReferenceHandlesRelativeUris()
throws IOException {
verifyRelativeUriHandling(
(testRestTemplate, relativeUri) -> testRestTemplate.exchange(relativeUri,
HttpMethod.GET, new HttpEntity<>(new byte[0]),
new ParameterizedTypeReference<String>() {
}));
public void exchangeWithParameterizedTypeReferenceHandlesRelativeUris() throws IOException {
verifyRelativeUriHandling((testRestTemplate, relativeUri) -> testRestTemplate.exchange(relativeUri,
HttpMethod.GET, new HttpEntity<>(new byte[0]), new ParameterizedTypeReference<String>() {
}));
}
@Test
public void executeHandlesRelativeUris() throws IOException {
verifyRelativeUriHandling((testRestTemplate, relativeUri) -> testRestTemplate
.execute(relativeUri, HttpMethod.GET, null, null));
verifyRelativeUriHandling(
(testRestTemplate, relativeUri) -> testRestTemplate.execute(relativeUri, HttpMethod.GET, null, null));
}
@Test
public void getForEntityHandlesRelativeUris() throws IOException {
verifyRelativeUriHandling((testRestTemplate, relativeUri) -> testRestTemplate
.getForEntity(relativeUri, String.class));
verifyRelativeUriHandling(
(testRestTemplate, relativeUri) -> testRestTemplate.getForEntity(relativeUri, String.class));
}
@Test
public void getForObjectHandlesRelativeUris() throws IOException {
verifyRelativeUriHandling((testRestTemplate, relativeUri) -> testRestTemplate
.getForObject(relativeUri, String.class));
verifyRelativeUriHandling(
(testRestTemplate, relativeUri) -> testRestTemplate.getForObject(relativeUri, String.class));
}
@Test
@@ -316,66 +292,57 @@ public class TestRestTemplateTests {
@Test
public void patchForObjectHandlesRelativeUris() throws IOException {
verifyRelativeUriHandling((testRestTemplate, relativeUri) -> testRestTemplate
.patchForObject(relativeUri, "hello", String.class));
verifyRelativeUriHandling(
(testRestTemplate, relativeUri) -> testRestTemplate.patchForObject(relativeUri, "hello", String.class));
}
@Test
public void postForEntityHandlesRelativeUris() throws IOException {
verifyRelativeUriHandling((testRestTemplate, relativeUri) -> testRestTemplate
.postForEntity(relativeUri, "hello", String.class));
verifyRelativeUriHandling(
(testRestTemplate, relativeUri) -> testRestTemplate.postForEntity(relativeUri, "hello", String.class));
}
@Test
public void postForLocationHandlesRelativeUris() throws IOException {
verifyRelativeUriHandling((testRestTemplate, relativeUri) -> testRestTemplate
.postForLocation(relativeUri, "hello"));
verifyRelativeUriHandling(
(testRestTemplate, relativeUri) -> testRestTemplate.postForLocation(relativeUri, "hello"));
}
@Test
public void postForObjectHandlesRelativeUris() throws IOException {
verifyRelativeUriHandling((testRestTemplate, relativeUri) -> testRestTemplate
.postForObject(relativeUri, "hello", String.class));
verifyRelativeUriHandling(
(testRestTemplate, relativeUri) -> testRestTemplate.postForObject(relativeUri, "hello", String.class));
}
@Test
public void putHandlesRelativeUris() throws IOException {
verifyRelativeUriHandling((testRestTemplate, relativeUri) -> testRestTemplate
.put(relativeUri, "hello"));
verifyRelativeUriHandling((testRestTemplate, 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), any(HttpMethod.class)))
.willReturn(request);
URI absoluteUri = URI.create("http://localhost:8080/a/b/c.txt?param=%7Bsomething%7D");
given(requestFactory.createRequest(eq(absoluteUri), any(HttpMethod.class))).willReturn(request);
TestRestTemplate template = new TestRestTemplate();
template.getRestTemplate().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), any(HttpMethod.class));
}
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);
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2017 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -72,13 +72,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);
@@ -86,8 +84,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 IOException {

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2017 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -92,30 +92,25 @@ 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(any(WebWindow.class),
requestToUrl(new URL("http://localhost:8080/test")));
verify(this.webClient).getPage(any(WebWindow.class), requestToUrl(new URL("http://localhost:8080/test")));
}
@Test
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(any(WebWindow.class),
requestToUrl(new URL("http://localhost:8181/test")));
verify(this.webClient).getPage(any(WebWindow.class), requestToUrl(new URL("http://localhost:8181/test")));
}
private WebRequest requestToUrl(URL url) {
return argThat(new WebRequestUrlArgumentMatcher(url));
}
public class TestLocalHostWebConnectionHtmlUnitDriver
extends LocalHostWebConnectionHtmlUnitDriver {
public class TestLocalHostWebConnectionHtmlUnitDriver extends LocalHostWebConnectionHtmlUnitDriver {
public TestLocalHostWebConnectionHtmlUnitDriver(Environment environment) {
super(environment);
@@ -128,8 +123,7 @@ public class LocalHostWebConnectionHtmlUnitDriverTests {
}
private static final class WebRequestUrlArgumentMatcher
implements ArgumentMatcher<WebRequest> {
private static final class WebRequestUrlArgumentMatcher implements ArgumentMatcher<WebRequest> {
private final URL expectedUrl;

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -35,8 +35,8 @@ class NoWebTestClientBeanChecker implements ImportSelector, BeanFactoryAware {
@Override
public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
assertThat(BeanFactoryUtils.beanNamesForTypeIncludingAncestors(
(ListableBeanFactory) beanFactory, WebTestClient.class)).isEmpty();
assertThat(BeanFactoryUtils.beanNamesForTypeIncludingAncestors((ListableBeanFactory) beanFactory,
WebTestClient.class)).isEmpty();
}
@Override

View File

@@ -42,8 +42,7 @@ import org.springframework.test.web.reactive.server.WebTestClient;
* @author Phillip Webb
*/
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT,
properties = "spring.main.web-application-type=reactive")
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, properties = "spring.main.web-application-type=reactive")
@DirtiesContext
public class WebTestClientContextCustomizerIntegrationTests {
@@ -52,8 +51,7 @@ public class WebTestClientContextCustomizerIntegrationTests {
@Test
public void test() {
this.webTestClient.get().uri("/").exchange().expectBody(String.class)
.isEqualTo("hello");
this.webTestClient.get().uri("/").exchange().expectBody(String.class).isEqualTo("hello");
}
@Configuration

View File

@@ -46,8 +46,7 @@ import static org.mockito.Mockito.mock;
* @author Phillip Webb
*/
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT,
properties = "spring.main.web-application-type=reactive")
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, properties = "spring.main.web-application-type=reactive")
@DirtiesContext
public class WebTestClientContextCustomizerWithOverrideIntegrationTests {