Merge branch '2.1.x'

Closes gh-17079
This commit is contained in:
Andy Wilkinson
2019-06-07 11:00:44 +01:00
2799 changed files with 28402 additions and 47836 deletions

View File

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

@@ -71,8 +71,7 @@ public abstract class AbstractSpringBootTestWebServerWebEnvironmentTests {
@Test
public void runAndTestHttpEndpoint() {
assertThat(this.port).isNotEqualTo(8080).isNotEqualTo(0);
String body = new RestTemplate()
.getForObject("http://localhost:" + this.port + "/", String.class);
String body = new RestTemplate().getForObject("http://localhost:" + this.port + "/", String.class);
assertThat(body).isEqualTo("Hello World");
}
@@ -89,8 +88,7 @@ public abstract class AbstractSpringBootTestWebServerWebEnvironmentTests {
@Test
public void validateWebApplicationContextIsSet() {
assertThat(this.context).isSameAs(
WebApplicationContextUtils.getWebApplicationContext(this.servletContext));
assertThat(this.context).isSameAs(WebApplicationContextUtils.getWebApplicationContext(this.servletContext));
}
protected abstract static class AbstractConfig {

View File

@@ -32,20 +32,17 @@ import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException
*/
public class AnnotatedClassFinderTests {
private AnnotatedClassFinder finder = new AnnotatedClassFinder(
SpringBootConfiguration.class);
private AnnotatedClassFinder finder = new AnnotatedClassFinder(SpringBootConfiguration.class);
@Test
public void findFromClassWhenSourceIsNullShouldThrowException() {
assertThatIllegalArgumentException()
.isThrownBy(() -> this.finder.findFromClass((Class<?>) null))
assertThatIllegalArgumentException().isThrownBy(() -> this.finder.findFromClass((Class<?>) null))
.withMessageContaining("Source must not be null");
}
@Test
public void findFromPackageWhenSourceIsNullShouldThrowException() {
assertThatIllegalArgumentException()
.isThrownBy(() -> this.finder.findFromPackage((String) null))
assertThatIllegalArgumentException().isThrownBy(() -> this.finder.findFromPackage((String) null))
.withMessageContaining("Source must not be null");
}
@@ -63,8 +60,7 @@ public class AnnotatedClassFinderTests {
@Test
public void findFromPackageWhenConfigurationIsFoundShouldReturnConfiguration() {
Class<?> config = this.finder
.findFromPackage("org.springframework.boot.test.context.example.scan");
Class<?> config = this.finder.findFromPackage("org.springframework.boot.test.context.example.scan");
assertThat(config).isEqualTo(ExampleConfig.class);
}

View File

@@ -39,8 +39,7 @@ public class FilteredClassLoaderTests {
"org/springframework/boot/test/context/FilteredClassLoaderTestsResource.txt");
@Test
public void loadClassWhenFilteredOnPackageShouldThrowClassNotFound()
throws Exception {
public void loadClassWhenFilteredOnPackageShouldThrowClassNotFound() throws Exception {
try (FilteredClassLoader classLoader = new FilteredClassLoader(
FilteredClassLoaderTests.class.getPackage().getName())) {
assertThatExceptionOfType(ClassNotFoundException.class)
@@ -50,8 +49,7 @@ public class FilteredClassLoaderTests {
@Test
public void loadClassWhenFilteredOnClassShouldThrowClassNotFound() throws Exception {
try (FilteredClassLoader classLoader = new FilteredClassLoader(
FilteredClassLoaderTests.class)) {
try (FilteredClassLoader classLoader = new FilteredClassLoader(FilteredClassLoaderTests.class)) {
assertThatExceptionOfType(ClassNotFoundException.class)
.isThrownBy(() -> classLoader.loadClass(getClass().getName()));
}
@@ -66,8 +64,7 @@ public class FilteredClassLoaderTests {
}
@Test
public void loadResourceWhenFilteredOnResourceShouldReturnNotFound()
throws Exception {
public void loadResourceWhenFilteredOnResourceShouldReturnNotFound() throws Exception {
try (FilteredClassLoader classLoader = new FilteredClassLoader(TEST_RESOURCE)) {
final URL loaded = classLoader.getResource(TEST_RESOURCE.getPath());
assertThat(loaded).isNull();
@@ -76,49 +73,40 @@ public class FilteredClassLoaderTests {
@Test
public void loadResourceWhenNotFilteredShouldLoadResource() throws Exception {
try (FilteredClassLoader classLoader = new FilteredClassLoader(
(resourceName) -> false)) {
try (FilteredClassLoader classLoader = new FilteredClassLoader((resourceName) -> false)) {
final URL loaded = classLoader.getResource(TEST_RESOURCE.getPath());
assertThat(loaded).isNotNull();
}
}
@Test
public void loadResourcesWhenFilteredOnResourceShouldReturnNotFound()
throws Exception {
public void loadResourcesWhenFilteredOnResourceShouldReturnNotFound() throws Exception {
try (FilteredClassLoader classLoader = new FilteredClassLoader(TEST_RESOURCE)) {
final Enumeration<URL> loaded = classLoader
.getResources(TEST_RESOURCE.getPath());
final Enumeration<URL> loaded = classLoader.getResources(TEST_RESOURCE.getPath());
assertThat(loaded.hasMoreElements()).isFalse();
}
}
@Test
public void loadResourcesWhenNotFilteredShouldLoadResource() throws Exception {
try (FilteredClassLoader classLoader = new FilteredClassLoader(
(resourceName) -> false)) {
final Enumeration<URL> loaded = classLoader
.getResources(TEST_RESOURCE.getPath());
try (FilteredClassLoader classLoader = new FilteredClassLoader((resourceName) -> false)) {
final Enumeration<URL> loaded = classLoader.getResources(TEST_RESOURCE.getPath());
assertThat(loaded.hasMoreElements()).isTrue();
}
}
@Test
public void loadResourceAsStreamWhenFilteredOnResourceShouldReturnNotFound()
throws Exception {
public void loadResourceAsStreamWhenFilteredOnResourceShouldReturnNotFound() throws Exception {
try (FilteredClassLoader classLoader = new FilteredClassLoader(TEST_RESOURCE)) {
final InputStream loaded = classLoader
.getResourceAsStream(TEST_RESOURCE.getPath());
final InputStream loaded = classLoader.getResourceAsStream(TEST_RESOURCE.getPath());
assertThat(loaded).isNull();
}
}
@Test
public void loadResourceAsStreamWhenNotFilteredShouldLoadResource() throws Exception {
try (FilteredClassLoader classLoader = new FilteredClassLoader(
(resourceName) -> false)) {
final InputStream loaded = classLoader
.getResourceAsStream(TEST_RESOURCE.getPath());
try (FilteredClassLoader classLoader = new FilteredClassLoader((resourceName) -> false)) {
final InputStream loaded = classLoader.getResourceAsStream(TEST_RESOURCE.getPath());
assertThat(loaded).isNotNull();
}
}

View File

@@ -45,54 +45,45 @@ public class ImportsContextCustomizerFactoryTests {
@Test
public void getContextCustomizerWhenHasNoImportAnnotationShouldReturnNull() {
ContextCustomizer customizer = this.factory
.createContextCustomizer(TestWithNoImport.class, null);
ContextCustomizer customizer = this.factory.createContextCustomizer(TestWithNoImport.class, null);
assertThat(customizer).isNull();
}
@Test
public void getContextCustomizerWhenHasImportAnnotationShouldReturnCustomizer() {
ContextCustomizer customizer = this.factory
.createContextCustomizer(TestWithImport.class, null);
ContextCustomizer customizer = this.factory.createContextCustomizer(TestWithImport.class, null);
assertThat(customizer).isNotNull();
}
@Test
public void getContextCustomizerWhenHasMetaImportAnnotationShouldReturnCustomizer() {
ContextCustomizer customizer = this.factory
.createContextCustomizer(TestWithMetaImport.class, null);
ContextCustomizer customizer = this.factory.createContextCustomizer(TestWithMetaImport.class, null);
assertThat(customizer).isNotNull();
}
@Test
public void contextCustomizerEqualsAndHashCode() {
ContextCustomizer customizer1 = this.factory
.createContextCustomizer(TestWithImport.class, null);
ContextCustomizer customizer2 = this.factory
.createContextCustomizer(TestWithImport.class, null);
ContextCustomizer customizer3 = this.factory
.createContextCustomizer(TestWithImportAndMetaImport.class, null);
ContextCustomizer customizer4 = this.factory
.createContextCustomizer(TestWithSameImportAndMetaImport.class, null);
ContextCustomizer customizer1 = this.factory.createContextCustomizer(TestWithImport.class, null);
ContextCustomizer customizer2 = this.factory.createContextCustomizer(TestWithImport.class, null);
ContextCustomizer customizer3 = this.factory.createContextCustomizer(TestWithImportAndMetaImport.class, null);
ContextCustomizer customizer4 = this.factory.createContextCustomizer(TestWithSameImportAndMetaImport.class,
null);
assertThat(customizer1.hashCode()).isEqualTo(customizer1.hashCode());
assertThat(customizer1.hashCode()).isEqualTo(customizer2.hashCode());
assertThat(customizer1).isEqualTo(customizer1).isEqualTo(customizer2)
.isNotEqualTo(customizer3);
assertThat(customizer1).isEqualTo(customizer1).isEqualTo(customizer2).isNotEqualTo(customizer3);
assertThat(customizer3).isEqualTo(customizer4);
}
@Test
public void getContextCustomizerWhenClassHasBeanMethodsShouldThrowException() {
assertThatIllegalStateException()
.isThrownBy(() -> this.factory
.createContextCustomizer(TestWithImportAndBeanMethod.class, null))
.isThrownBy(() -> this.factory.createContextCustomizer(TestWithImportAndBeanMethod.class, null))
.withMessageContaining("Test classes cannot include @Bean methods");
}
@Test
public void contextCustomizerImportsBeans() {
ContextCustomizer customizer = this.factory
.createContextCustomizer(TestWithImport.class, null);
ContextCustomizer customizer = this.factory.createContextCustomizer(TestWithImport.class, null);
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
customizer.customizeContext(context, mock(MergedContextConfiguration.class));
context.refresh();
@@ -101,8 +92,8 @@ public class ImportsContextCustomizerFactoryTests {
@Test
public void selfAnnotatingAnnotationDoesNotCauseStackOverflow() {
assertThat(this.factory.createContextCustomizer(
TestWithImportAndSelfAnnotatingAnnotation.class, null)).isNotNull();
assertThat(this.factory.createContextCustomizer(TestWithImportAndSelfAnnotatingAnnotation.class, null))
.isNotNull();
}
static class TestWithNoImport {

View File

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

@@ -67,14 +67,12 @@ public class SpringBootContextLoaderMockMvcTests {
@Test
public void testMockHttpEndpoint() throws Exception {
this.mvc.perform(get("/")).andExpect(status().isOk())
.andExpect(content().string("Hello World"));
this.mvc.perform(get("/")).andExpect(status().isOk()).andExpect(content().string("Hello World"));
}
@Test
public void validateWebApplicationContextIsSet() {
assertThat(this.context).isSameAs(
WebApplicationContextUtils.getWebApplicationContext(this.servletContext));
assertThat(this.context).isSameAs(WebApplicationContextUtils.getWebApplicationContext(this.servletContext));
}
@Configuration(proxyBeanMethods = false)

View File

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

@@ -41,8 +41,7 @@ public class SpringBootTestActiveProfileTests {
@Test
public void profiles() {
assertThat(this.context.getEnvironment().getActiveProfiles())
.containsExactly("override");
assertThat(this.context.getEnvironment().getActiveProfiles()).containsExactly("override");
}
@Configuration(proxyBeanMethods = false)

View File

@@ -40,8 +40,7 @@ public class SpringBootTestArgsTests {
public void applicationArgumentsPopulated() {
assertThat(this.args.getOptionNames()).containsOnly("option.foo");
assertThat(this.args.getOptionValues("option.foo")).containsOnly("foo-value");
assertThat(this.args.getNonOptionArgs())
.containsOnly("other.bar=other-bar-value");
assertThat(this.args.getNonOptionArgs()).containsOnly("other.bar=other-bar-value");
}
@Configuration(proxyBeanMethods = false)

View File

@@ -29,8 +29,8 @@ import org.springframework.web.reactive.config.EnableWebFlux;
* @author Stephane Nicoll
*/
@DirtiesContext
@SpringBootTest(webEnvironment = WebEnvironment.DEFINED_PORT, properties = {
"spring.main.web-application-type=reactive", "server.port=0", "value=123" })
@SpringBootTest(webEnvironment = WebEnvironment.DEFINED_PORT,
properties = { "spring.main.web-application-type=reactive", "server.port=0", "value=123" })
public class SpringBootTestReactiveWebEnvironmentDefinedPortTests
extends AbstractSpringBootTestEmbeddedReactiveWebEnvironmentTests {

View File

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

View File

@@ -37,13 +37,11 @@ import static org.assertj.core.api.Assertions.assertThat;
*/
@DirtiesContext
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, properties = { "value=123" })
public class SpringBootTestUserDefinedTestRestTemplateTests
extends AbstractSpringBootTestWebServerWebEnvironmentTests {
public class SpringBootTestUserDefinedTestRestTemplateTests extends AbstractSpringBootTestWebServerWebEnvironmentTests {
@Test
public void restTemplateIsUserDefined() {
assertThat(getContext().getBean("testRestTemplate"))
.isInstanceOf(RestTemplate.class);
assertThat(getContext().getBean("testRestTemplate")).isInstanceOf(RestTemplate.class);
}
// gh-7711

View File

@@ -42,8 +42,7 @@ import static org.assertj.core.api.Assertions.assertThat;
* @author Andy Wilkinson
*/
@DirtiesContext
@SpringBootTest(webEnvironment = WebEnvironment.DEFINED_PORT,
properties = { "server.port=0", "value=123" })
@SpringBootTest(webEnvironment = WebEnvironment.DEFINED_PORT, properties = { "server.port=0", "value=123" })
@ContextHierarchy({ @ContextConfiguration(classes = ParentConfiguration.class),
@ContextConfiguration(classes = ChildConfiguration.class) })
public class SpringBootTestWebEnvironmentContextHierarchyTests {

View File

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

View File

@@ -75,8 +75,7 @@ public class SpringBootTestWebEnvironmentMockTests {
@Test
public void resourcePath() {
assertThat(this.servletContext).hasFieldOrPropertyWithValue("resourceBasePath",
"src/main/webapp");
assertThat(this.servletContext).hasFieldOrPropertyWithValue("resourceBasePath", "src/main/webapp");
}
@Configuration(proxyBeanMethods = false)

View File

@@ -48,8 +48,7 @@ public class SpringBootTestWebEnvironmentMockWithWebAppConfigurationTests {
@Test
public void resourcePath() {
assertThat(this.servletContext).hasFieldOrPropertyWithValue("resourceBasePath",
"src/mymain/mywebapp");
assertThat(this.servletContext).hasFieldOrPropertyWithValue("resourceBasePath", "src/mymain/mywebapp");
}
@Configuration(proxyBeanMethods = false)

View File

@@ -35,8 +35,7 @@ import static org.assertj.core.api.Assertions.assertThat;
* @author Stephane Nicoll
*/
@DirtiesContext
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT,
properties = { "server.port=12345" })
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, properties = { "server.port=12345" })
public class SpringBootTestWebEnvironmentRandomPortCustomPortTests {
@Autowired

View File

@@ -38,8 +38,7 @@ import static org.assertj.core.api.Assertions.assertThat;
*/
@DirtiesContext
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, properties = { "value=123" })
public class SpringBootTestWebEnvironmentRandomPortTests
extends AbstractSpringBootTestWebServerWebEnvironmentTests {
public class SpringBootTestWebEnvironmentRandomPortTests extends AbstractSpringBootTestWebServerWebEnvironmentTests {
@Test
public void testRestTemplateShouldUseBuilder() {
@@ -54,8 +53,7 @@ public class SpringBootTestWebEnvironmentRandomPortTests
@Bean
public RestTemplateBuilder restTemplateBuilder() {
return new RestTemplateBuilder()
.additionalMessageConverters(new MyConverter());
return new RestTemplateBuilder().additionalMessageConverters(new MyConverter());
}

View File

@@ -36,8 +36,7 @@ import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
*/
@DirtiesContext
@SpringBootTest
@ContextConfiguration(
classes = SpringBootTestWithContextConfigurationIntegrationTests.Config.class)
@ContextConfiguration(classes = SpringBootTestWithContextConfigurationIntegrationTests.Config.class)
public class SpringBootTestWithContextConfigurationIntegrationTests {
@Autowired

View File

@@ -37,11 +37,10 @@ import static org.assertj.core.api.Assertions.assertThat;
* @author Andy Wilkinson
*/
@DirtiesContext
@SpringBootTest(webEnvironment = WebEnvironment.NONE, properties = {
"boot-test-inlined=foo", "b=boot-test-inlined", "c=boot-test-inlined" })
@SpringBootTest(webEnvironment = WebEnvironment.NONE,
properties = { "boot-test-inlined=foo", "b=boot-test-inlined", "c=boot-test-inlined" })
@TestPropertySource(
properties = { "property-source-inlined=bar", "a=property-source-inlined",
"c=property-source-inlined" },
properties = { "property-source-inlined=bar", "a=property-source-inlined", "c=property-source-inlined" },
locations = "classpath:/test-property-source-annotation.properties")
public class SpringBootTestWithTestPropertySourceTests {
@@ -71,14 +70,12 @@ public class SpringBootTestWithTestPropertySourceTests {
@Test
public void propertyFromBootTestPropertiesOverridesPropertyFromPropertySourceLocations() {
assertThat(this.config.bootTestInlinedOverridesPropertySourceLocation)
.isEqualTo("boot-test-inlined");
assertThat(this.config.bootTestInlinedOverridesPropertySourceLocation).isEqualTo("boot-test-inlined");
}
@Test
public void propertyFromPropertySourcePropertiesOverridesPropertyFromBootTestProperties() {
assertThat(this.config.propertySourceInlinedOverridesBootTestInlined)
.isEqualTo("property-source-inlined");
assertThat(this.config.propertySourceInlinedOverridesBootTestInlined).isEqualTo("property-source-inlined");
}
@Configuration(proxyBeanMethods = false)

View File

@@ -61,51 +61,44 @@ public class ApplicationContextAssertProviderTests {
@Test
public void getWhenTypeIsNullShouldThrowException() {
assertThatIllegalArgumentException()
.isThrownBy(() -> ApplicationContextAssertProvider.get(null,
ApplicationContext.class, this.mockContextSupplier))
assertThatIllegalArgumentException().isThrownBy(
() -> ApplicationContextAssertProvider.get(null, ApplicationContext.class, this.mockContextSupplier))
.withMessageContaining("Type must not be null");
}
@Test
public void getWhenTypeIsClassShouldThrowException() {
assertThatIllegalArgumentException()
.isThrownBy(() -> ApplicationContextAssertProvider.get(null,
ApplicationContext.class, this.mockContextSupplier))
assertThatIllegalArgumentException().isThrownBy(
() -> ApplicationContextAssertProvider.get(null, ApplicationContext.class, this.mockContextSupplier))
.withMessageContaining("Type must not be null");
}
@Test
public void getWhenContextTypeIsNullShouldThrowException() {
assertThatIllegalArgumentException()
.isThrownBy(() -> ApplicationContextAssertProvider.get(
TestAssertProviderApplicationContextClass.class,
.isThrownBy(() -> ApplicationContextAssertProvider.get(TestAssertProviderApplicationContextClass.class,
ApplicationContext.class, this.mockContextSupplier))
.withMessageContaining("Type must be an interface");
}
@Test
public void getWhenContextTypeIsClassShouldThrowException() {
assertThatIllegalArgumentException()
.isThrownBy(() -> ApplicationContextAssertProvider.get(
TestAssertProviderApplicationContext.class, null,
this.mockContextSupplier))
assertThatIllegalArgumentException().isThrownBy(() -> ApplicationContextAssertProvider
.get(TestAssertProviderApplicationContext.class, null, this.mockContextSupplier))
.withMessageContaining("ContextType must not be null");
}
@Test
public void getWhenSupplierIsNullShouldThrowException() {
assertThatIllegalArgumentException()
.isThrownBy(() -> ApplicationContextAssertProvider.get(
TestAssertProviderApplicationContext.class,
.isThrownBy(() -> ApplicationContextAssertProvider.get(TestAssertProviderApplicationContext.class,
StaticApplicationContext.class, this.mockContextSupplier))
.withMessageContaining("ContextType must be an interface");
}
@Test
public void getWhenContextStartsShouldReturnProxyThatCallsRealMethods() {
ApplicationContextAssertProvider<ApplicationContext> context = get(
this.mockContextSupplier);
ApplicationContextAssertProvider<ApplicationContext> context = get(this.mockContextSupplier);
assertThat((Object) context).isNotNull();
context.getBean("foo");
verify(this.mockContext).getBean("foo");
@@ -113,63 +106,54 @@ public class ApplicationContextAssertProviderTests {
@Test
public void getWhenContextFailsShouldReturnProxyThatThrowsExceptions() {
ApplicationContextAssertProvider<ApplicationContext> context = get(
this.startupFailureSupplier);
ApplicationContextAssertProvider<ApplicationContext> context = get(this.startupFailureSupplier);
assertThat((Object) context).isNotNull();
assertThatIllegalStateException().isThrownBy(() -> context.getBean("foo"))
.withCause(this.startupFailure).withMessageContaining("failed to start");
assertThatIllegalStateException().isThrownBy(() -> context.getBean("foo")).withCause(this.startupFailure)
.withMessageContaining("failed to start");
}
@Test
public void getSourceContextWhenContextStartsShouldReturnSourceContext() {
ApplicationContextAssertProvider<ApplicationContext> context = get(
this.mockContextSupplier);
ApplicationContextAssertProvider<ApplicationContext> context = get(this.mockContextSupplier);
assertThat(context.getSourceApplicationContext()).isSameAs(this.mockContext);
}
@Test
public void getSourceContextWhenContextFailsShouldThrowException() {
ApplicationContextAssertProvider<ApplicationContext> context = get(
this.startupFailureSupplier);
ApplicationContextAssertProvider<ApplicationContext> context = get(this.startupFailureSupplier);
assertThatIllegalStateException().isThrownBy(context::getSourceApplicationContext)
.withCause(this.startupFailure).withMessageContaining("failed to start");
}
@Test
public void getSourceContextOfTypeWhenContextStartsShouldReturnSourceContext() {
ApplicationContextAssertProvider<ApplicationContext> context = get(
this.mockContextSupplier);
assertThat(context.getSourceApplicationContext(ApplicationContext.class))
.isSameAs(this.mockContext);
ApplicationContextAssertProvider<ApplicationContext> context = get(this.mockContextSupplier);
assertThat(context.getSourceApplicationContext(ApplicationContext.class)).isSameAs(this.mockContext);
}
@Test
public void getSourceContextOfTypeWhenContextFailsToStartShouldThrowException() {
ApplicationContextAssertProvider<ApplicationContext> context = get(
this.startupFailureSupplier);
assertThatIllegalStateException().isThrownBy(
() -> context.getSourceApplicationContext(ApplicationContext.class))
ApplicationContextAssertProvider<ApplicationContext> context = get(this.startupFailureSupplier);
assertThatIllegalStateException()
.isThrownBy(() -> context.getSourceApplicationContext(ApplicationContext.class))
.withCause(this.startupFailure).withMessageContaining("failed to start");
}
@Test
public void getStartupFailureWhenContextStartsShouldReturnNull() {
ApplicationContextAssertProvider<ApplicationContext> context = get(
this.mockContextSupplier);
ApplicationContextAssertProvider<ApplicationContext> context = get(this.mockContextSupplier);
assertThat(context.getStartupFailure()).isNull();
}
@Test
public void getStartupFailureWhenContextFailsToStartShouldReturnException() {
ApplicationContextAssertProvider<ApplicationContext> context = get(
this.startupFailureSupplier);
ApplicationContextAssertProvider<ApplicationContext> context = get(this.startupFailureSupplier);
assertThat(context.getStartupFailure()).isEqualTo(this.startupFailure);
}
@Test
public void assertThatWhenContextStartsShouldReturnAssertions() {
ApplicationContextAssertProvider<ApplicationContext> context = get(
this.mockContextSupplier);
ApplicationContextAssertProvider<ApplicationContext> context = get(this.mockContextSupplier);
ApplicationContextAssert<ApplicationContext> contextAssert = assertThat(context);
assertThat(contextAssert.getApplicationContext()).isSameAs(context);
assertThat(contextAssert.getStartupFailure()).isNull();
@@ -177,8 +161,7 @@ public class ApplicationContextAssertProviderTests {
@Test
public void assertThatWhenContextFailsShouldReturnAssertions() {
ApplicationContextAssertProvider<ApplicationContext> context = get(
this.startupFailureSupplier);
ApplicationContextAssertProvider<ApplicationContext> context = get(this.startupFailureSupplier);
ApplicationContextAssert<ApplicationContext> contextAssert = assertThat(context);
assertThat(contextAssert.getApplicationContext()).isSameAs(context);
assertThat(contextAssert.getStartupFailure()).isSameAs(this.startupFailure);
@@ -186,37 +169,28 @@ public class ApplicationContextAssertProviderTests {
@Test
public void toStringWhenContextStartsShouldReturnSimpleString() {
ApplicationContextAssertProvider<ApplicationContext> context = get(
this.mockContextSupplier);
assertThat(context.toString())
.startsWith(
"Started application [ConfigurableApplicationContext.MockitoMock")
.endsWith(
"id = [null], applicationName = [null], beanDefinitionCount = 0]");
ApplicationContextAssertProvider<ApplicationContext> context = get(this.mockContextSupplier);
assertThat(context.toString()).startsWith("Started application [ConfigurableApplicationContext.MockitoMock")
.endsWith("id = [null], applicationName = [null], beanDefinitionCount = 0]");
}
@Test
public void toStringWhenContextFailsToStartShouldReturnSimpleString() {
ApplicationContextAssertProvider<ApplicationContext> context = get(
this.startupFailureSupplier);
ApplicationContextAssertProvider<ApplicationContext> context = get(this.startupFailureSupplier);
assertThat(context.toString()).isEqualTo("Unstarted application context "
+ "org.springframework.context.ApplicationContext"
+ "[startupFailure=java.lang.RuntimeException]");
+ "org.springframework.context.ApplicationContext" + "[startupFailure=java.lang.RuntimeException]");
}
@Test
public void closeShouldCloseContext() {
ApplicationContextAssertProvider<ApplicationContext> context = get(
this.mockContextSupplier);
ApplicationContextAssertProvider<ApplicationContext> context = get(this.mockContextSupplier);
context.close();
verify(this.mockContext).close();
}
private ApplicationContextAssertProvider<ApplicationContext> get(
Supplier<ApplicationContext> contextSupplier) {
return ApplicationContextAssertProvider.get(
TestAssertProviderApplicationContext.class, ApplicationContext.class,
contextSupplier);
private ApplicationContextAssertProvider<ApplicationContext> get(Supplier<ApplicationContext> contextSupplier) {
return ApplicationContextAssertProvider.get(TestAssertProviderApplicationContext.class,
ApplicationContext.class, contextSupplier);
}
private interface TestAssertProviderApplicationContext

View File

@@ -61,15 +61,13 @@ public class ApplicationContextAssertTests {
@Test
public void createWhenApplicationContextIsNullShouldThrowException() {
assertThatIllegalArgumentException()
.isThrownBy(() -> new ApplicationContextAssert<>(null, null))
assertThatIllegalArgumentException().isThrownBy(() -> new ApplicationContextAssert<>(null, null))
.withMessageContaining("ApplicationContext must not be null");
}
@Test
public void createWhenHasApplicationContextShouldSetActual() {
assertThat(getAssert(this.context).getSourceApplicationContext())
.isSameAs(this.context);
assertThat(getAssert(this.context).getSourceApplicationContext()).isSameAs(this.context);
}
@Test
@@ -94,8 +92,7 @@ public class ApplicationContextAssertTests {
public void hasBeanWhenNotStartedShouldFail() {
assertThatExceptionOfType(AssertionError.class)
.isThrownBy(() -> assertThat(getAssert(this.failure)).hasBean("foo"))
.withMessageContaining(String.format(
"but context failed to start:%n java.lang.RuntimeException"));
.withMessageContaining(String.format("but context failed to start:%n java.lang.RuntimeException"));
}
@Test
@@ -106,8 +103,8 @@ public class ApplicationContextAssertTests {
@Test
public void hasSingleBeanWhenHasNoBeansShouldFail() {
assertThatExceptionOfType(AssertionError.class).isThrownBy(
() -> assertThat(getAssert(this.context)).hasSingleBean(Foo.class))
assertThatExceptionOfType(AssertionError.class)
.isThrownBy(() -> assertThat(getAssert(this.context)).hasSingleBean(Foo.class))
.withMessageContaining("to have a single bean of type");
}
@@ -115,26 +112,25 @@ public class ApplicationContextAssertTests {
public void hasSingleBeanWhenHasMultipleShouldFail() {
this.context.registerSingleton("foo", Foo.class);
this.context.registerSingleton("bar", Foo.class);
assertThatExceptionOfType(AssertionError.class).isThrownBy(
() -> assertThat(getAssert(this.context)).hasSingleBean(Foo.class))
assertThatExceptionOfType(AssertionError.class)
.isThrownBy(() -> assertThat(getAssert(this.context)).hasSingleBean(Foo.class))
.withMessageContaining("but found:");
}
@Test
public void hasSingleBeanWhenFailedToStartShouldFail() {
assertThatExceptionOfType(AssertionError.class).isThrownBy(
() -> assertThat(getAssert(this.failure)).hasSingleBean(Foo.class))
assertThatExceptionOfType(AssertionError.class)
.isThrownBy(() -> assertThat(getAssert(this.failure)).hasSingleBean(Foo.class))
.withMessageContaining("to have a single bean of type")
.withMessageContaining(String.format(
"but context failed to start:%n java.lang.RuntimeException"));
.withMessageContaining(String.format("but context failed to start:%n java.lang.RuntimeException"));
}
@Test
public void hasSingleBeanWhenInParentShouldFail() {
this.parent.registerSingleton("foo", Foo.class);
this.context.registerSingleton("bar", Foo.class);
assertThatExceptionOfType(AssertionError.class).isThrownBy(
() -> assertThat(getAssert(this.context)).hasSingleBean(Foo.class))
assertThatExceptionOfType(AssertionError.class)
.isThrownBy(() -> assertThat(getAssert(this.context)).hasSingleBean(Foo.class))
.withMessageContaining("but found:");
}
@@ -153,33 +149,31 @@ public class ApplicationContextAssertTests {
@Test
public void doesNotHaveBeanOfTypeWhenHasBeanOfTypeShouldFail() {
this.context.registerSingleton("foo", Foo.class);
assertThatExceptionOfType(AssertionError.class).isThrownBy(
() -> assertThat(getAssert(this.context)).doesNotHaveBean(Foo.class))
assertThatExceptionOfType(AssertionError.class)
.isThrownBy(() -> assertThat(getAssert(this.context)).doesNotHaveBean(Foo.class))
.withMessageContaining("but found");
}
@Test
public void doesNotHaveBeanOfTypeWhenFailedToStartShouldFail() {
assertThatExceptionOfType(AssertionError.class).isThrownBy(
() -> assertThat(getAssert(this.failure)).doesNotHaveBean(Foo.class))
assertThatExceptionOfType(AssertionError.class)
.isThrownBy(() -> assertThat(getAssert(this.failure)).doesNotHaveBean(Foo.class))
.withMessageContaining("not to have any beans of type")
.withMessageContaining(String.format(
"but context failed to start:%n java.lang.RuntimeException"));
.withMessageContaining(String.format("but context failed to start:%n java.lang.RuntimeException"));
}
@Test
public void doesNotHaveBeanOfTypeWhenInParentShouldFail() {
this.parent.registerSingleton("foo", Foo.class);
assertThatExceptionOfType(AssertionError.class).isThrownBy(
() -> assertThat(getAssert(this.context)).doesNotHaveBean(Foo.class))
assertThatExceptionOfType(AssertionError.class)
.isThrownBy(() -> assertThat(getAssert(this.context)).doesNotHaveBean(Foo.class))
.withMessageContaining("but found");
}
@Test
public void doesNotHaveBeanOfTypeWithLimitedScopeWhenInParentShouldPass() {
this.parent.registerSingleton("foo", Foo.class);
assertThat(getAssert(this.context)).doesNotHaveBean(Foo.class,
Scope.NO_ANCESTORS);
assertThat(getAssert(this.context)).doesNotHaveBean(Foo.class, Scope.NO_ANCESTORS);
}
@Test
@@ -191,26 +185,22 @@ public class ApplicationContextAssertTests {
public void doesNotHaveBeanOfNameWhenHasBeanOfTypeShouldFail() {
this.context.registerSingleton("foo", Foo.class);
assertThatExceptionOfType(AssertionError.class)
.isThrownBy(
() -> assertThat(getAssert(this.context)).doesNotHaveBean("foo"))
.isThrownBy(() -> assertThat(getAssert(this.context)).doesNotHaveBean("foo"))
.withMessageContaining("but found");
}
@Test
public void doesNotHaveBeanOfNameWhenFailedToStartShouldFail() {
assertThatExceptionOfType(AssertionError.class)
.isThrownBy(
() -> assertThat(getAssert(this.failure)).doesNotHaveBean("foo"))
.withMessageContaining("not to have any beans of name")
.withMessageContaining("failed to start");
.isThrownBy(() -> assertThat(getAssert(this.failure)).doesNotHaveBean("foo"))
.withMessageContaining("not to have any beans of name").withMessageContaining("failed to start");
}
@Test
public void getBeanNamesWhenHasNamesShouldReturnNamesAssert() {
this.context.registerSingleton("foo", Foo.class);
this.context.registerSingleton("bar", Foo.class);
assertThat(getAssert(this.context)).getBeanNames(Foo.class).containsOnly("foo",
"bar");
assertThat(getAssert(this.context)).getBeanNames(Foo.class).containsOnly("foo", "bar");
}
@Test
@@ -221,11 +211,9 @@ public class ApplicationContextAssertTests {
@Test
public void getBeanNamesWhenFailedToStartShouldFail() {
assertThatExceptionOfType(AssertionError.class)
.isThrownBy(
() -> assertThat(getAssert(this.failure)).doesNotHaveBean("foo"))
.isThrownBy(() -> assertThat(getAssert(this.failure)).doesNotHaveBean("foo"))
.withMessageContaining("not to have any beans of name")
.withMessageContaining(String.format(
"but context failed to start:%n java.lang.RuntimeException"));
.withMessageContaining(String.format("but context failed to start:%n java.lang.RuntimeException"));
}
@Test
@@ -250,8 +238,7 @@ public class ApplicationContextAssertTests {
@Test
public void getBeanOfTypeWhenHasPrimaryBeanShouldReturnPrimary() {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(
PrimaryFooConfig.class);
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(PrimaryFooConfig.class);
assertThat(getAssert(context)).getBean(Foo.class).isInstanceOf(Bar.class);
context.close();
}
@@ -261,8 +248,7 @@ public class ApplicationContextAssertTests {
assertThatExceptionOfType(AssertionError.class)
.isThrownBy(() -> assertThat(getAssert(this.failure)).getBean(Foo.class))
.withMessageContaining("to contain bean of type")
.withMessageContaining(String.format(
"but context failed to start:%n java.lang.RuntimeException"));
.withMessageContaining(String.format("but context failed to start:%n java.lang.RuntimeException"));
}
@Test
@@ -274,8 +260,7 @@ public class ApplicationContextAssertTests {
@Test
public void getBeanOfTypeWhenInParentWithLimitedScopeShouldReturnNullAssert() {
this.parent.registerSingleton("foo", Foo.class);
assertThat(getAssert(this.context)).getBean(Foo.class, Scope.NO_ANCESTORS)
.isNull();
assertThat(getAssert(this.context)).getBean(Foo.class, Scope.NO_ANCESTORS).isNull();
}
@Test
@@ -291,8 +276,7 @@ public class ApplicationContextAssertTests {
public void getBeanOfTypeWithLimitedScopeWhenHasMultipleBeansIncludingParentShouldReturnBeanAssert() {
this.parent.registerSingleton("foo", Foo.class);
this.context.registerSingleton("bar", Foo.class);
assertThat(getAssert(this.context)).getBean(Foo.class, Scope.NO_ANCESTORS)
.isNotNull();
assertThat(getAssert(this.context)).getBean(Foo.class, Scope.NO_ANCESTORS).isNotNull();
}
@Test
@@ -311,8 +295,7 @@ public class ApplicationContextAssertTests {
assertThatExceptionOfType(AssertionError.class)
.isThrownBy(() -> assertThat(getAssert(this.failure)).getBean("foo"))
.withMessageContaining("to contain a bean of name")
.withMessageContaining(String.format(
"but context failed to start:%n java.lang.RuntimeException"));
.withMessageContaining(String.format("but context failed to start:%n java.lang.RuntimeException"));
}
@Test
@@ -329,27 +312,24 @@ public class ApplicationContextAssertTests {
@Test
public void getBeanOfNameAndTypeWhenHasNoBeanOfNameButDifferentTypeShouldFail() {
this.context.registerSingleton("foo", Foo.class);
assertThatExceptionOfType(AssertionError.class).isThrownBy(
() -> assertThat(getAssert(this.context)).getBean("foo", String.class))
assertThatExceptionOfType(AssertionError.class)
.isThrownBy(() -> assertThat(getAssert(this.context)).getBean("foo", String.class))
.withMessageContaining("of type");
}
@Test
public void getBeanOfNameAndTypeWhenFailedToStartShouldFail() {
assertThatExceptionOfType(AssertionError.class)
.isThrownBy(() -> assertThat(getAssert(this.failure)).getBean("foo",
Foo.class))
.isThrownBy(() -> assertThat(getAssert(this.failure)).getBean("foo", Foo.class))
.withMessageContaining("to contain a bean of name")
.withMessageContaining(String.format(
"but context failed to start:%n java.lang.RuntimeException"));
.withMessageContaining(String.format("but context failed to start:%n java.lang.RuntimeException"));
}
@Test
public void getBeansWhenHasBeansShouldReturnMapAssert() {
this.context.registerSingleton("foo", Foo.class);
this.context.registerSingleton("bar", Foo.class);
assertThat(getAssert(this.context)).getBeans(Foo.class).hasSize(2)
.containsKeys("foo", "bar");
assertThat(getAssert(this.context)).getBeans(Foo.class).hasSize(2).containsKeys("foo", "bar");
}
@Test
@@ -362,24 +342,21 @@ public class ApplicationContextAssertTests {
assertThatExceptionOfType(AssertionError.class)
.isThrownBy(() -> assertThat(getAssert(this.failure)).getBeans(Foo.class))
.withMessageContaining("to get beans of type")
.withMessageContaining(String.format(
"but context failed to start:%n java.lang.RuntimeException"));
.withMessageContaining(String.format("but context failed to start:%n java.lang.RuntimeException"));
}
@Test
public void getBeansShouldIncludeBeansFromParentScope() {
this.parent.registerSingleton("foo", Foo.class);
this.context.registerSingleton("bar", Foo.class);
assertThat(getAssert(this.context)).getBeans(Foo.class).hasSize(2)
.containsKeys("foo", "bar");
assertThat(getAssert(this.context)).getBeans(Foo.class).hasSize(2).containsKeys("foo", "bar");
}
@Test
public void getBeansWithLimitedScopeShouldNotIncludeBeansFromParentScope() {
this.parent.registerSingleton("foo", Foo.class);
this.context.registerSingleton("bar", Foo.class);
assertThat(getAssert(this.context)).getBeans(Foo.class, Scope.NO_ANCESTORS)
.hasSize(1).containsKeys("bar");
assertThat(getAssert(this.context)).getBeans(Foo.class, Scope.NO_ANCESTORS).hasSize(1).containsKeys("bar");
}
@Test
@@ -411,8 +388,7 @@ public class ApplicationContextAssertTests {
assertThatExceptionOfType(AssertionError.class)
.isThrownBy(() -> assertThat(getAssert(this.failure)).hasNotFailed())
.withMessageContaining("to have not failed")
.withMessageContaining(String.format(
"but context failed to start:%n java.lang.RuntimeException"));
.withMessageContaining(String.format("but context failed to start:%n java.lang.RuntimeException"));
}
@Test
@@ -420,8 +396,7 @@ public class ApplicationContextAssertTests {
assertThat(getAssert(this.context)).hasNotFailed();
}
private AssertableApplicationContext getAssert(
ConfigurableApplicationContext applicationContext) {
private AssertableApplicationContext getAssert(ConfigurableApplicationContext applicationContext) {
return AssertableApplicationContext.get(() -> applicationContext);
}

View File

@@ -39,12 +39,10 @@ public class SpringBootTestContextBootstrapperTests {
@Test
public void springBootTestWithANonMockWebEnvironmentAndWebAppConfigurationFailsFast() {
assertThatIllegalStateException()
.isThrownBy(() -> buildTestContext(
SpringBootTestNonMockWebEnvironmentAndWebAppConfiguration.class))
.isThrownBy(() -> buildTestContext(SpringBootTestNonMockWebEnvironmentAndWebAppConfiguration.class))
.withMessageContaining("@WebAppConfiguration should only be used with "
+ "@SpringBootTest when @SpringBootTest is configured with a mock web "
+ "environment. Please remove @WebAppConfiguration or reconfigure "
+ "@SpringBootTest.");
+ "environment. Please remove @WebAppConfiguration or reconfigure " + "@SpringBootTest.");
}
@Test
@@ -58,10 +56,8 @@ public class SpringBootTestContextBootstrapperTests {
BootstrapContext bootstrapContext = mock(BootstrapContext.class);
bootstrapper.setBootstrapContext(bootstrapContext);
given((Class) bootstrapContext.getTestClass()).willReturn(testClass);
CacheAwareContextLoaderDelegate contextLoaderDelegate = mock(
CacheAwareContextLoaderDelegate.class);
given(bootstrapContext.getCacheAwareContextLoaderDelegate())
.willReturn(contextLoaderDelegate);
CacheAwareContextLoaderDelegate contextLoaderDelegate = mock(CacheAwareContextLoaderDelegate.class);
given(bootstrapContext.getCacheAwareContextLoaderDelegate()).willReturn(contextLoaderDelegate);
bootstrapper.buildTestContext();
}

View File

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

@@ -41,68 +41,57 @@ public class TestTypeExcludeFilterTests {
@Test
public void matchesJUnit4TestClass() throws Exception {
assertThat(this.filter.match(getMetadataReader(TestTypeExcludeFilterTests.class),
this.metadataReaderFactory)).isTrue();
assertThat(this.filter.match(getMetadataReader(TestTypeExcludeFilterTests.class), this.metadataReaderFactory))
.isTrue();
}
@Test
public void matchesJUnitJupiterTestClass() throws Exception {
assertThat(this.filter.match(getMetadataReader(JupiterTestExample.class),
this.metadataReaderFactory)).isTrue();
assertThat(this.filter.match(getMetadataReader(JupiterTestExample.class), this.metadataReaderFactory)).isTrue();
}
@Test
public void matchesJUnitJupiterRepeatedTestClass() throws Exception {
assertThat(this.filter.match(getMetadataReader(JupiterRepeatedTestExample.class),
this.metadataReaderFactory)).isTrue();
assertThat(this.filter.match(getMetadataReader(JupiterRepeatedTestExample.class), this.metadataReaderFactory))
.isTrue();
}
@Test
public void matchesJUnitJupiterTestFactoryClass() throws Exception {
assertThat(this.filter.match(getMetadataReader(JupiterTestFactoryExample.class),
this.metadataReaderFactory)).isTrue();
assertThat(this.filter.match(getMetadataReader(JupiterTestFactoryExample.class), this.metadataReaderFactory))
.isTrue();
}
@Test
public void matchesNestedConfiguration() throws Exception {
assertThat(this.filter.match(getMetadataReader(NestedConfig.class),
assertThat(this.filter.match(getMetadataReader(NestedConfig.class), this.metadataReaderFactory)).isTrue();
}
@Test
public void matchesNestedConfigurationClassWithoutTestMethodsIfItHasRunWith() throws Exception {
assertThat(this.filter.match(getMetadataReader(AbstractTestWithConfigAndRunWith.Config.class),
this.metadataReaderFactory)).isTrue();
}
@Test
public void matchesNestedConfigurationClassWithoutTestMethodsIfItHasRunWith()
throws Exception {
assertThat(this.filter.match(
getMetadataReader(AbstractTestWithConfigAndRunWith.Config.class),
this.metadataReaderFactory)).isTrue();
}
@Test
public void matchesNestedConfigurationClassWithoutTestMethodsIfItHasExtendWith()
throws Exception {
assertThat(this.filter.match(
getMetadataReader(
AbstractJupiterTestWithConfigAndExtendWith.Config.class),
public void matchesNestedConfigurationClassWithoutTestMethodsIfItHasExtendWith() throws Exception {
assertThat(this.filter.match(getMetadataReader(AbstractJupiterTestWithConfigAndExtendWith.Config.class),
this.metadataReaderFactory)).isTrue();
}
@Test
public void matchesTestConfiguration() throws Exception {
assertThat(this.filter.match(getMetadataReader(SampleTestConfig.class),
this.metadataReaderFactory)).isTrue();
assertThat(this.filter.match(getMetadataReader(SampleTestConfig.class), this.metadataReaderFactory)).isTrue();
}
@Test
public void doesNotMatchRegularConfiguration() throws Exception {
assertThat(this.filter.match(getMetadataReader(SampleConfig.class),
this.metadataReaderFactory)).isFalse();
assertThat(this.filter.match(getMetadataReader(SampleConfig.class), this.metadataReaderFactory)).isFalse();
}
@Test
public void matchesNestedConfigurationClassWithoutTestNgAnnotation()
throws Exception {
assertThat(this.filter.match(
getMetadataReader(AbstractTestNgTestWithConfig.Config.class),
public void matchesNestedConfigurationClassWithoutTestNgAnnotation() throws Exception {
assertThat(this.filter.match(getMetadataReader(AbstractTestNgTestWithConfig.Config.class),
this.metadataReaderFactory)).isTrue();
}

View File

@@ -64,8 +64,7 @@ public abstract class AbstractApplicationContextRunnerTests<T extends AbstractAp
String key = "test." + UUID.randomUUID();
assertThat(System.getProperties().containsKey(key)).isFalse();
get().withSystemProperties(key + "=value")
.run((context) -> assertThat(System.getProperties()).containsEntry(key,
"value"));
.run((context) -> assertThat(System.getProperties()).containsEntry(key, "value"));
assertThat(System.getProperties().containsKey(key)).isFalse();
}
@@ -73,8 +72,7 @@ public abstract class AbstractApplicationContextRunnerTests<T extends AbstractAp
public void runWithSystemPropertiesWhenContextFailsShouldRemoveProperties() {
String key = "test." + UUID.randomUUID();
assertThat(System.getProperties().containsKey(key)).isFalse();
get().withSystemProperties(key + "=value")
.withUserConfiguration(FailingConfig.class)
get().withSystemProperties(key + "=value").withUserConfiguration(FailingConfig.class)
.run((context) -> assertThat(context).hasFailed());
assertThat(System.getProperties().containsKey(key)).isFalse();
}
@@ -86,8 +84,7 @@ public abstract class AbstractApplicationContextRunnerTests<T extends AbstractAp
try {
assertThat(System.getProperties().getProperty(key)).isEqualTo("value");
get().withSystemProperties(key + "=newValue")
.run((context) -> assertThat(System.getProperties())
.containsEntry(key, "newValue"));
.run((context) -> assertThat(System.getProperties()).containsEntry(key, "newValue"));
assertThat(System.getProperties().getProperty(key)).isEqualTo("value");
}
finally {
@@ -102,8 +99,7 @@ public abstract class AbstractApplicationContextRunnerTests<T extends AbstractAp
try {
assertThat(System.getProperties().getProperty(key)).isEqualTo("value");
get().withSystemProperties(key + "=")
.run((context) -> assertThat(System.getProperties())
.doesNotContainKey(key));
.run((context) -> assertThat(System.getProperties()).doesNotContainKey(key));
assertThat(System.getProperties().getProperty(key)).isEqualTo("value");
}
finally {
@@ -113,39 +109,34 @@ public abstract class AbstractApplicationContextRunnerTests<T extends AbstractAp
@Test
public void runWithMultiplePropertyValuesShouldAllAllValues() {
get().withPropertyValues("test.foo=1").withPropertyValues("test.bar=2")
.run((context) -> {
Environment environment = context.getEnvironment();
assertThat(environment.getProperty("test.foo")).isEqualTo("1");
assertThat(environment.getProperty("test.bar")).isEqualTo("2");
});
get().withPropertyValues("test.foo=1").withPropertyValues("test.bar=2").run((context) -> {
Environment environment = context.getEnvironment();
assertThat(environment.getProperty("test.foo")).isEqualTo("1");
assertThat(environment.getProperty("test.bar")).isEqualTo("2");
});
}
@Test
public void runWithPropertyValuesWhenHasExistingShouldReplaceValue() {
get().withPropertyValues("test.foo=1").withPropertyValues("test.foo=2")
.run((context) -> {
Environment environment = context.getEnvironment();
assertThat(environment.getProperty("test.foo")).isEqualTo("2");
});
get().withPropertyValues("test.foo=1").withPropertyValues("test.foo=2").run((context) -> {
Environment environment = context.getEnvironment();
assertThat(environment.getProperty("test.foo")).isEqualTo("2");
});
}
@Test
public void runWithConfigurationsShouldRegisterConfigurations() {
get().withUserConfiguration(FooConfig.class)
.run((context) -> assertThat(context).hasBean("foo"));
get().withUserConfiguration(FooConfig.class).run((context) -> assertThat(context).hasBean("foo"));
}
@Test
public void runWithUserNamedBeanShouldRegisterBean() {
get().withBean("foo", String.class, () -> "foo")
.run((context) -> assertThat(context).hasBean("foo"));
get().withBean("foo", String.class, () -> "foo").run((context) -> assertThat(context).hasBean("foo"));
}
@Test
public void runWithUserBeanShouldRegisterBeanWithDefaultName() {
get().withBean(String.class, () -> "foo")
.run((context) -> assertThat(context).hasBean("string"));
get().withBean(String.class, () -> "foo").run((context) -> assertThat(context).hasBean("string"));
}
@Test
@@ -159,8 +150,8 @@ public abstract class AbstractApplicationContextRunnerTests<T extends AbstractAp
@Test
public void runWithConfigurationsAndUserBeanShouldRegisterUserBeanLast() {
get().withUserConfiguration(FooConfig.class)
.withBean("foo", String.class, () -> "overridden").run((context) -> {
get().withUserConfiguration(FooConfig.class).withBean("foo", String.class, () -> "overridden")
.run((context) -> {
assertThat(context).hasBean("foo");
assertThat(context.getBean("foo")).isEqualTo("overridden");
});
@@ -168,37 +159,32 @@ public abstract class AbstractApplicationContextRunnerTests<T extends AbstractAp
@Test
public void runWithMultipleConfigurationsShouldRegisterAllConfigurations() {
get().withUserConfiguration(FooConfig.class)
.withConfiguration(UserConfigurations.of(BarConfig.class))
get().withUserConfiguration(FooConfig.class).withConfiguration(UserConfigurations.of(BarConfig.class))
.run((context) -> assertThat(context).hasBean("foo").hasBean("bar"));
}
@Test
public void runWithFailedContextShouldReturnFailedAssertableContext() {
get().withUserConfiguration(FailingConfig.class)
.run((context) -> assertThat(context).hasFailed());
get().withUserConfiguration(FailingConfig.class).run((context) -> assertThat(context).hasFailed());
}
@Test
public void runWithClassLoaderShouldSetClassLoaderOnContext() {
get().withClassLoader(new FilteredClassLoader(Gson.class.getPackage().getName()))
.run((context) -> assertThatExceptionOfType(ClassNotFoundException.class)
.isThrownBy(() -> ClassUtils.forName(Gson.class.getName(),
context.getClassLoader())));
.isThrownBy(() -> ClassUtils.forName(Gson.class.getName(), context.getClassLoader())));
}
@Test
public void runWithClassLoaderShouldSetClassLoaderOnConditionContext() {
get().withClassLoader(new FilteredClassLoader(Gson.class.getPackage().getName()))
.withUserConfiguration(ConditionalConfig.class)
.run((context) -> assertThat(context)
.hasSingleBean(ConditionalConfig.class));
.run((context) -> assertThat(context).hasSingleBean(ConditionalConfig.class));
}
@Test
public void thrownRuleWorksWithCheckedException() {
get().run((context) -> assertThatIOException()
.isThrownBy(() -> throwCheckedException("Expected message"))
get().run((context) -> assertThatIOException().isThrownBy(() -> throwCheckedException("Expected message"))
.withMessageContaining("Expected message"));
}

View File

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

@@ -55,8 +55,7 @@ public abstract class AbstractJsonMarshalTesterTests {
private static final ExampleObject OBJECT = createExampleObject("Spring", 123);
private static final ResolvableType TYPE = ResolvableType
.forClass(ExampleObject.class);
private static final ResolvableType TYPE = ResolvableType.forClass(ExampleObject.class);
@Test
public void writeShouldReturnJsonContent() throws Exception {
@@ -91,15 +90,14 @@ public abstract class AbstractJsonMarshalTesterTests {
@Test
public void createWhenResourceLoadClassIsNullShouldThrowException() {
assertThatIllegalArgumentException().isThrownBy(
() -> createTester(null, ResolvableType.forClass(ExampleObject.class)))
assertThatIllegalArgumentException()
.isThrownBy(() -> createTester(null, ResolvableType.forClass(ExampleObject.class)))
.withMessageContaining("ResourceLoadClass must not be null");
}
@Test
public void createWhenTypeIsNullShouldThrowException() {
assertThatIllegalArgumentException()
.isThrownBy(() -> createTester(getClass(), null))
assertThatIllegalArgumentException().isThrownBy(() -> createTester(getClass(), null))
.withMessageContaining("Type must not be null");
}
@@ -182,8 +180,7 @@ public abstract class AbstractJsonMarshalTesterTests {
return createTester(AbstractJsonMarshalTesterTests.class, type);
}
protected abstract AbstractJsonMarshalTester<Object> createTester(
Class<?> resourceLoadClass, ResolvableType type);
protected abstract AbstractJsonMarshalTester<Object> createTester(Class<?> resourceLoadClass, ResolvableType type);
/**
* Access to field backed by {@link ResolvableType}.

View File

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

@@ -55,16 +55,14 @@ public class GsonTesterIntegrationTests {
@Test
public void typicalTest() throws Exception {
String example = JSON;
assertThat(this.simpleJson.parse(example).getObject().getName())
.isEqualTo("Spring");
assertThat(this.simpleJson.parse(example).getObject().getName()).isEqualTo("Spring");
}
@Test
public void typicalListTest() throws Exception {
String example = "[" + JSON + "]";
assertThat(this.listJson.parse(example)).asList().hasSize(1);
assertThat(this.listJson.parse(example).getObject().get(0).getName())
.isEqualTo("Spring");
assertThat(this.listJson.parse(example).getObject().get(0).getName()).isEqualTo("Spring");
}
@Test
@@ -72,15 +70,13 @@ public class GsonTesterIntegrationTests {
Map<String, Integer> map = new LinkedHashMap<>();
map.put("a", 1);
map.put("b", 2);
assertThat(this.mapJson.write(map)).extractingJsonPathNumberValue("@.a")
.isEqualTo(1);
assertThat(this.mapJson.write(map)).extractingJsonPathNumberValue("@.a").isEqualTo(1);
}
@Test
public void stringLiteral() throws Exception {
String stringWithSpecialCharacters = "myString";
assertThat(this.stringJson.write(stringWithSpecialCharacters))
.extractingJsonPathStringValue("@")
assertThat(this.stringJson.write(stringWithSpecialCharacters)).extractingJsonPathStringValue("@")
.isEqualTo(stringWithSpecialCharacters);
}

View File

@@ -36,15 +36,14 @@ public class GsonTesterTests extends AbstractJsonMarshalTesterTests {
@Test
public void initFieldsWhenTestIsNullShouldThrowException() {
assertThatIllegalArgumentException()
.isThrownBy(() -> GsonTester.initFields(null, new GsonBuilder().create()))
assertThatIllegalArgumentException().isThrownBy(() -> GsonTester.initFields(null, new GsonBuilder().create()))
.withMessageContaining("TestInstance must not be null");
}
@Test
public void initFieldsWhenMarshallerIsNullShouldThrowException() {
assertThatIllegalArgumentException().isThrownBy(
() -> GsonTester.initFields(new InitFieldsTestClass(), (Gson) null))
assertThatIllegalArgumentException()
.isThrownBy(() -> GsonTester.initFields(new InitFieldsTestClass(), (Gson) null))
.withMessageContaining("Marshaller must not be null");
}
@@ -61,8 +60,7 @@ public class GsonTesterTests extends AbstractJsonMarshalTesterTests {
}
@Override
protected AbstractJsonMarshalTester<Object> createTester(Class<?> resourceLoadClass,
ResolvableType type) {
protected AbstractJsonMarshalTester<Object> createTester(Class<?> resourceLoadClass, ResolvableType type) {
return new GsonTester<>(resourceLoadClass, type, new GsonBuilder().create());
}
@@ -70,9 +68,8 @@ public class GsonTesterTests extends AbstractJsonMarshalTesterTests {
public GsonTester<ExampleObject> base;
public GsonTester<ExampleObject> baseSet = new GsonTester<>(
InitFieldsBaseClass.class, ResolvableType.forClass(ExampleObject.class),
new GsonBuilder().create());
public GsonTester<ExampleObject> baseSet = new GsonTester<>(InitFieldsBaseClass.class,
ResolvableType.forClass(ExampleObject.class), new GsonBuilder().create());
}
@@ -80,9 +77,8 @@ public class GsonTesterTests extends AbstractJsonMarshalTesterTests {
public GsonTester<List<ExampleObject>> test;
public GsonTester<ExampleObject> testSet = new GsonTester<>(
InitFieldsBaseClass.class, ResolvableType.forClass(ExampleObject.class),
new GsonBuilder().create());
public GsonTester<ExampleObject> testSet = new GsonTester<>(InitFieldsBaseClass.class,
ResolvableType.forClass(ExampleObject.class), new GsonBuilder().create());
}

View File

@@ -63,16 +63,14 @@ public class JacksonTesterIntegrationTests {
@Test
public void typicalTest() throws Exception {
String example = JSON;
assertThat(this.simpleJson.parse(example).getObject().getName())
.isEqualTo("Spring");
assertThat(this.simpleJson.parse(example).getObject().getName()).isEqualTo("Spring");
}
@Test
public void typicalListTest() throws Exception {
String example = "[" + JSON + "]";
assertThat(this.listJson.parse(example)).asList().hasSize(1);
assertThat(this.listJson.parse(example).getObject().get(0).getName())
.isEqualTo("Spring");
assertThat(this.listJson.parse(example).getObject().get(0).getName()).isEqualTo("Spring");
}
@Test
@@ -80,15 +78,13 @@ public class JacksonTesterIntegrationTests {
Map<String, Integer> map = new LinkedHashMap<>();
map.put("a", 1);
map.put("b", 2);
assertThat(this.mapJson.write(map)).extractingJsonPathNumberValue("@.a")
.isEqualTo(1);
assertThat(this.mapJson.write(map)).extractingJsonPathNumberValue("@.a").isEqualTo(1);
}
@Test
public void stringLiteral() throws Exception {
String stringWithSpecialCharacters = "myString";
assertThat(this.stringJson.write(stringWithSpecialCharacters))
.extractingJsonPathStringValue("@")
assertThat(this.stringJson.write(stringWithSpecialCharacters)).extractingJsonPathStringValue("@")
.isEqualTo(stringWithSpecialCharacters);
}
@@ -101,8 +97,7 @@ public class JacksonTesterIntegrationTests {
// configures json-path to use Jackson for evaluating the path expressions and
// restores the symmetry. See gh-15727
String stringWithSpecialCharacters = "\u0006\u007F";
assertThat(this.stringJson.write(stringWithSpecialCharacters))
.extractingJsonPathStringValue("@")
assertThat(this.stringJson.write(stringWithSpecialCharacters)).extractingJsonPathStringValue("@")
.isEqualTo(stringWithSpecialCharacters);
}
@@ -112,8 +107,8 @@ public class JacksonTesterIntegrationTests {
ExampleObjectWithView object = new ExampleObjectWithView();
object.setName("Spring");
object.setAge(123);
JsonContent<ExampleObjectWithView> content = this.jsonWithView
.forView(ExampleObjectWithView.TestView.class).write(object);
JsonContent<ExampleObjectWithView> content = this.jsonWithView.forView(ExampleObjectWithView.TestView.class)
.write(object);
assertThat(content).extractingJsonPathStringValue("@.name").isEqualTo("Spring");
assertThat(content).doesNotHaveJsonPathValue("age");
}
@@ -122,8 +117,8 @@ public class JacksonTesterIntegrationTests {
public void readWithResourceAndView() throws Exception {
this.objectMapper.disable(MapperFeature.DEFAULT_VIEW_INCLUSION);
ByteArrayResource resource = new ByteArrayResource(JSON.getBytes());
ObjectContent<ExampleObjectWithView> content = this.jsonWithView
.forView(ExampleObjectWithView.TestView.class).read(resource);
ObjectContent<ExampleObjectWithView> content = this.jsonWithView.forView(ExampleObjectWithView.TestView.class)
.read(resource);
assertThat(content.getObject().getName()).isEqualTo("Spring");
assertThat(content.getObject().getAge()).isEqualTo(0);
}
@@ -132,8 +127,8 @@ public class JacksonTesterIntegrationTests {
public void readWithReaderAndView() throws Exception {
this.objectMapper.disable(MapperFeature.DEFAULT_VIEW_INCLUSION);
Reader reader = new StringReader(JSON);
ObjectContent<ExampleObjectWithView> content = this.jsonWithView
.forView(ExampleObjectWithView.TestView.class).read(reader);
ObjectContent<ExampleObjectWithView> content = this.jsonWithView.forView(ExampleObjectWithView.TestView.class)
.read(reader);
assertThat(content.getObject().getName()).isEqualTo("Spring");
assertThat(content.getObject().getAge()).isEqualTo(0);
}

View File

@@ -35,16 +35,14 @@ public class JacksonTesterTests extends AbstractJsonMarshalTesterTests {
@Test
public void initFieldsWhenTestIsNullShouldThrowException() {
assertThatIllegalArgumentException()
.isThrownBy(() -> JacksonTester.initFields(null, new ObjectMapper()))
assertThatIllegalArgumentException().isThrownBy(() -> JacksonTester.initFields(null, new ObjectMapper()))
.withMessageContaining("TestInstance must not be null");
}
@Test
public void initFieldsWhenMarshallerIsNullShouldThrowException() {
assertThatIllegalArgumentException()
.isThrownBy(() -> JacksonTester.initFields(new InitFieldsTestClass(),
(ObjectMapper) null))
.isThrownBy(() -> JacksonTester.initFields(new InitFieldsTestClass(), (ObjectMapper) null))
.withMessageContaining("Marshaller must not be null");
}
@@ -61,8 +59,7 @@ public class JacksonTesterTests extends AbstractJsonMarshalTesterTests {
}
@Override
protected AbstractJsonMarshalTester<Object> createTester(Class<?> resourceLoadClass,
ResolvableType type) {
protected AbstractJsonMarshalTester<Object> createTester(Class<?> resourceLoadClass, ResolvableType type) {
return new JacksonTester<>(resourceLoadClass, type, new ObjectMapper());
}
@@ -70,9 +67,8 @@ public class JacksonTesterTests extends AbstractJsonMarshalTesterTests {
public JacksonTester<ExampleObject> base;
public JacksonTester<ExampleObject> baseSet = new JacksonTester<>(
InitFieldsBaseClass.class, ResolvableType.forClass(ExampleObject.class),
new ObjectMapper());
public JacksonTester<ExampleObject> baseSet = new JacksonTester<>(InitFieldsBaseClass.class,
ResolvableType.forClass(ExampleObject.class), new ObjectMapper());
}
@@ -80,9 +76,8 @@ public class JacksonTesterTests extends AbstractJsonMarshalTesterTests {
public JacksonTester<List<ExampleObject>> test;
public JacksonTester<ExampleObject> testSet = new JacksonTester<>(
InitFieldsBaseClass.class, ResolvableType.forClass(ExampleObject.class),
new ObjectMapper());
public JacksonTester<ExampleObject> testSet = new JacksonTester<>(InitFieldsBaseClass.class,
ResolvableType.forClass(ExampleObject.class), new ObjectMapper());
}

View File

@@ -33,29 +33,27 @@ public class JsonContentTests {
private static final String JSON = "{\"name\":\"spring\", \"age\":100}";
private static final ResolvableType TYPE = ResolvableType
.forClass(ExampleObject.class);
private static final ResolvableType TYPE = ResolvableType.forClass(ExampleObject.class);
@Test
public void createWhenResourceLoadClassIsNullShouldThrowException() {
assertThatIllegalArgumentException()
.isThrownBy(() -> new JsonContent<ExampleObject>(null, TYPE, JSON,
Configuration.defaultConfiguration()))
.isThrownBy(
() -> new JsonContent<ExampleObject>(null, TYPE, JSON, Configuration.defaultConfiguration()))
.withMessageContaining("ResourceLoadClass must not be null");
}
@Test
public void createWhenJsonIsNullShouldThrowException() {
assertThatIllegalArgumentException()
.isThrownBy(() -> new JsonContent<ExampleObject>(getClass(), TYPE, null,
Configuration.defaultConfiguration()))
assertThatIllegalArgumentException().isThrownBy(
() -> new JsonContent<ExampleObject>(getClass(), TYPE, null, Configuration.defaultConfiguration()))
.withMessageContaining("JSON must not be null");
}
@Test
public void createWhenConfigurationIsNullShouldThrowException() {
assertThatIllegalArgumentException().isThrownBy(
() -> new JsonContent<ExampleObject>(getClass(), TYPE, JSON, null))
assertThatIllegalArgumentException()
.isThrownBy(() -> new JsonContent<ExampleObject>(getClass(), TYPE, JSON, null))
.withMessageContaining("Configuration must not be null");
}
@@ -86,8 +84,7 @@ public class JsonContentTests {
public void toStringWhenHasTypeShouldReturnString() {
JsonContent<ExampleObject> content = new JsonContent<>(getClass(), TYPE, JSON,
Configuration.defaultConfiguration());
assertThat(content.toString())
.isEqualTo("JsonContent " + JSON + " created from " + TYPE);
assertThat(content.toString()).isEqualTo("JsonContent " + JSON + " created from " + TYPE);
}
@Test

View File

@@ -37,15 +37,14 @@ public class JsonbTesterTests extends AbstractJsonMarshalTesterTests {
@Test
public void initFieldsWhenTestIsNullShouldThrowException() {
assertThatIllegalArgumentException()
.isThrownBy(() -> JsonbTester.initFields(null, JsonbBuilder.create()))
assertThatIllegalArgumentException().isThrownBy(() -> JsonbTester.initFields(null, JsonbBuilder.create()))
.withMessageContaining("TestInstance must not be null");
}
@Test
public void initFieldsWhenMarshallerIsNullShouldThrowException() {
assertThatIllegalArgumentException().isThrownBy(
() -> JsonbTester.initFields(new InitFieldsTestClass(), (Jsonb) null))
assertThatIllegalArgumentException()
.isThrownBy(() -> JsonbTester.initFields(new InitFieldsTestClass(), (Jsonb) null))
.withMessageContaining("Marshaller must not be null");
}
@@ -62,8 +61,7 @@ public class JsonbTesterTests extends AbstractJsonMarshalTesterTests {
}
@Override
protected AbstractJsonMarshalTester<Object> createTester(Class<?> resourceLoadClass,
ResolvableType type) {
protected AbstractJsonMarshalTester<Object> createTester(Class<?> resourceLoadClass, ResolvableType type) {
return new JsonbTester<>(resourceLoadClass, type, JsonbBuilder.create());
}
@@ -71,9 +69,8 @@ public class JsonbTesterTests extends AbstractJsonMarshalTesterTests {
public JsonbTester<ExampleObject> base;
public JsonbTester<ExampleObject> baseSet = new JsonbTester<>(
InitFieldsBaseClass.class, ResolvableType.forClass(ExampleObject.class),
JsonbBuilder.create());
public JsonbTester<ExampleObject> baseSet = new JsonbTester<>(InitFieldsBaseClass.class,
ResolvableType.forClass(ExampleObject.class), JsonbBuilder.create());
}
@@ -81,9 +78,8 @@ public class JsonbTesterTests extends AbstractJsonMarshalTesterTests {
public JsonbTester<List<ExampleObject>> test;
public JsonbTester<ExampleObject> testSet = new JsonbTester<>(
InitFieldsBaseClass.class, ResolvableType.forClass(ExampleObject.class),
JsonbBuilder.create());
public JsonbTester<ExampleObject> testSet = new JsonbTester<>(InitFieldsBaseClass.class,
ResolvableType.forClass(ExampleObject.class), JsonbBuilder.create());
}

View File

@@ -60,8 +60,7 @@ public class ObjectContentAssertTests {
@Test
public void asArrayForNonArrayShouldFail() {
assertThatExceptionOfType(AssertionError.class)
.isThrownBy(() -> assertThat(forObject(SOURCE)).asArray());
assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> assertThat(forObject(SOURCE)).asArray());
}
@Test
@@ -72,8 +71,7 @@ public class ObjectContentAssertTests {
@Test
public void asMapForNonMapShouldFail() {
assertThatExceptionOfType(AssertionError.class)
.isThrownBy(() -> assertThat(forObject(SOURCE)).asMap());
assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> assertThat(forObject(SOURCE)).asMap());
}
private AssertProvider<ObjectContentAssert<Object>> forObject(Object source) {

View File

@@ -32,13 +32,11 @@ public class ObjectContentTests {
private static final ExampleObject OBJECT = new ExampleObject();
private static final ResolvableType TYPE = ResolvableType
.forClass(ExampleObject.class);
private static final ResolvableType TYPE = ResolvableType.forClass(ExampleObject.class);
@Test
public void createWhenObjectIsNullShouldThrowException() {
assertThatIllegalArgumentException()
.isThrownBy(() -> new ObjectContent<ExampleObject>(TYPE, null))
assertThatIllegalArgumentException().isThrownBy(() -> new ObjectContent<ExampleObject>(TYPE, null))
.withMessageContaining("Object must not be null");
}
@@ -63,8 +61,7 @@ public class ObjectContentTests {
@Test
public void toStringWhenHasTypeShouldReturnString() {
ObjectContent<ExampleObject> content = new ObjectContent<>(TYPE, OBJECT);
assertThat(content.toString())
.isEqualTo("ObjectContent " + OBJECT + " created from " + TYPE);
assertThat(content.toString()).isEqualTo("ObjectContent " + OBJECT + " created from " + TYPE);
}
@Test

View File

@@ -45,18 +45,15 @@ public class DefinitionsParserTests {
public void parseSingleMockBean() {
this.parser.parse(SingleMockBean.class);
assertThat(getDefinitions()).hasSize(1);
assertThat(getMockDefinition(0).getTypeToMock().resolve())
.isEqualTo(ExampleService.class);
assertThat(getMockDefinition(0).getTypeToMock().resolve()).isEqualTo(ExampleService.class);
}
@Test
public void parseRepeatMockBean() {
this.parser.parse(RepeatMockBean.class);
assertThat(getDefinitions()).hasSize(2);
assertThat(getMockDefinition(0).getTypeToMock().resolve())
.isEqualTo(ExampleService.class);
assertThat(getMockDefinition(1).getTypeToMock().resolve())
.isEqualTo(ExampleServiceCaller.class);
assertThat(getMockDefinition(0).getTypeToMock().resolve()).isEqualTo(ExampleService.class);
assertThat(getMockDefinition(1).getTypeToMock().resolve()).isEqualTo(ExampleServiceCaller.class);
}
@Test
@@ -66,8 +63,7 @@ public class DefinitionsParserTests {
MockDefinition definition = getMockDefinition(0);
assertThat(definition.getName()).isEqualTo("Name");
assertThat(definition.getTypeToMock().resolve()).isEqualTo(ExampleService.class);
assertThat(definition.getExtraInterfaces())
.containsExactly(ExampleExtraInterface.class);
assertThat(definition.getExtraInterfaces()).containsExactly(ExampleExtraInterface.class);
assertThat(definition.getAnswer()).isEqualTo(Answers.RETURNS_SMART_NULLS);
assertThat(definition.isSerializable()).isTrue();
assertThat(definition.getReset()).isEqualTo(MockReset.NONE);
@@ -79,14 +75,12 @@ public class DefinitionsParserTests {
this.parser.parse(MockBeanOnClassAndField.class);
assertThat(getDefinitions()).hasSize(2);
MockDefinition classDefinition = getMockDefinition(0);
assertThat(classDefinition.getTypeToMock().resolve())
.isEqualTo(ExampleService.class);
assertThat(classDefinition.getTypeToMock().resolve()).isEqualTo(ExampleService.class);
assertThat(classDefinition.getQualifier()).isNull();
MockDefinition fieldDefinition = getMockDefinition(1);
assertThat(fieldDefinition.getTypeToMock().resolve())
.isEqualTo(ExampleServiceCaller.class);
QualifierDefinition qualifier = QualifierDefinition.forElement(
ReflectionUtils.findField(MockBeanOnClassAndField.class, "caller"));
assertThat(fieldDefinition.getTypeToMock().resolve()).isEqualTo(ExampleServiceCaller.class);
QualifierDefinition qualifier = QualifierDefinition
.forElement(ReflectionUtils.findField(MockBeanOnClassAndField.class, "caller"));
assertThat(fieldDefinition.getQualifier()).isNotNull().isEqualTo(qualifier);
}
@@ -94,14 +88,12 @@ public class DefinitionsParserTests {
public void parseMockBeanInferClassToMock() {
this.parser.parse(MockBeanInferClassToMock.class);
assertThat(getDefinitions()).hasSize(1);
assertThat(getMockDefinition(0).getTypeToMock().resolve())
.isEqualTo(ExampleService.class);
assertThat(getMockDefinition(0).getTypeToMock().resolve()).isEqualTo(ExampleService.class);
}
@Test
public void parseMockBeanMissingClassToMock() {
assertThatIllegalStateException()
.isThrownBy(() -> this.parser.parse(MockBeanMissingClassToMock.class))
assertThatIllegalStateException().isThrownBy(() -> this.parser.parse(MockBeanMissingClassToMock.class))
.withMessageContaining("Unable to deduce type to mock");
}
@@ -109,37 +101,29 @@ public class DefinitionsParserTests {
public void parseMockBeanMultipleClasses() {
this.parser.parse(MockBeanMultipleClasses.class);
assertThat(getDefinitions()).hasSize(2);
assertThat(getMockDefinition(0).getTypeToMock().resolve())
.isEqualTo(ExampleService.class);
assertThat(getMockDefinition(1).getTypeToMock().resolve())
.isEqualTo(ExampleServiceCaller.class);
assertThat(getMockDefinition(0).getTypeToMock().resolve()).isEqualTo(ExampleService.class);
assertThat(getMockDefinition(1).getTypeToMock().resolve()).isEqualTo(ExampleServiceCaller.class);
}
@Test
public void parseMockBeanMultipleClassesWithName() {
assertThatIllegalStateException()
.isThrownBy(
() -> this.parser.parse(MockBeanMultipleClassesWithName.class))
.withMessageContaining(
"The name attribute can only be used when mocking a single class");
assertThatIllegalStateException().isThrownBy(() -> this.parser.parse(MockBeanMultipleClassesWithName.class))
.withMessageContaining("The name attribute can only be used when mocking a single class");
}
@Test
public void parseSingleSpyBean() {
this.parser.parse(SingleSpyBean.class);
assertThat(getDefinitions()).hasSize(1);
assertThat(getSpyDefinition(0).getTypeToSpy().resolve())
.isEqualTo(RealExampleService.class);
assertThat(getSpyDefinition(0).getTypeToSpy().resolve()).isEqualTo(RealExampleService.class);
}
@Test
public void parseRepeatSpyBean() {
this.parser.parse(RepeatSpyBean.class);
assertThat(getDefinitions()).hasSize(2);
assertThat(getSpyDefinition(0).getTypeToSpy().resolve())
.isEqualTo(RealExampleService.class);
assertThat(getSpyDefinition(1).getTypeToSpy().resolve())
.isEqualTo(ExampleServiceCaller.class);
assertThat(getSpyDefinition(0).getTypeToSpy().resolve()).isEqualTo(RealExampleService.class);
assertThat(getSpyDefinition(1).getTypeToSpy().resolve()).isEqualTo(ExampleServiceCaller.class);
}
@Test
@@ -148,8 +132,7 @@ public class DefinitionsParserTests {
assertThat(getDefinitions()).hasSize(1);
SpyDefinition definition = getSpyDefinition(0);
assertThat(definition.getName()).isEqualTo("Name");
assertThat(definition.getTypeToSpy().resolve())
.isEqualTo(RealExampleService.class);
assertThat(definition.getTypeToSpy().resolve()).isEqualTo(RealExampleService.class);
assertThat(definition.getReset()).isEqualTo(MockReset.NONE);
assertThat(definition.getQualifier()).isNull();
}
@@ -160,28 +143,24 @@ public class DefinitionsParserTests {
assertThat(getDefinitions()).hasSize(2);
SpyDefinition classDefinition = getSpyDefinition(0);
assertThat(classDefinition.getQualifier()).isNull();
assertThat(classDefinition.getTypeToSpy().resolve())
.isEqualTo(RealExampleService.class);
assertThat(classDefinition.getTypeToSpy().resolve()).isEqualTo(RealExampleService.class);
SpyDefinition fieldDefinition = getSpyDefinition(1);
QualifierDefinition qualifier = QualifierDefinition.forElement(
ReflectionUtils.findField(SpyBeanOnClassAndField.class, "caller"));
QualifierDefinition qualifier = QualifierDefinition
.forElement(ReflectionUtils.findField(SpyBeanOnClassAndField.class, "caller"));
assertThat(fieldDefinition.getQualifier()).isNotNull().isEqualTo(qualifier);
assertThat(fieldDefinition.getTypeToSpy().resolve())
.isEqualTo(ExampleServiceCaller.class);
assertThat(fieldDefinition.getTypeToSpy().resolve()).isEqualTo(ExampleServiceCaller.class);
}
@Test
public void parseSpyBeanInferClassToMock() {
this.parser.parse(SpyBeanInferClassToMock.class);
assertThat(getDefinitions()).hasSize(1);
assertThat(getSpyDefinition(0).getTypeToSpy().resolve())
.isEqualTo(RealExampleService.class);
assertThat(getSpyDefinition(0).getTypeToSpy().resolve()).isEqualTo(RealExampleService.class);
}
@Test
public void parseSpyBeanMissingClassToMock() {
assertThatIllegalStateException()
.isThrownBy(() -> this.parser.parse(SpyBeanMissingClassToMock.class))
assertThatIllegalStateException().isThrownBy(() -> this.parser.parse(SpyBeanMissingClassToMock.class))
.withMessageContaining("Unable to deduce type to spy");
}
@@ -189,18 +168,14 @@ public class DefinitionsParserTests {
public void parseSpyBeanMultipleClasses() {
this.parser.parse(SpyBeanMultipleClasses.class);
assertThat(getDefinitions()).hasSize(2);
assertThat(getSpyDefinition(0).getTypeToSpy().resolve())
.isEqualTo(RealExampleService.class);
assertThat(getSpyDefinition(1).getTypeToSpy().resolve())
.isEqualTo(ExampleServiceCaller.class);
assertThat(getSpyDefinition(0).getTypeToSpy().resolve()).isEqualTo(RealExampleService.class);
assertThat(getSpyDefinition(1).getTypeToSpy().resolve()).isEqualTo(ExampleServiceCaller.class);
}
@Test
public void parseSpyBeanMultipleClassesWithName() {
assertThatIllegalStateException()
.isThrownBy(() -> this.parser.parse(SpyBeanMultipleClassesWithName.class))
.withMessageContaining(
"The name attribute can only be used when spying a single class");
assertThatIllegalStateException().isThrownBy(() -> this.parser.parse(SpyBeanMultipleClassesWithName.class))
.withMessageContaining("The name attribute can only be used when spying a single class");
}
private MockDefinition getMockDefinition(int index) {
@@ -225,10 +200,8 @@ public class DefinitionsParserTests {
}
@MockBean(name = "Name", classes = ExampleService.class,
extraInterfaces = ExampleExtraInterface.class,
answer = Answers.RETURNS_SMART_NULLS, serializable = true,
reset = MockReset.NONE)
@MockBean(name = "Name", classes = ExampleService.class, extraInterfaces = ExampleExtraInterface.class,
answer = Answers.RETURNS_SMART_NULLS, serializable = true, reset = MockReset.NONE)
static class MockBeanAttributes {
}
@@ -247,8 +220,7 @@ public class DefinitionsParserTests {
}
@MockBean(name = "name",
classes = { ExampleService.class, ExampleServiceCaller.class })
@MockBean(name = "name", classes = { ExampleService.class, ExampleServiceCaller.class })
static class MockBeanMultipleClassesWithName {
}
@@ -270,8 +242,7 @@ public class DefinitionsParserTests {
}
@SpyBeans({ @SpyBean(RealExampleService.class),
@SpyBean(ExampleServiceCaller.class) })
@SpyBeans({ @SpyBean(RealExampleService.class), @SpyBean(ExampleServiceCaller.class) })
static class RepeatSpyBean {
}
@@ -295,8 +266,7 @@ public class DefinitionsParserTests {
}
@SpyBean(name = "name",
classes = { RealExampleService.class, ExampleServiceCaller.class })
@SpyBean(name = "name", classes = { RealExampleService.class, ExampleServiceCaller.class })
static class SpyBeanMultipleClassesWithName {
}

View File

@@ -53,8 +53,7 @@ public class MockBeanOnContextHierarchyIntegrationTests {
ApplicationContext context = this.childConfig.getContext();
ApplicationContext parentContext = context.getParent();
assertThat(parentContext.getBeanNamesForType(ExampleService.class)).hasSize(1);
assertThat(parentContext.getBeanNamesForType(ExampleServiceCaller.class))
.hasSize(0);
assertThat(parentContext.getBeanNamesForType(ExampleServiceCaller.class)).hasSize(0);
assertThat(context.getBeanNamesForType(ExampleService.class)).hasSize(0);
assertThat(context.getBeanNamesForType(ExampleServiceCaller.class)).hasSize(1);
assertThat(context.getBean(ExampleService.class)).isNotNull();
@@ -74,8 +73,7 @@ public class MockBeanOnContextHierarchyIntegrationTests {
private ApplicationContext context;
@Override
public void setApplicationContext(ApplicationContext applicationContext)
throws BeansException {
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.context = applicationContext;
}

View File

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

@@ -36,20 +36,18 @@ import static org.mockito.Mockito.mock;
*/
public class MockDefinitionTests {
private static final ResolvableType EXAMPLE_SERVICE_TYPE = ResolvableType
.forClass(ExampleService.class);
private static final ResolvableType EXAMPLE_SERVICE_TYPE = ResolvableType.forClass(ExampleService.class);
@Test
public void classToMockMustNotBeNull() {
assertThatIllegalArgumentException().isThrownBy(
() -> new MockDefinition(null, null, null, null, false, null, null))
assertThatIllegalArgumentException()
.isThrownBy(() -> new MockDefinition(null, null, null, null, false, null, null))
.withMessageContaining("TypeToMock must not be null");
}
@Test
public void createWithDefaults() {
MockDefinition definition = new MockDefinition(null, EXAMPLE_SERVICE_TYPE, null,
null, false, null, null);
MockDefinition definition = new MockDefinition(null, EXAMPLE_SERVICE_TYPE, null, null, false, null, null);
assertThat(definition.getName()).isNull();
assertThat(definition.getTypeToMock()).isEqualTo(EXAMPLE_SERVICE_TYPE);
assertThat(definition.getExtraInterfaces()).isEmpty();
@@ -63,12 +61,11 @@ public class MockDefinitionTests {
public void createExplicit() {
QualifierDefinition qualifier = mock(QualifierDefinition.class);
MockDefinition definition = new MockDefinition("name", EXAMPLE_SERVICE_TYPE,
new Class<?>[] { ExampleExtraInterface.class },
Answers.RETURNS_SMART_NULLS, true, MockReset.BEFORE, qualifier);
new Class<?>[] { ExampleExtraInterface.class }, Answers.RETURNS_SMART_NULLS, true, MockReset.BEFORE,
qualifier);
assertThat(definition.getName()).isEqualTo("name");
assertThat(definition.getTypeToMock()).isEqualTo(EXAMPLE_SERVICE_TYPE);
assertThat(definition.getExtraInterfaces())
.containsExactly(ExampleExtraInterface.class);
assertThat(definition.getExtraInterfaces()).containsExactly(ExampleExtraInterface.class);
assertThat(definition.getAnswer()).isEqualTo(Answers.RETURNS_SMART_NULLS);
assertThat(definition.isSerializable()).isTrue();
assertThat(definition.getReset()).isEqualTo(MockReset.BEFORE);
@@ -79,11 +76,10 @@ public class MockDefinitionTests {
@Test
public void createMock() {
MockDefinition definition = new MockDefinition("name", EXAMPLE_SERVICE_TYPE,
new Class<?>[] { ExampleExtraInterface.class },
Answers.RETURNS_SMART_NULLS, true, MockReset.BEFORE, null);
new Class<?>[] { ExampleExtraInterface.class }, Answers.RETURNS_SMART_NULLS, true, MockReset.BEFORE,
null);
ExampleService mock = definition.createMock();
MockCreationSettings<?> settings = Mockito.mockingDetails(mock)
.getMockCreationSettings();
MockCreationSettings<?> settings = Mockito.mockingDetails(mock).getMockCreationSettings();
assertThat(mock).isInstanceOf(ExampleService.class);
assertThat(mock).isInstanceOf(ExampleExtraInterface.class);
assertThat(settings.getMockName().toString()).isEqualTo("name");

View File

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

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

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

@@ -48,10 +48,8 @@ public class MockitoPostProcessorTests {
MockitoPostProcessor.register(context);
context.register(MultipleBeans.class);
assertThatIllegalStateException().isThrownBy(context::refresh)
.withMessageContaining(
"Unable to register mock bean " + ExampleService.class.getName()
+ " expected a single matching bean to replace "
+ "but found [example1, example2]");
.withMessageContaining("Unable to register mock bean " + ExampleService.class.getName()
+ " expected a single matching bean to replace " + "but found [example1, example2]");
}
@Test
@@ -60,25 +58,20 @@ public class MockitoPostProcessorTests {
MockitoPostProcessor.register(context);
context.register(MultipleQualifiedBeans.class);
assertThatIllegalStateException().isThrownBy(context::refresh)
.withMessageContaining(
"Unable to register mock bean " + ExampleService.class.getName()
+ " expected a single matching bean to replace "
+ "but found [example1, example3]");
.withMessageContaining("Unable to register mock bean " + ExampleService.class.getName()
+ " expected a single matching bean to replace " + "but found [example1, example3]");
}
@Test
public void canMockBeanProducedByFactoryBeanWithObjectTypeAttribute() {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
MockitoPostProcessor.register(context);
RootBeanDefinition factoryBeanDefinition = new RootBeanDefinition(
TestFactoryBean.class);
factoryBeanDefinition.setAttribute("factoryBeanObjectType",
SomeInterface.class.getName());
RootBeanDefinition factoryBeanDefinition = new RootBeanDefinition(TestFactoryBean.class);
factoryBeanDefinition.setAttribute("factoryBeanObjectType", SomeInterface.class.getName());
context.registerBeanDefinition("beanToBeMocked", factoryBeanDefinition);
context.register(MockedFactoryBean.class);
context.refresh();
assertThat(Mockito.mockingDetails(context.getBean("beanToBeMocked")).isMock())
.isTrue();
assertThat(Mockito.mockingDetails(context.getBean("beanToBeMocked")).isMock()).isTrue();
}
@Test
@@ -87,16 +80,11 @@ public class MockitoPostProcessorTests {
MockitoPostProcessor.register(context);
context.register(MockPrimaryBean.class);
context.refresh();
assertThat(Mockito.mockingDetails(context.getBean(MockPrimaryBean.class).mock)
.isMock()).isTrue();
assertThat(Mockito.mockingDetails(context.getBean(ExampleService.class)).isMock())
.isTrue();
assertThat(Mockito
.mockingDetails(context.getBean("examplePrimary", ExampleService.class))
.isMock()).isTrue();
assertThat(Mockito
.mockingDetails(context.getBean("exampleQualified", ExampleService.class))
.isMock()).isFalse();
assertThat(Mockito.mockingDetails(context.getBean(MockPrimaryBean.class).mock).isMock()).isTrue();
assertThat(Mockito.mockingDetails(context.getBean(ExampleService.class)).isMock()).isTrue();
assertThat(Mockito.mockingDetails(context.getBean("examplePrimary", ExampleService.class)).isMock()).isTrue();
assertThat(Mockito.mockingDetails(context.getBean("exampleQualified", ExampleService.class)).isMock())
.isFalse();
}
@Test
@@ -105,16 +93,10 @@ public class MockitoPostProcessorTests {
MockitoPostProcessor.register(context);
context.register(MockQualifiedBean.class);
context.refresh();
assertThat(Mockito.mockingDetails(context.getBean(MockQualifiedBean.class).mock)
.isMock()).isTrue();
assertThat(Mockito.mockingDetails(context.getBean(ExampleService.class)).isMock())
.isFalse();
assertThat(Mockito
.mockingDetails(context.getBean("examplePrimary", ExampleService.class))
.isMock()).isFalse();
assertThat(Mockito
.mockingDetails(context.getBean("exampleQualified", ExampleService.class))
.isMock()).isTrue();
assertThat(Mockito.mockingDetails(context.getBean(MockQualifiedBean.class).mock).isMock()).isTrue();
assertThat(Mockito.mockingDetails(context.getBean(ExampleService.class)).isMock()).isFalse();
assertThat(Mockito.mockingDetails(context.getBean("examplePrimary", ExampleService.class)).isMock()).isFalse();
assertThat(Mockito.mockingDetails(context.getBean("exampleQualified", ExampleService.class)).isMock()).isTrue();
}
@Test
@@ -123,17 +105,10 @@ public class MockitoPostProcessorTests {
MockitoPostProcessor.register(context);
context.register(SpyPrimaryBean.class);
context.refresh();
assertThat(
Mockito.mockingDetails(context.getBean(SpyPrimaryBean.class).spy).isSpy())
.isTrue();
assertThat(Mockito.mockingDetails(context.getBean(ExampleService.class)).isSpy())
.isTrue();
assertThat(Mockito
.mockingDetails(context.getBean("examplePrimary", ExampleService.class))
.isSpy()).isTrue();
assertThat(Mockito
.mockingDetails(context.getBean("exampleQualified", ExampleService.class))
.isSpy()).isFalse();
assertThat(Mockito.mockingDetails(context.getBean(SpyPrimaryBean.class).spy).isSpy()).isTrue();
assertThat(Mockito.mockingDetails(context.getBean(ExampleService.class)).isSpy()).isTrue();
assertThat(Mockito.mockingDetails(context.getBean("examplePrimary", ExampleService.class)).isSpy()).isTrue();
assertThat(Mockito.mockingDetails(context.getBean("exampleQualified", ExampleService.class)).isSpy()).isFalse();
}
@Test
@@ -142,16 +117,10 @@ public class MockitoPostProcessorTests {
MockitoPostProcessor.register(context);
context.register(SpyQualifiedBean.class);
context.refresh();
assertThat(Mockito.mockingDetails(context.getBean(SpyQualifiedBean.class).spy)
.isSpy()).isTrue();
assertThat(Mockito.mockingDetails(context.getBean(ExampleService.class)).isSpy())
.isFalse();
assertThat(Mockito
.mockingDetails(context.getBean("examplePrimary", ExampleService.class))
.isSpy()).isFalse();
assertThat(Mockito
.mockingDetails(context.getBean("exampleQualified", ExampleService.class))
.isSpy()).isTrue();
assertThat(Mockito.mockingDetails(context.getBean(SpyQualifiedBean.class).spy).isSpy()).isTrue();
assertThat(Mockito.mockingDetails(context.getBean(ExampleService.class)).isSpy()).isFalse();
assertThat(Mockito.mockingDetails(context.getBean("examplePrimary", ExampleService.class)).isSpy()).isFalse();
assertThat(Mockito.mockingDetails(context.getBean("exampleQualified", ExampleService.class)).isSpy()).isTrue();
}
@Configuration(proxyBeanMethods = false)

View File

@@ -59,8 +59,7 @@ public class MockitoTestExecutionListenerTests {
@BeforeEach
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

@@ -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(proxyBeanMethods = false)

View File

@@ -54,8 +54,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();
@@ -75,8 +74,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

@@ -61,8 +61,7 @@ public class SpyBeanOnTestFieldForExistingBeanWithQualifierIntegrationTests {
@Test
public void onlyQualifiedBeanIsReplaced() {
assertThat(this.applicationContext.getBean("service")).isSameAs(this.service);
ExampleService anotherService = this.applicationContext.getBean("anotherService",
ExampleService.class);
ExampleService anotherService = this.applicationContext.getBean("anotherService", ExampleService.class);
assertThat(anotherService.greeting()).isEqualTo("Another");
}

View File

@@ -57,8 +57,7 @@ public class SpyBeanOnTestFieldForExistingGenericBeanIntegrationTests {
}
@Configuration(proxyBeanMethods = false)
@Import({ ExampleGenericServiceCaller.class,
SimpleExampleIntegerGenericService.class })
@Import({ ExampleGenericServiceCaller.class, SimpleExampleIntegerGenericService.class })
static class SpyBeanOnTestFieldForExistingBeanConfig {
@Bean

View File

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

@@ -55,8 +55,7 @@ public class SpyBeanWithAopProxyAndNotProxyTargetAwareTests {
public void verifyShouldUseProxyTarget() {
this.dateService.getDate(false);
verify(this.dateService, times(1)).getDate(false);
assertThatExceptionOfType(UnfinishedVerificationException.class)
.isThrownBy(() -> reset(this.dateService));
assertThatExceptionOfType(UnfinishedVerificationException.class).isThrownBy(() -> reset(this.dateService));
}
@Configuration(proxyBeanMethods = false)

View File

@@ -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(proxyBeanMethods = false)

View File

@@ -37,20 +37,17 @@ 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);
@Test
public void classToSpyMustNotBeNull() {
assertThatIllegalArgumentException()
.isThrownBy(() -> new SpyDefinition(null, null, null, true, null))
assertThatIllegalArgumentException().isThrownBy(() -> new SpyDefinition(null, null, null, true, null))
.withMessageContaining("TypeToSpy must not be null");
}
@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);
@@ -61,8 +58,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);
@@ -72,11 +68,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);
@@ -85,25 +79,21 @@ 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);
assertThatIllegalArgumentException().isThrownBy(() -> definition.createSpy(null))
.withMessageContaining("Instance must not be null");
}
@Test
public void createSpyWhenWrongInstanceShouldThrowException() {
SpyDefinition definition = new SpyDefinition("name", REAL_SERVICE_TYPE,
MockReset.BEFORE, true, null);
assertThatIllegalArgumentException()
.isThrownBy(() -> definition.createSpy(new ExampleServiceCaller(null)))
SpyDefinition definition = new SpyDefinition("name", REAL_SERVICE_TYPE, MockReset.BEFORE, true, null);
assertThatIllegalArgumentException().isThrownBy(() -> definition.createSpy(new ExampleServiceCaller(null)))
.withMessageContaining("must be an instance of");
}
@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

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

@@ -43,8 +43,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

@@ -80,8 +80,7 @@ class OutputCaptureTests {
@Test
void popWhenEmptyThrowsException() {
assertThatExceptionOfType(NoSuchElementException.class)
.isThrownBy(this.output::pop);
assertThatExceptionOfType(NoSuchElementException.class).isThrownBy(this.output::pop);
}
@Test

View File

@@ -40,8 +40,7 @@ class OutputExtensionExtendWithTests {
void captureShouldReturnAllCapturedOutput(CapturedOutput output) {
System.out.println("Hello World");
System.err.println("Error!!!");
assertThat(output).contains("Before all").contains("Hello World")
.contains("Error!!!");
assertThat(output).contains("Before all").contains("Hello World").contains("Error!!!");
}
static class BeforeAllExtension implements BeforeAllCallback {

View File

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

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

@@ -76,8 +76,7 @@ public class SpringBootTestRandomPortEnvironmentPostProcessorTests {
this.environment.setProperty("management.server.port", "8081");
this.postProcessor.postProcessEnvironment(this.environment, null);
assertThat(this.environment.getProperty("server.port")).isEqualTo("8080");
assertThat(this.environment.getProperty("management.server.port"))
.isEqualTo("8081");
assertThat(this.environment.getProperty("management.server.port")).isEqualTo("8081");
}
@Test
@@ -85,8 +84,7 @@ public class SpringBootTestRandomPortEnvironmentPostProcessorTests {
addTestPropertySource("0", "8080");
this.postProcessor.postProcessEnvironment(this.environment, null);
assertThat(this.environment.getProperty("server.port")).isEqualTo("0");
assertThat(this.environment.getProperty("management.server.port"))
.isEqualTo("8080");
assertThat(this.environment.getProperty("management.server.port")).isEqualTo("8080");
}
@Test
@@ -115,8 +113,8 @@ public class SpringBootTestRandomPortEnvironmentPostProcessorTests {
// mgmt port is 8080 which means it's on the same port as main server since that
// is null in app properties
addTestPropertySource("0", null);
this.propertySources.addLast(new MapPropertySource("other",
Collections.singletonMap("management.server.port", "8080")));
this.propertySources
.addLast(new MapPropertySource("other", Collections.singletonMap("management.server.port", "8080")));
this.postProcessor.postProcessEnvironment(this.environment, null);
assertThat(this.environment.getProperty("server.port")).isEqualTo("0");
assertThat(this.environment.getProperty("management.server.port")).isEqualTo("");
@@ -125,8 +123,8 @@ public class SpringBootTestRandomPortEnvironmentPostProcessorTests {
@Test
public void postProcessWhenTestServerPortIsZeroAndManagementPortIsNotNullAndDifferentInProduction() {
addTestPropertySource("0", null);
this.propertySources.addLast(new MapPropertySource("other",
Collections.singletonMap("management.server.port", "8081")));
this.propertySources
.addLast(new MapPropertySource("other", Collections.singletonMap("management.server.port", "8081")));
this.postProcessor.postProcessEnvironment(this.environment, null);
assertThat(this.environment.getProperty("server.port")).isEqualTo("0");
assertThat(this.environment.getProperty("management.server.port")).isEqualTo("0");
@@ -135,19 +133,18 @@ public class SpringBootTestRandomPortEnvironmentPostProcessorTests {
@Test
public void postProcessWhenTestServerPortIsZeroAndManagementPortMinusOne() {
addTestPropertySource("0", null);
this.propertySources.addLast(new MapPropertySource("other",
Collections.singletonMap("management.server.port", "-1")));
this.propertySources
.addLast(new MapPropertySource("other", Collections.singletonMap("management.server.port", "-1")));
this.postProcessor.postProcessEnvironment(this.environment, null);
assertThat(this.environment.getProperty("server.port")).isEqualTo("0");
assertThat(this.environment.getProperty("management.server.port"))
.isEqualTo("-1");
assertThat(this.environment.getProperty("management.server.port")).isEqualTo("-1");
}
@Test
public void postProcessWhenTestServerPortIsZeroAndManagementPortIsAnInteger() {
addTestPropertySource("0", null);
this.propertySources.addLast(new MapPropertySource("other",
Collections.singletonMap("management.server.port", 8081)));
this.propertySources
.addLast(new MapPropertySource("other", Collections.singletonMap("management.server.port", 8081)));
this.postProcessor.postProcessEnvironment(this.environment, null);
assertThat(this.environment.getProperty("server.port")).isEqualTo("0");
assertThat(this.environment.getProperty("management.server.port")).isEqualTo("0");
@@ -159,8 +156,8 @@ public class SpringBootTestRandomPortEnvironmentPostProcessorTests {
MapPropertySource testPropertySource = (MapPropertySource) this.propertySources
.get(TestPropertySourceUtils.INLINED_PROPERTIES_PROPERTY_SOURCE_NAME);
testPropertySource.getSource().put("port", "9090");
this.propertySources.addLast(new MapPropertySource("other",
Collections.singletonMap("management.server.port", "${port}")));
this.propertySources
.addLast(new MapPropertySource("other", Collections.singletonMap("management.server.port", "${port}")));
this.postProcessor.postProcessEnvironment(this.environment, null);
assertThat(this.environment.getProperty("server.port")).isEqualTo("0");
assertThat(this.environment.getProperty("management.server.port")).isEqualTo("0");
@@ -169,10 +166,10 @@ public class SpringBootTestRandomPortEnvironmentPostProcessorTests {
@Test
public void postProcessWhenManagementServerPortPlaceholderAbsentShouldFail() {
addTestPropertySource("0", null);
this.propertySources.addLast(new MapPropertySource("other",
Collections.singletonMap("management.server.port", "${port}")));
assertThatIllegalArgumentException().isThrownBy(
() -> this.postProcessor.postProcessEnvironment(this.environment, null))
this.propertySources
.addLast(new MapPropertySource("other", Collections.singletonMap("management.server.port", "${port}")));
assertThatIllegalArgumentException()
.isThrownBy(() -> this.postProcessor.postProcessEnvironment(this.environment, null))
.withMessage("Could not resolve placeholder 'port' in value \"${port}\"");
}
@@ -198,8 +195,8 @@ public class SpringBootTestRandomPortEnvironmentPostProcessorTests {
source.put("server.port", "${port}");
source.put("management.server.port", "9090");
this.propertySources.addLast(new MapPropertySource("other", source));
assertThatIllegalArgumentException().isThrownBy(
() -> this.postProcessor.postProcessEnvironment(this.environment, null))
assertThatIllegalArgumentException()
.isThrownBy(() -> this.postProcessor.postProcessEnvironment(this.environment, null))
.withMessage("Could not resolve placeholder 'port' in value \"${port}\"");
}

View File

@@ -42,23 +42,21 @@ public class LocalHostUriTemplateHandlerTests {
@Test
public void createWhenEnvironmentIsNullShouldThrowException() {
assertThatIllegalArgumentException()
.isThrownBy(() -> new LocalHostUriTemplateHandler(null))
assertThatIllegalArgumentException().isThrownBy(() -> new LocalHostUriTemplateHandler(null))
.withMessageContaining("Environment must not be null");
}
@Test
public void createWhenSchemeIsNullShouldThrowException() {
assertThatIllegalArgumentException().isThrownBy(
() -> new LocalHostUriTemplateHandler(new MockEnvironment(), null))
assertThatIllegalArgumentException()
.isThrownBy(() -> new LocalHostUriTemplateHandler(new MockEnvironment(), null))
.withMessageContaining("Scheme must not be null");
}
@Test
public void createWhenHandlerIsNullShouldThrowException() {
assertThatIllegalArgumentException()
.isThrownBy(() -> new LocalHostUriTemplateHandler(new MockEnvironment(),
"http", null))
.isThrownBy(() -> new LocalHostUriTemplateHandler(new MockEnvironment(), "http", null))
.withMessageContaining("Handler must not be null");
}
@@ -66,24 +64,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");
}
@@ -91,8 +86,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");
}
@@ -102,10 +96,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

@@ -55,8 +55,7 @@ public class MockServerRestTemplateCustomizerTests {
@Test
public void createWhenExpectationManagerClassIsNullShouldThrowException() {
assertThatIllegalArgumentException()
.isThrownBy(() -> new MockServerRestTemplateCustomizer(null))
assertThatIllegalArgumentException().isThrownBy(() -> new MockServerRestTemplateCustomizer(null))
.withMessageContaining("ExpectationManager must not be null");
}
@@ -73,8 +72,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);
}
@@ -82,8 +80,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);
@@ -100,9 +97,8 @@ public class MockServerRestTemplateCustomizerTests {
@Test
public void getServerWhenNoServersAreBoundShouldThrowException() {
assertThatIllegalStateException().isThrownBy(this.customizer::getServer)
.withMessageContaining(
"Unable to return a single MockRestServiceServer since "
+ "MockServerRestTemplateCustomizer has not been bound to a RestTemplate");
.withMessageContaining("Unable to return a single MockRestServiceServer since "
+ "MockServerRestTemplateCustomizer has not been bound to a RestTemplate");
}
@Test
@@ -110,17 +106,15 @@ public class MockServerRestTemplateCustomizerTests {
this.customizer.customize(new RestTemplate());
this.customizer.customize(new RestTemplate());
assertThatIllegalStateException().isThrownBy(this.customizer::getServer)
.withMessageContaining(
"Unable to return a single MockRestServiceServer since "
+ "MockServerRestTemplateCustomizer has been bound to more than one RestTemplate");
.withMessageContaining("Unable to return a single MockRestServiceServer since "
+ "MockServerRestTemplateCustomizer has been bound to more than one RestTemplate");
}
@Test
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
@@ -130,8 +124,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
@@ -158,14 +151,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

@@ -69,16 +69,13 @@ public class RootUriRequestExpectationManagerTests {
@Test
public void createWhenRootUriIsNullShouldThrowException() {
assertThatIllegalArgumentException()
.isThrownBy(
() -> new RootUriRequestExpectationManager(null, this.delegate))
assertThatIllegalArgumentException().isThrownBy(() -> new RootUriRequestExpectationManager(null, this.delegate))
.withMessageContaining("RootUri must not be null");
}
@Test
public void createWhenExpectationManagerIsNullShouldThrowException() {
assertThatIllegalArgumentException()
.isThrownBy(() -> new RootUriRequestExpectationManager(this.uri, null))
assertThatIllegalArgumentException().isThrownBy(() -> new RootUriRequestExpectationManager(this.uri, null))
.withMessageContaining("ExpectationManager must not be null");
}
@@ -91,8 +88,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);
@@ -100,8 +96,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);
@@ -112,17 +107,13 @@ 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>"));
assertThatExceptionOfType(AssertionError.class)
.isThrownBy(() -> this.manager.validateRequest(request))
.withMessageContaining(
"Request URI expected:<https://example.com/hello>");
.willThrow(new AssertionError("Request URI expected:</hello> was:<https://example.com/bad>"));
assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> this.manager.validateRequest(request))
.withMessageContaining("Request URI expected:<https://example.com/hello>");
}
@Test
@@ -134,24 +125,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);
}
@@ -159,32 +148,27 @@ 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());
assertThatExceptionOfType(AssertionError.class).isThrownBy(
() -> restTemplate.getForEntity("https://spring.io/hello", String.class))
.withMessageContaining(
"expected:<https://example.com/hello> but was:<https://spring.io/hello>");
assertThatExceptionOfType(AssertionError.class)
.isThrownBy(() -> restTemplate.getForEntity("https://spring.io/hello", String.class))
.withMessageContaining("expected:<https://example.com/hello> but was:<https://spring.io/hello>");
}
}

View File

@@ -68,8 +68,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

@@ -41,16 +41,11 @@ public class TestRestTemplateContextCustomizerTests {
@Test
@SuppressWarnings({ "unchecked", "rawtypes" })
public void whenContextIsNotABeanDefinitionRegistryTestRestTemplateIsRegistered() {
new ApplicationContextRunner(TestApplicationContext::new)
.withInitializer((context) -> {
MergedContextConfiguration configuration = mock(
MergedContextConfiguration.class);
given(configuration.getTestClass())
.willReturn((Class) TestClass.class);
new TestRestTemplateContextCustomizer().customizeContext(context,
configuration);
}).run((context) -> assertThat(context)
.hasSingleBean(TestRestTemplate.class));
new ApplicationContextRunner(TestApplicationContext::new).withInitializer((context) -> {
MergedContextConfiguration configuration = mock(MergedContextConfiguration.class);
given(configuration.getTestClass()).willReturn((Class) TestClass.class);
new TestRestTemplateContextCustomizer().customizeContext(context, configuration);
}).run((context) -> assertThat(context).hasSingleBean(TestRestTemplate.class));
}
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
@@ -72,8 +67,7 @@ public class TestRestTemplateContextCustomizerTests {
}
@Override
public ConfigurableListableBeanFactory getBeanFactory()
throws IllegalStateException {
public ConfigurableListableBeanFactory getBeanFactory() throws IllegalStateException {
return this.beanFactory;
}

View File

@@ -35,8 +35,7 @@ import static org.assertj.core.api.Assertions.assertThat;
*
* @author Madhura Bhave
*/
@SpringBootTest(
classes = TestRestTemplateContextCustomizerWithFactoryBeanTests.TestClassWithFactoryBean.class,
@SpringBootTest(classes = TestRestTemplateContextCustomizerWithFactoryBeanTests.TestClassWithFactoryBean.class,
webEnvironment = WebEnvironment.RANDOM_PORT)
@DirtiesContext
public class TestRestTemplateContextCustomizerWithFactoryBeanTests {

View File

@@ -74,8 +74,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

@@ -85,8 +85,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);
@@ -95,15 +94,11 @@ public class TestRestTemplateTests {
@Test
public void useTheSameRequestFactoryClassWithBasicAuth() {
OkHttp3ClientHttpRequestFactory customFactory = new OkHttp3ClientHttpRequestFactory();
RestTemplateBuilder builder = new RestTemplateBuilder()
.requestFactory(() -> customFactory);
TestRestTemplate testRestTemplate = new TestRestTemplate(builder)
.withBasicAuth("test", "test");
RestTemplateBuilder builder = new RestTemplateBuilder().requestFactory(() -> customFactory);
TestRestTemplate testRestTemplate = new TestRestTemplate(builder).withBasicAuth("test", "test");
RestTemplate restTemplate = testRestTemplate.getRestTemplate();
assertThat(restTemplate.getRequestFactory().getClass().getName())
.contains("BasicAuth");
Object requestFactory = ReflectionTestUtils
.getField(restTemplate.getRequestFactory(), "requestFactory");
assertThat(restTemplate.getRequestFactory().getClass().getName()).contains("BasicAuth");
Object requestFactory = ReflectionTestUtils.getField(restTemplate.getRequestFactory(), "requestFactory");
assertThat(requestFactory).isEqualTo(customFactory).hasSameClassAs(customFactory);
}
@@ -118,8 +113,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);
@@ -132,16 +126,14 @@ public class TestRestTemplateTests {
@Test
public void authenticated() {
RestTemplate restTemplate = new TestRestTemplate("user", "password")
.getRestTemplate();
RestTemplate restTemplate = new TestRestTemplate("user", "password").getRestTemplate();
ClientHttpRequestFactory factory = restTemplate.getRequestFactory();
assertThat(factory.getClass().getName()).contains("BasicAuthentication");
}
@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();
@@ -151,10 +143,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);
@@ -162,14 +152,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);
@@ -215,36 +204,29 @@ public class TestRestTemplateTests {
public void withBasicAuthAddsBasicAuthClientFactoryWhenNotAlreadyPresent() {
TestRestTemplate original = new TestRestTemplate();
TestRestTemplate basicAuth = original.withBasicAuth("user", "password");
assertThat(getConverterClasses(original))
.containsExactlyElementsOf(getConverterClasses(basicAuth));
assertThat(basicAuth.getRestTemplate().getRequestFactory().getClass().getName())
.contains("BasicAuth");
assertThat(ReflectionTestUtils.getField(
basicAuth.getRestTemplate().getRequestFactory(), "requestFactory"))
.isInstanceOf(CustomHttpComponentsClientHttpRequestFactory.class);
assertThat(getConverterClasses(original)).containsExactlyElementsOf(getConverterClasses(basicAuth));
assertThat(basicAuth.getRestTemplate().getRequestFactory().getClass().getName()).contains("BasicAuth");
assertThat(ReflectionTestUtils.getField(basicAuth.getRestTemplate().getRequestFactory(), "requestFactory"))
.isInstanceOf(CustomHttpComponentsClientHttpRequestFactory.class);
assertThat(basicAuth.getRestTemplate().getInterceptors()).isEmpty();
assertBasicAuthorizationCredentials(basicAuth, "user", "password");
}
@Test
public void withBasicAuthReplacesBasicAuthClientFactoryWhenAlreadyPresent() {
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(getConverterClasses(basicAuth))
.containsExactlyElementsOf(getConverterClasses(original));
assertThat(basicAuth.getRestTemplate().getRequestFactory().getClass().getName())
.contains("BasicAuth");
assertThat(ReflectionTestUtils.getField(
basicAuth.getRestTemplate().getRequestFactory(), "requestFactory"))
.isInstanceOf(CustomHttpComponentsClientHttpRequestFactory.class);
assertThat(getConverterClasses(basicAuth)).containsExactlyElementsOf(getConverterClasses(original));
assertThat(basicAuth.getRestTemplate().getRequestFactory().getClass().getName()).contains("BasicAuth");
assertThat(ReflectionTestUtils.getField(basicAuth.getRestTemplate().getRequestFactory(), "requestFactory"))
.isInstanceOf(CustomHttpComponentsClientHttpRequestFactory.class);
assertThat(basicAuth.getRestTemplate().getInterceptors()).isEmpty();
assertBasicAuthorizationCredentials(basicAuth, "user", "password");
}
private List<Class<?>> getConverterClasses(TestRestTemplate testRestTemplate) {
return testRestTemplate.getRestTemplate().getMessageConverters().stream()
.map(Object::getClass).collect(Collectors.toList());
return testRestTemplate.getRestTemplate().getMessageConverters().stream().map(Object::getClass)
.collect(Collectors.toList());
}
@Test
@@ -252,11 +234,9 @@ 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())
.isInstanceOf(Class.forName(
"org.springframework.boot.test.web.client.TestRestTemplate$NoOpResponseErrorHandler"));
TestRestTemplate basicAuthTemplate = originalTemplate.withBasicAuth("user", "password");
assertThat(basicAuthTemplate.getRestTemplate().getErrorHandler()).isInstanceOf(
Class.forName("org.springframework.boot.test.web.client.TestRestTemplate$NoOpResponseErrorHandler"));
}
@Test
@@ -265,55 +245,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
@@ -328,59 +300,51 @@ 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 assertBasicAuthorizationCredentials(TestRestTemplate testRestTemplate,
String username, String password) {
ClientHttpRequestFactory requestFactory = testRestTemplate.getRestTemplate()
.getRequestFactory();
Object authentication = ReflectionTestUtils.getField(requestFactory,
"authentication");
private void assertBasicAuthorizationCredentials(TestRestTemplate testRestTemplate, String username,
String password) {
ClientHttpRequestFactory requestFactory = testRestTemplate.getRestTemplate().getRequestFactory();
Object authentication = ReflectionTestUtils.getField(requestFactory, "authentication");
assertThat(authentication).hasFieldOrPropertyWithValue("username", username);
assertThat(authentication).hasFieldOrPropertyWithValue("password", password);
@@ -398,8 +362,7 @@ public class TestRestTemplateTests {
}
@Override
public ClientHttpRequest createRequest(URI uri, HttpMethod httpMethod)
throws IOException {
public ClientHttpRequest createRequest(URI uri, HttpMethod httpMethod) throws IOException {
return null;
}

View File

@@ -55,8 +55,7 @@ public class LocalHostWebClientTests {
@Test
public void createWhenEnvironmentIsNullWillThrowException() {
assertThatIllegalArgumentException()
.isThrownBy(() -> new LocalHostWebClient(null))
assertThatIllegalArgumentException().isThrownBy(() -> new LocalHostWebClient(null))
.withMessageContaining("Environment must not be null");
}
@@ -68,13 +67,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);
@@ -82,8 +79,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

@@ -58,23 +58,20 @@ public class LocalHostWebConnectionHtmlUnitDriverTests {
@Test
public void createWhenEnvironmentIsNullWillThrowException() {
assertThatIllegalArgumentException()
.isThrownBy(() -> new LocalHostWebConnectionHtmlUnitDriver(null))
assertThatIllegalArgumentException().isThrownBy(() -> new LocalHostWebConnectionHtmlUnitDriver(null))
.withMessageContaining("Environment must not be null");
}
@Test
public void createWithJavascriptFlagWhenEnvironmentIsNullWillThrowException() {
assertThatIllegalArgumentException()
.isThrownBy(() -> new LocalHostWebConnectionHtmlUnitDriver(null, true))
assertThatIllegalArgumentException().isThrownBy(() -> new LocalHostWebConnectionHtmlUnitDriver(null, true))
.withMessageContaining("Environment must not be null");
}
@Test
public void createWithBrowserVersionWhenEnvironmentIsNullWillThrowException() {
assertThatIllegalArgumentException()
.isThrownBy(() -> new LocalHostWebConnectionHtmlUnitDriver(null,
BrowserVersion.CHROME))
.isThrownBy(() -> new LocalHostWebConnectionHtmlUnitDriver(null, BrowserVersion.CHROME))
.withMessageContaining("Environment must not be null");
}
@@ -83,38 +80,33 @@ public class LocalHostWebConnectionHtmlUnitDriverTests {
Capabilities capabilities = mock(Capabilities.class);
given(capabilities.getBrowserName()).willReturn("htmlunit");
given(capabilities.getVersion()).willReturn("chrome");
assertThatIllegalArgumentException().isThrownBy(
() -> new LocalHostWebConnectionHtmlUnitDriver(null, capabilities))
assertThatIllegalArgumentException()
.isThrownBy(() -> new LocalHostWebConnectionHtmlUnitDriver(null, capabilities))
.withMessageContaining("Environment must not be null");
}
@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);
@@ -127,8 +119,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

@@ -39,8 +39,7 @@ import org.springframework.test.web.reactive.server.WebTestClient;
*
* @author Phillip Webb
*/
@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 {
@@ -49,8 +48,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(proxyBeanMethods = false)

View File

@@ -43,8 +43,7 @@ import static org.mockito.Mockito.mock;
*
* @author Phillip Webb
*/
@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 {