From e19e3209d9fcb40f3ccb0485652e931977b13947 Mon Sep 17 00:00:00 2001 From: Phillip Webb Date: Sat, 6 Feb 2016 14:48:27 -0800 Subject: [PATCH] Use AssertJ in spring-boot See gh-5083 --- .../boot/ApplicationPidTests.java | 13 +- .../boot/ApplicationTempTests.java | 13 +- .../org/springframework/boot/BannerTests.java | 9 +- .../boot/BeanDefinitionLoaderTests.java | 54 ++-- .../DefaultApplicationArgumentsTests.java | 29 +- .../boot/ExitCodeGeneratorsTests.java | 13 +- .../boot/OverrideSourcesTests.java | 6 +- .../org/springframework/boot/ReproTests.java | 15 +- .../boot/ResourceBannerTests.java | 19 +- .../springframework/boot/SimpleMainTests.java | 12 +- .../boot/SpringApplicationTests.java | 209 +++++++------- .../boot/StartUpLoggerTests.java | 6 +- ...gApplicationAdminMXBeanRegistrarTests.java | 22 +- .../boot/ansi/AnsiOutputTests.java | 5 +- .../boot/ansi/AnsiPropertySourceTests.java | 28 +- .../boot/bind/BindingPreparationTests.java | 70 +++-- .../boot/bind/ConverterBindingTests.java | 7 +- ...faultPropertyNamePatternsMatcherTests.java | 33 ++- ...ropertiesConfigurationFactoryMapTests.java | 12 +- ...onfigurationFactoryParameterizedTests.java | 18 +- ...sConfigurationFactoryPerformanceTests.java | 6 +- .../PropertiesConfigurationFactoryTests.java | 16 +- .../bind/PropertySourcesBindingTests.java | 14 +- .../PropertySourcesPropertyValuesTests.java | 35 ++- .../boot/bind/RelaxedDataBinderTests.java | 265 +++++++++--------- .../boot/bind/RelaxedNamesTests.java | 109 ++++--- .../bind/RelaxedPropertyResolverTests.java | 70 +++-- .../SimplerPropertySourcesBindingTests.java | 5 +- .../bind/YamlConfigurationFactoryTests.java | 8 +- .../SpringApplicationBuilderTests.java | 89 +++--- .../boot/cloud/CloudPlatformTests.java | 20 +- ...ndryVcapEnvironmentPostProcessorTests.java | 28 +- ...ngsApplicationContextInitializerTests.java | 26 +- ...tIdApplicationContextInitializerTests.java | 12 +- .../ConfigFileApplicationListenerTests.java | 260 ++++++++--------- ...ingApplicationContextInitializerTests.java | 18 +- .../DelegatingApplicationListenerTests.java | 13 +- .../RandomValuePropertySourceTests.java | 38 +-- ...tEmbeddedServletContainerFactoryTests.java | 125 ++++----- ...figEmbeddedWebApplicationContextTests.java | 15 +- ...atingFilterProxyRegistrationBeanTests.java | 16 +- ...edServletContainerMvcIntegrationTests.java | 5 +- .../EmbeddedWebApplicationContextTests.java | 52 ++-- .../context/embedded/MimeMappingsTests.java | 42 ++- .../embedded/MultipartConfigFactoryTests.java | 25 +- .../AnsiOutputApplicationListenerTests.java | 9 +- ...yEmbeddedServletContainerFactoryTests.java | 14 +- ...tEmbeddedServletContainerFactoryTests.java | 29 +- .../undertow/FileSessionPersistenceTests.java | 22 +- ...wEmbeddedServletContainerFactoryTests.java | 24 +- ...onPropertiesBindingPostProcessorTests.java | 63 ++--- .../EnableConfigurationPropertiesTests.java | 166 ++++++----- .../web/ErrorPageFilterIntegrationTests.java | 15 +- .../context/web/ErrorPageFilterTests.java | 252 ++++++++--------- .../SpringBootServletInitializerTests.java | 32 +-- .../PropertiesPropertySourceLoaderTests.java | 12 +- .../boot/env/PropertySourcesLoaderTests.java | 8 +- ...tionJsonEnvironmentPostProcessorTests.java | 41 +-- .../env/YamlPropertySourceLoaderTests.java | 24 +- .../boot/json/AbstractJsonParserTests.java | 38 +-- .../AtomikosConnectionFactoryBeanTests.java | 5 +- .../atomikos/AtomikosDataSourceBeanTests.java | 5 +- ...ependsOnBeanFactoryPostProcessorTests.java | 8 +- .../jta/atomikos/AtomikosPropertiesTests.java | 7 +- ...omikosXAConnectionFactoryWrapperTests.java | 10 +- .../AtomikosXADataSourceWrapperTests.java | 10 +- ...tronixXAConnectionFactoryWrapperTests.java | 10 +- .../BitronixXADataSourceWrapperTests.java | 10 +- .../PoolingConnectionFactoryBeanTests.java | 15 +- .../bitronix/PoolingDataSourceBeanTests.java | 13 +- ...erviceLocatorApplicationListenerTests.java | 5 +- .../SpringPackageScanClassResolverTests.java | 5 +- .../boot/logging/DeferredLogTests.java | 15 +- .../boot/logging/LogFileTests.java | 24 +- ...ngApplicationListenerIntegrationTests.java | 4 +- .../LoggingApplicationListenerTests.java | 86 +++--- .../logging/java/JavaLoggingSystemTests.java | 28 +- .../logging/log4j2/ColorConverterTests.java | 27 +- ...tespaceThrowablePatternConverterTests.java | 10 +- .../log4j2/Log4J2LoggingSystemTests.java | 75 +++-- ...tespaceThrowablePatternConverterTests.java | 11 +- .../logging/logback/ColorConverterTests.java | 25 +- ...hitespaceThrowableProxyConverterTests.java | 10 +- .../logback/LevelRemappingAppenderTests.java | 13 +- .../logback/LogbackLoggingSystemTests.java | 83 +++--- .../SpringBootJoranConfiguratorTests.java | 7 +- ...hitespaceThrowableProxyConverterTests.java | 10 +- .../jpa/EntityManagerFactoryBuilderTests.java | 11 +- .../boot/orm/jpa/EntityScanTests.java | 5 +- .../test/AbstractConfigurationClassTests.java | 5 +- ...ileApplicationContextInitializerTests.java | 5 +- .../boot/test/EnvironmentTestUtilsTests.java | 20 +- ...cationConfigurationActiveProfileTests.java | 7 +- ...onfigurationDefaultConfigurationTests.java | 4 +- ...ConfigurationGroovyConfigurationTests.java | 4 +- ...ionGroovyConventionConfigurationTests.java | 5 +- ...pringApplicationConfigurationJmxTests.java | 4 +- ...nConfigurationMixedConfigurationTests.java | 6 +- ...rationXmlConventionConfigurationTests.java | 5 +- .../SpringApplicationContextLoaderTests.java | 7 +- ...nIntegrationTestPropertyLocationTests.java | 17 +- ...SpringApplicationIntegrationTestTests.java | 13 +- .../test/SpringApplicationMockMvcTests.java | 4 +- ...ingApplicationWebIntegrationTestTests.java | 13 +- .../SpringBootMockServletContextTests.java | 19 +- .../boot/test/TestRestTemplateTests.java | 14 +- ...enceCachingMetadataReaderFactoryTests.java | 7 +- .../ServletComponentScanIntegrationTests.java | 6 +- .../ServletComponentScanRegistrarTests.java | 23 +- .../web/servlet/WebFilterHandlerTests.java | 57 ++-- .../web/servlet/WebServletHandlerTests.java | 41 ++- .../EmbeddedVelocityToolboxViewTests.java | 8 +- .../EmbeddedVelocityViewResolverTests.java | 6 +- .../boot/yaml/ArrayDocumentMatcherTests.java | 12 +- 114 files changed, 1613 insertions(+), 1900 deletions(-) diff --git a/spring-boot/src/test/java/org/springframework/boot/ApplicationPidTests.java b/spring-boot/src/test/java/org/springframework/boot/ApplicationPidTests.java index a6fb25f5e1..ba24d35005 100644 --- a/spring-boot/src/test/java/org/springframework/boot/ApplicationPidTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/ApplicationPidTests.java @@ -26,10 +26,7 @@ import org.junit.rules.TemporaryFolder; import org.springframework.util.FileCopyUtils; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.isEmptyOrNullString; -import static org.hamcrest.Matchers.not; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link ApplicationPid}. @@ -45,12 +42,12 @@ public class ApplicationPidTests { @Test public void toStringWithPid() throws Exception { - assertThat(new ApplicationPid("123").toString(), equalTo("123")); + assertThat(new ApplicationPid("123").toString()).isEqualTo("123"); } @Test public void toStringWithoutPid() throws Exception { - assertThat(new ApplicationPid(null).toString(), equalTo("???")); + assertThat(new ApplicationPid(null).toString()).isEqualTo("???"); } @Test @@ -67,12 +64,12 @@ public class ApplicationPidTests { File file = this.temporaryFolder.newFile(); pid.write(file); String actual = FileCopyUtils.copyToString(new FileReader(file)); - assertThat(actual, equalTo("123")); + assertThat(actual).isEqualTo("123"); } @Test public void getPidFromJvm() throws Exception { - assertThat(new ApplicationPid().toString(), not(isEmptyOrNullString())); + assertThat(new ApplicationPid().toString()).isNotEmpty(); } } diff --git a/spring-boot/src/test/java/org/springframework/boot/ApplicationTempTests.java b/spring-boot/src/test/java/org/springframework/boot/ApplicationTempTests.java index 182c284d52..d42370615a 100644 --- a/spring-boot/src/test/java/org/springframework/boot/ApplicationTempTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/ApplicationTempTests.java @@ -20,10 +20,7 @@ import java.io.File; import org.junit.Test; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.not; -import static org.hamcrest.Matchers.notNullValue; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link ApplicationTemp}. @@ -36,8 +33,8 @@ public class ApplicationTempTests { public void generatesConsistentTemp() throws Exception { ApplicationTemp t1 = new ApplicationTemp(); ApplicationTemp t2 = new ApplicationTemp(); - assertThat(t1.getDir(), notNullValue()); - assertThat(t1.getDir(), equalTo(t2.getDir())); + assertThat(t1.getDir()).isNotNull(); + assertThat(t1.getDir()).isEqualTo(t2.getDir()); } @Test @@ -47,7 +44,7 @@ public class ApplicationTempTests { File t1 = new ApplicationTemp().getDir(); System.setProperty("user.dir", "abc"); File t2 = new ApplicationTemp().getDir(); - assertThat(t1, not(equalTo(t2))); + assertThat(t1).isNotEqualTo(t2); } finally { System.setProperty("user.dir", userDir); @@ -57,7 +54,7 @@ public class ApplicationTempTests { @Test public void getSubDir() throws Exception { ApplicationTemp temp = new ApplicationTemp(); - assertThat(temp.getDir("abc"), equalTo(new File(temp.getDir(), "abc"))); + assertThat(temp.getDir("abc")).isEqualTo(new File(temp.getDir(), "abc")); } } diff --git a/spring-boot/src/test/java/org/springframework/boot/BannerTests.java b/spring-boot/src/test/java/org/springframework/boot/BannerTests.java index 0dc9c1fd4a..86eb658ca3 100644 --- a/spring-boot/src/test/java/org/springframework/boot/BannerTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/BannerTests.java @@ -27,8 +27,7 @@ import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.annotation.Configuration; import org.springframework.core.env.Environment; -import static org.hamcrest.Matchers.containsString; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link Banner} and its usage by {@link SpringApplication}. @@ -55,7 +54,7 @@ public class BannerTests { SpringApplication application = new SpringApplication(Config.class); application.setWebEnvironment(false); this.context = application.run(); - assertThat(this.out.toString(), containsString(":: Spring Boot ::")); + assertThat(this.out.toString()).contains(":: Spring Boot ::"); } @Test @@ -63,7 +62,7 @@ public class BannerTests { SpringApplication application = new SpringApplication(Config.class); application.setWebEnvironment(false); this.context = application.run(); - assertThat(this.out.toString(), containsString(":: Spring Boot ::")); + assertThat(this.out.toString()).contains(":: Spring Boot ::"); } @Test @@ -72,7 +71,7 @@ public class BannerTests { application.setWebEnvironment(false); application.setBanner(new DummyBanner()); this.context = application.run(); - assertThat(this.out.toString(), containsString("My Banner")); + assertThat(this.out.toString()).contains("My Banner"); } static class DummyBanner implements Banner { diff --git a/spring-boot/src/test/java/org/springframework/boot/BeanDefinitionLoaderTests.java b/spring-boot/src/test/java/org/springframework/boot/BeanDefinitionLoaderTests.java index 12b2146279..7bf2d4c052 100644 --- a/spring-boot/src/test/java/org/springframework/boot/BeanDefinitionLoaderTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/BeanDefinitionLoaderTests.java @@ -24,9 +24,7 @@ import org.springframework.boot.sampleconfig.MyComponent; import org.springframework.context.support.StaticApplicationContext; import org.springframework.core.io.ClassPathResource; -import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link BeanDefinitionLoader}. @@ -51,9 +49,8 @@ public class BeanDefinitionLoaderTests { public void loadClass() throws Exception { BeanDefinitionLoader loader = new BeanDefinitionLoader(this.registry, MyComponent.class); - int loaded = loader.load(); - assertThat(loaded, equalTo(1)); - assertTrue(this.registry.containsBean("myComponent")); + assertThat(loader.load()).isEqualTo(1); + assertThat(this.registry.containsBean("myComponent")).isTrue(); } @Test @@ -61,9 +58,8 @@ public class BeanDefinitionLoaderTests { ClassPathResource resource = new ClassPathResource("sample-beans.xml", getClass()); BeanDefinitionLoader loader = new BeanDefinitionLoader(this.registry, resource); - int loaded = loader.load(); - assertThat(loaded, equalTo(1)); - assertTrue(this.registry.containsBean("myXmlComponent")); + assertThat(loader.load()).isEqualTo(1); + assertThat(this.registry.containsBean("myXmlComponent")).isTrue(); } @@ -72,9 +68,8 @@ public class BeanDefinitionLoaderTests { ClassPathResource resource = new ClassPathResource("sample-beans.groovy", getClass()); BeanDefinitionLoader loader = new BeanDefinitionLoader(this.registry, resource); - int loaded = loader.load(); - assertThat(loaded, equalTo(1)); - assertTrue(this.registry.containsBean("myGroovyComponent")); + assertThat(loader.load()).isEqualTo(1); + assertThat(this.registry.containsBean("myGroovyComponent")).isTrue(); } @@ -83,9 +78,8 @@ public class BeanDefinitionLoaderTests { ClassPathResource resource = new ClassPathResource("sample-namespace.groovy", getClass()); BeanDefinitionLoader loader = new BeanDefinitionLoader(this.registry, resource); - int loaded = loader.load(); - assertThat(loaded, equalTo(1)); - assertTrue(this.registry.containsBean("myGroovyComponent")); + assertThat(loader.load()).isEqualTo(1); + assertThat(this.registry.containsBean("myGroovyComponent")).isTrue(); } @@ -93,54 +87,48 @@ public class BeanDefinitionLoaderTests { public void loadPackage() throws Exception { BeanDefinitionLoader loader = new BeanDefinitionLoader(this.registry, MyComponent.class.getPackage()); - int loaded = loader.load(); - assertThat(loaded, equalTo(1)); - assertTrue(this.registry.containsBean("myComponent")); + assertThat(loader.load()).isEqualTo(1); + assertThat(this.registry.containsBean("myComponent")).isTrue(); } @Test public void loadClassName() throws Exception { BeanDefinitionLoader loader = new BeanDefinitionLoader(this.registry, MyComponent.class.getName()); - int loaded = loader.load(); - assertThat(loaded, equalTo(1)); - assertTrue(this.registry.containsBean("myComponent")); + assertThat(loader.load()).isEqualTo(1); + assertThat(this.registry.containsBean("myComponent")).isTrue(); } @Test public void loadResourceName() throws Exception { BeanDefinitionLoader loader = new BeanDefinitionLoader(this.registry, "classpath:org/springframework/boot/sample-beans.xml"); - int loaded = loader.load(); - assertThat(loaded, equalTo(1)); - assertTrue(this.registry.containsBean("myXmlComponent")); + assertThat(loader.load()).isEqualTo(1); + assertThat(this.registry.containsBean("myXmlComponent")).isTrue(); } @Test public void loadGroovyName() throws Exception { BeanDefinitionLoader loader = new BeanDefinitionLoader(this.registry, "classpath:org/springframework/boot/sample-beans.groovy"); - int loaded = loader.load(); - assertThat(loaded, equalTo(1)); - assertTrue(this.registry.containsBean("myGroovyComponent")); + assertThat(loader.load()).isEqualTo(1); + assertThat(this.registry.containsBean("myGroovyComponent")).isTrue(); } @Test public void loadPackageName() throws Exception { BeanDefinitionLoader loader = new BeanDefinitionLoader(this.registry, MyComponent.class.getPackage().getName()); - int loaded = loader.load(); - assertThat(loaded, equalTo(1)); - assertTrue(this.registry.containsBean("myComponent")); + assertThat(loader.load()).isEqualTo(1); + assertThat(this.registry.containsBean("myComponent")).isTrue(); } @Test public void loadPackageAndClassDoesNotDoubleAdd() throws Exception { BeanDefinitionLoader loader = new BeanDefinitionLoader(this.registry, MyComponent.class.getPackage(), MyComponent.class); - int loaded = loader.load(); - assertThat(loaded, equalTo(1)); - assertTrue(this.registry.containsBean("myComponent")); + assertThat(loader.load()).isEqualTo(1); + assertThat(this.registry.containsBean("myComponent")).isTrue(); } } diff --git a/spring-boot/src/test/java/org/springframework/boot/DefaultApplicationArgumentsTests.java b/spring-boot/src/test/java/org/springframework/boot/DefaultApplicationArgumentsTests.java index 2abd056504..91c9cd2ee8 100644 --- a/spring-boot/src/test/java/org/springframework/boot/DefaultApplicationArgumentsTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/DefaultApplicationArgumentsTests.java @@ -17,7 +17,6 @@ package org.springframework.boot; import java.util.Arrays; -import java.util.Collections; import java.util.HashSet; import java.util.Set; @@ -25,8 +24,7 @@ import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; -import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link DefaultApplicationArguments}. @@ -51,47 +49,44 @@ public class DefaultApplicationArgumentsTests { @Test public void getArgs() throws Exception { ApplicationArguments arguments = new DefaultApplicationArguments(ARGS); - assertThat(arguments.getSourceArgs(), equalTo(ARGS)); + assertThat(arguments.getSourceArgs()).isEqualTo(ARGS); } @Test public void optionNames() throws Exception { ApplicationArguments arguments = new DefaultApplicationArguments(ARGS); Set expected = new HashSet(Arrays.asList("foo", "debug")); - assertThat(arguments.getOptionNames(), equalTo(expected)); + assertThat(arguments.getOptionNames()).isEqualTo(expected); } @Test public void containsOption() throws Exception { ApplicationArguments arguments = new DefaultApplicationArguments(ARGS); - assertThat(arguments.containsOption("foo"), equalTo(true)); - assertThat(arguments.containsOption("debug"), equalTo(true)); - assertThat(arguments.containsOption("spring"), equalTo(false)); + assertThat(arguments.containsOption("foo")).isTrue(); + assertThat(arguments.containsOption("debug")).isTrue(); + assertThat(arguments.containsOption("spring")).isFalse(); } @Test public void getOptionValues() throws Exception { ApplicationArguments arguments = new DefaultApplicationArguments(ARGS); - assertThat(arguments.getOptionValues("foo"), - equalTo(Arrays.asList("bar", "baz"))); - assertThat(arguments.getOptionValues("debug"), - equalTo(Collections.emptyList())); - assertThat(arguments.getOptionValues("spring"), equalTo(null)); + assertThat(arguments.getOptionValues("foo")) + .isEqualTo(Arrays.asList("bar", "baz")); + assertThat(arguments.getOptionValues("debug")).isEmpty(); + assertThat(arguments.getOptionValues("spring")).isNull(); } @Test public void getNonOptionArgs() throws Exception { ApplicationArguments arguments = new DefaultApplicationArguments(ARGS); - assertThat(arguments.getNonOptionArgs(), - equalTo(Arrays.asList("spring", "boot"))); + assertThat(arguments.getNonOptionArgs()).containsExactly("spring", "boot"); } @Test public void getNoNonOptionArgs() throws Exception { ApplicationArguments arguments = new DefaultApplicationArguments( new String[] { "--debug" }); - assertThat(arguments.getNonOptionArgs(), - equalTo(Collections.emptyList())); + assertThat(arguments.getNonOptionArgs()).isEmpty(); } } diff --git a/spring-boot/src/test/java/org/springframework/boot/ExitCodeGeneratorsTests.java b/spring-boot/src/test/java/org/springframework/boot/ExitCodeGeneratorsTests.java index 747dea577e..bbed22a8a8 100644 --- a/spring-boot/src/test/java/org/springframework/boot/ExitCodeGeneratorsTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/ExitCodeGeneratorsTests.java @@ -23,8 +23,7 @@ import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; -import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; @@ -55,7 +54,7 @@ public class ExitCodeGeneratorsTests { @Test public void getExitCodeWhenNoGeneratorsShouldReturnZero() throws Exception { - assertThat(new ExitCodeGenerators().getExitCode(), equalTo(0)); + assertThat(new ExitCodeGenerators().getExitCode()).isEqualTo(0); } @Test @@ -64,7 +63,7 @@ public class ExitCodeGeneratorsTests { given(generator.getExitCode()).willThrow(new IllegalStateException()); ExitCodeGenerators generators = new ExitCodeGenerators(); generators.add(generator); - assertThat(generators.getExitCode(), equalTo(1)); + assertThat(generators.getExitCode()).isEqualTo(1); } @Test @@ -73,7 +72,7 @@ public class ExitCodeGeneratorsTests { generators.add(mockGenerator(-1)); generators.add(mockGenerator(-3)); generators.add(mockGenerator(-2)); - assertThat(generators.getExitCode(), equalTo(-3)); + assertThat(generators.getExitCode()).isEqualTo(-3); } @Test @@ -82,7 +81,7 @@ public class ExitCodeGeneratorsTests { generators.add(mockGenerator(1)); generators.add(mockGenerator(3)); generators.add(mockGenerator(2)); - assertThat(generators.getExitCode(), equalTo(3)); + assertThat(generators.getExitCode()).isEqualTo(3); } @Test @@ -93,7 +92,7 @@ public class ExitCodeGeneratorsTests { generators.add(e, mockMapper(IllegalStateException.class, 1)); generators.add(e, mockMapper(IOException.class, 2)); generators.add(e, mockMapper(UnsupportedOperationException.class, 3)); - assertThat(generators.getExitCode(), equalTo(2)); + assertThat(generators.getExitCode()).isEqualTo(2); } private ExitCodeGenerator mockGenerator(int exitCode) { diff --git a/spring-boot/src/test/java/org/springframework/boot/OverrideSourcesTests.java b/spring-boot/src/test/java/org/springframework/boot/OverrideSourcesTests.java index ec5072228a..f3e059f7b0 100644 --- a/spring-boot/src/test/java/org/springframework/boot/OverrideSourcesTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/OverrideSourcesTests.java @@ -25,7 +25,7 @@ import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Primary; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link SpringApplication} {@link SpringApplication#setSources(java.util.Set) @@ -48,7 +48,7 @@ public class OverrideSourcesTests { public void beanInjectedToMainConfiguration() { this.context = SpringApplication.run(new Object[] { MainConfiguration.class }, new String[] { "--spring.main.web_environment=false" }); - assertEquals("foo", this.context.getBean(Service.class).bean.name); + assertThat(this.context.getBean(Service.class).bean.name).isEqualTo("foo"); } @Test @@ -57,7 +57,7 @@ public class OverrideSourcesTests { new Object[] { MainConfiguration.class, TestConfiguration.class }, new String[] { "--spring.main.web_environment=false", "--spring.main.sources=org.springframework.boot.OverrideSourcesTests.MainConfiguration" }); - assertEquals("bar", this.context.getBean(Service.class).bean.name); + assertThat(this.context.getBean(Service.class).bean.name).isEqualTo("bar"); } @Configuration diff --git a/spring-boot/src/test/java/org/springframework/boot/ReproTests.java b/spring-boot/src/test/java/org/springframework/boot/ReproTests.java index 06adcc975c..c7bd2ffab6 100644 --- a/spring-boot/src/test/java/org/springframework/boot/ReproTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/ReproTests.java @@ -22,8 +22,7 @@ import org.junit.Test; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.annotation.Configuration; -import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests to reproduce reported issues. @@ -51,8 +50,8 @@ public class ReproTests { this.context = application.run( "--spring.config.name=enableprofileviaapplicationproperties", "--spring.profiles.active=dev"); - assertThat(this.context.getEnvironment().acceptsProfiles("dev"), equalTo(true)); - assertThat(this.context.getEnvironment().acceptsProfiles("a"), equalTo(true)); + assertThat(this.context.getEnvironment().acceptsProfiles("dev")).isTrue(); + assertThat(this.context.getEnvironment().acceptsProfiles("a")).isTrue(); } @Test @@ -167,10 +166,10 @@ public class ReproTests { private void assertVersionProperty(ConfigurableApplicationContext context, String expectedVersion, String... expectedActiveProfiles) { - assertThat(context.getEnvironment().getActiveProfiles(), - equalTo(expectedActiveProfiles)); - assertThat("version mismatch", context.getEnvironment().getProperty("version"), - equalTo(expectedVersion)); + assertThat(context.getEnvironment().getActiveProfiles()) + .isEqualTo(expectedActiveProfiles); + assertThat(context.getEnvironment().getProperty("version")).as("version mismatch") + .isEqualTo(expectedVersion); context.close(); } diff --git a/spring-boot/src/test/java/org/springframework/boot/ResourceBannerTests.java b/spring-boot/src/test/java/org/springframework/boot/ResourceBannerTests.java index 423cfea901..f948e45506 100644 --- a/spring-boot/src/test/java/org/springframework/boot/ResourceBannerTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/ResourceBannerTests.java @@ -32,8 +32,7 @@ import org.springframework.core.io.ByteArrayResource; import org.springframework.core.io.Resource; import org.springframework.mock.env.MockEnvironment; -import static org.hamcrest.Matchers.startsWith; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link ResourceBanner}. @@ -53,7 +52,7 @@ public class ResourceBannerTests { Resource resource = new ByteArrayResource( "banner ${a} ${spring-boot.version} ${application.version}".getBytes()); String banner = printBanner(resource, "10.2", "2.0", null); - assertThat(banner, startsWith("banner 1 10.2 2.0")); + assertThat(banner).startsWith("banner 1 10.2 2.0"); } @Test @@ -61,7 +60,7 @@ public class ResourceBannerTests { Resource resource = new ByteArrayResource( "banner ${a} ${spring-boot.version} ${application.version}".getBytes()); String banner = printBanner(resource, null, null, null); - assertThat(banner, startsWith("banner 1 ")); + assertThat(banner).startsWith("banner 1 "); } @Test @@ -70,7 +69,7 @@ public class ResourceBannerTests { "banner ${a}${spring-boot.formatted-version}${application.formatted-version}" .getBytes()); String banner = printBanner(resource, "10.2", "2.0", null); - assertThat(banner, startsWith("banner 1 (v10.2) (v2.0)")); + assertThat(banner).startsWith("banner 1 (v10.2) (v2.0)"); } @Test @@ -79,7 +78,7 @@ public class ResourceBannerTests { "banner ${a}${spring-boot.formatted-version}${application.formatted-version}" .getBytes()); String banner = printBanner(resource, null, null, null); - assertThat(banner, startsWith("banner 1")); + assertThat(banner).startsWith("banner 1"); } @Test @@ -88,7 +87,7 @@ public class ResourceBannerTests { "${Ansi.RED}This is red.${Ansi.NORMAL}".getBytes()); AnsiOutput.setEnabled(AnsiOutput.Enabled.ALWAYS); String banner = printBanner(resource, null, null, null); - assertThat(banner, startsWith("\u001B[31mThis is red.\u001B[0m")); + assertThat(banner).startsWith("\u001B[31mThis is red.\u001B[0m"); } @Test @@ -97,7 +96,7 @@ public class ResourceBannerTests { "${Ansi.RED}This is red.${Ansi.NORMAL}".getBytes()); AnsiOutput.setEnabled(AnsiOutput.Enabled.NEVER); String banner = printBanner(resource, null, null, null); - assertThat(banner, startsWith("This is red.")); + assertThat(banner).startsWith("This is red."); } @Test @@ -105,7 +104,7 @@ public class ResourceBannerTests { Resource resource = new ByteArrayResource( "banner ${application.title} ${a}".getBytes()); String banner = printBanner(resource, null, null, "title"); - assertThat(banner, startsWith("banner title 1")); + assertThat(banner).startsWith("banner title 1"); } @Test @@ -113,7 +112,7 @@ public class ResourceBannerTests { Resource resource = new ByteArrayResource( "banner ${application.title} ${a}".getBytes()); String banner = printBanner(resource, null, null, null); - assertThat(banner, startsWith("banner 1")); + assertThat(banner).startsWith("banner 1"); } private String printBanner(Resource resource, String bootVersion, diff --git a/spring-boot/src/test/java/org/springframework/boot/SimpleMainTests.java b/spring-boot/src/test/java/org/springframework/boot/SimpleMainTests.java index 58fd4a9c9f..f942f6b3f7 100644 --- a/spring-boot/src/test/java/org/springframework/boot/SimpleMainTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/SimpleMainTests.java @@ -28,7 +28,7 @@ import org.springframework.context.annotation.Configuration; import org.springframework.util.ClassUtils; import org.springframework.util.StringUtils; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link SpringApplication} main method. @@ -46,33 +46,33 @@ public class SimpleMainTests { @Test(expected = IllegalArgumentException.class) public void emptyApplicationContext() throws Exception { SpringApplication.main(getArgs()); - assertTrue(getOutput().contains(SPRING_STARTUP)); + assertThat(getOutput()).contains(SPRING_STARTUP); } @Test public void basePackageScan() throws Exception { SpringApplication .main(getArgs(ClassUtils.getPackageName(getClass()) + ".sampleconfig")); - assertTrue(getOutput().contains(SPRING_STARTUP)); + assertThat(getOutput()).contains(SPRING_STARTUP); } @Test public void configClassContext() throws Exception { SpringApplication.main(getArgs(getClass().getName())); - assertTrue(getOutput().contains(SPRING_STARTUP)); + assertThat(getOutput()).contains(SPRING_STARTUP); } @Test public void xmlContext() throws Exception { SpringApplication.main(getArgs("org/springframework/boot/sample-beans.xml")); - assertTrue(getOutput().contains(SPRING_STARTUP)); + assertThat(getOutput()).contains(SPRING_STARTUP); } @Test public void mixedContext() throws Exception { SpringApplication.main(getArgs(getClass().getName(), "org/springframework/boot/sample-beans.xml")); - assertTrue(getOutput().contains(SPRING_STARTUP)); + assertThat(getOutput()).contains(SPRING_STARTUP); } private String[] getArgs(String... args) { diff --git a/spring-boot/src/test/java/org/springframework/boot/SpringApplicationTests.java b/spring-boot/src/test/java/org/springframework/boot/SpringApplicationTests.java index b65cd6ce2b..c4bd255537 100644 --- a/spring-boot/src/test/java/org/springframework/boot/SpringApplicationTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/SpringApplicationTests.java @@ -26,6 +26,7 @@ import java.util.concurrent.atomic.AtomicReference; import javax.annotation.PostConstruct; +import org.assertj.core.api.Condition; import org.junit.After; import org.junit.Before; import org.junit.Rule; @@ -70,21 +71,7 @@ import org.springframework.core.io.ResourceLoader; import org.springframework.util.StringUtils; import org.springframework.web.context.support.StandardServletEnvironment; -import static org.hamcrest.Matchers.containsString; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.hasItem; -import static org.hamcrest.Matchers.instanceOf; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.isA; -import static org.hamcrest.Matchers.not; -import static org.hamcrest.Matchers.sameInstance; -import static org.hamcrest.Matchers.startsWith; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.fail; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyObject; @@ -190,7 +177,7 @@ public class SpringApplicationTests { SpringApplication application = spy(new SpringApplication(ExampleConfig.class)); application.setWebEnvironment(false); this.context = application.run("--banner.location=classpath:test-banner.txt"); - assertThat(this.output.toString(), startsWith("Running a Test!")); + assertThat(this.output.toString()).startsWith("Running a Test!"); } @Test @@ -200,8 +187,8 @@ public class SpringApplicationTests { this.context = application.run( "--banner.location=classpath:test-banner-with-placeholder.txt", "--test.property=123456"); - assertThat(this.output.toString(), - startsWith(String.format("Running a Test!%n%n123456"))); + assertThat(this.output.toString()) + .startsWith(String.format("Running a Test!%n%n123456")); } @Test @@ -209,8 +196,8 @@ public class SpringApplicationTests { SpringApplication application = new SpringApplication(ExampleConfig.class); application.setWebEnvironment(false); this.context = application.run(); - assertThat(this.output.toString(), containsString( - "No active profile set, falling back to default profiles: default")); + assertThat(this.output.toString()).contains( + "No active profile set, falling back to default profiles: default"); } @Test @@ -218,8 +205,8 @@ public class SpringApplicationTests { SpringApplication application = new SpringApplication(ExampleConfig.class); application.setWebEnvironment(false); this.context = application.run("--spring.profiles.active=myprofiles"); - assertThat(this.output.toString(), - containsString("The following profiles are active: myprofile")); + assertThat(this.output.toString()) + .contains("The following profiles are active: myprofile"); } @Test @@ -228,7 +215,7 @@ public class SpringApplicationTests { application.setWebEnvironment(false); this.context = application.run("--spring.main.banner-mode=log"); verify(application, atLeastOnce()).setBannerMode(Banner.Mode.LOG); - assertThat(this.output.toString(), containsString("o.s.boot.SpringApplication")); + assertThat(this.output.toString()).contains("o.s.boot.SpringApplication"); } @Test @@ -236,7 +223,7 @@ public class SpringApplicationTests { SpringApplication application = new SpringApplication(ExampleConfig.class); application.setWebEnvironment(false); this.context = application.run("--spring.application.name=foo"); - assertThat(this.context.getId(), startsWith("foo")); + assertThat(this.context.getId()).startsWith("foo"); } @Test @@ -244,7 +231,7 @@ public class SpringApplicationTests { SpringApplication application = new SpringApplication(ExampleConfig.class); application.setApplicationContextClass(StaticApplicationContext.class); this.context = application.run(); - assertThat(this.context, instanceOf(StaticApplicationContext.class)); + assertThat(this.context).isInstanceOf(StaticApplicationContext.class); } @Test @@ -260,9 +247,9 @@ public class SpringApplicationTests { } })); this.context = application.run("--foo=bar"); - assertThat(this.context, sameInstance(reference.get())); + assertThat(this.context).isSameAs(reference.get()); // Custom initializers do not switch off the defaults - assertThat(getEnvironment().getProperty("foo"), equalTo("bar")); + assertThat(getEnvironment().getProperty("foo")).isEqualTo("bar"); } @Test @@ -279,7 +266,7 @@ public class SpringApplicationTests { } application.addListeners(new ApplicationReadyEventListener()); this.context = application.run("--foo=bar"); - assertThat(application, sameInstance(reference.get())); + assertThat(application).isSameAs(reference.get()); } @Test @@ -295,9 +282,9 @@ public class SpringApplicationTests { } application.setListeners(Arrays.asList(new InitializerListener())); this.context = application.run("--foo=bar"); - assertThat(this.context, sameInstance(reference.get())); + assertThat(this.context).isSameAs(reference.get()); // Custom initializers do not switch off the defaults - assertThat(getEnvironment().getProperty("foo"), equalTo("bar")); + assertThat(getEnvironment().getProperty("foo")).isEqualTo("bar"); } @Test @@ -314,13 +301,12 @@ public class SpringApplicationTests { } application.addListeners(new ApplicationRunningEventListener()); this.context = application.run(); - assertThat(5, is(events.size())); - assertThat(events.get(0), is(instanceOf(ApplicationStartedEvent.class))); - assertThat(events.get(1), - is(instanceOf(ApplicationEnvironmentPreparedEvent.class))); - assertThat(events.get(2), is(instanceOf(ApplicationPreparedEvent.class))); - assertThat(events.get(3), is(instanceOf(ContextRefreshedEvent.class))); - assertThat(events.get(4), is(instanceOf(ApplicationReadyEvent.class))); + assertThat(events).hasSize(5); + assertThat(events.get(0)).isInstanceOf(ApplicationStartedEvent.class); + assertThat(events.get(1)).isInstanceOf(ApplicationEnvironmentPreparedEvent.class); + assertThat(events.get(2)).isInstanceOf(ApplicationPreparedEvent.class); + assertThat(events.get(3)).isInstanceOf(ContextRefreshedEvent.class); + assertThat(events.get(4)).isInstanceOf(ApplicationReadyEvent.class); } @Test @@ -328,7 +314,7 @@ public class SpringApplicationTests { SpringApplication application = new SpringApplication(ExampleConfig.class); application.setWebEnvironment(false); this.context = application.run(); - assertThat(this.context, instanceOf(AnnotationConfigApplicationContext.class)); + assertThat(this.context).isInstanceOf(AnnotationConfigApplicationContext.class); } @Test @@ -336,8 +322,8 @@ public class SpringApplicationTests { SpringApplication application = new SpringApplication(ExampleWebConfig.class); application.setWebEnvironment(true); this.context = application.run(); - assertThat(this.context, - instanceOf(AnnotationConfigEmbeddedWebApplicationContext.class)); + assertThat(this.context) + .isInstanceOf(AnnotationConfigEmbeddedWebApplicationContext.class); } @Test @@ -379,10 +365,9 @@ public class SpringApplicationTests { application.setBeanNameGenerator(beanNameGenerator); this.context = application.run(); verify(application.getLoader()).setBeanNameGenerator(beanNameGenerator); - assertThat( - this.context - .getBean(AnnotationConfigUtils.CONFIGURATION_BEAN_NAME_GENERATOR), - sameInstance((Object) beanNameGenerator)); + Object bean = this.context + .getBean(AnnotationConfigUtils.CONFIGURATION_BEAN_NAME_GENERATOR); + assertThat(bean).isSameAs(beanNameGenerator); } @Test @@ -392,8 +377,8 @@ public class SpringApplicationTests { ConfigurableEnvironment environment = new StandardEnvironment(); application.setEnvironment(environment); this.context = application.run("--foo=bar"); - assertTrue(hasPropertySource(environment, CommandLinePropertySource.class, - "commandLineArgs")); + assertThat(environment).has(matchingPropertySource( + CommandLinePropertySource.class, "commandLineArgs")); } @Test @@ -405,11 +390,11 @@ public class SpringApplicationTests { Collections.singletonMap("foo", "original"))); application.setEnvironment(environment); this.context = application.run("--foo=bar", "--bar=foo"); - assertTrue(hasPropertySource(environment, CompositePropertySource.class, - "commandLineArgs")); - assertEquals("foo", environment.getProperty("bar")); + assertThat(environment).has( + matchingPropertySource(CompositePropertySource.class, "commandLineArgs")); + assertThat(environment.getProperty("bar")).isEqualTo("foo"); // New command line properties take precedence - assertEquals("bar", environment.getProperty("foo")); + assertThat(environment.getProperty("foo")).isEqualTo("bar"); } @Test @@ -419,7 +404,7 @@ public class SpringApplicationTests { ConfigurableEnvironment environment = new StandardEnvironment(); application.setEnvironment(environment); this.context = application.run(); - assertEquals("bucket", environment.getProperty("foo")); + assertThat(environment.getProperty("foo")).isEqualTo("bucket"); } @Test @@ -430,7 +415,7 @@ public class SpringApplicationTests { ConfigurableEnvironment environment = new StandardEnvironment(); application.setEnvironment(environment); this.context = application.run(); - assertTrue(environment.acceptsProfiles("foo")); + assertThat(environment.acceptsProfiles("foo")).isTrue(); } @Test @@ -442,8 +427,7 @@ public class SpringApplicationTests { application.setEnvironment(environment); this.context = application.run("--spring.profiles.active=bar,spam"); // Command line should always come last - assertArrayEquals(new String[] { "foo", "bar", "spam" }, - environment.getActiveProfiles()); + assertThat(environment.getActiveProfiles()).containsExactly("foo", "bar", "spam"); } @Test @@ -455,7 +439,8 @@ public class SpringApplicationTests { application.setEnvironment(environment); this.context = application.run(); // Active profile should win over default - assertEquals("fromotherpropertiesfile", environment.getProperty("my.property")); + assertThat(environment.getProperty("my.property")) + .isEqualTo("fromotherpropertiesfile"); } @Test @@ -465,7 +450,7 @@ public class SpringApplicationTests { ConfigurableEnvironment environment = new StandardEnvironment(); application.setEnvironment(environment); this.context = application.run(); - assertEquals("bucket", environment.getProperty("foo")); + assertThat(environment.getProperty("foo")).isEqualTo("bucket"); } @Test @@ -476,8 +461,8 @@ public class SpringApplicationTests { ConfigurableEnvironment environment = new StandardEnvironment(); application.setEnvironment(environment); this.context = application.run("--foo=bar"); - assertFalse( - hasPropertySource(environment, PropertySource.class, "commandLineArgs")); + assertThat(environment).doesNotHave( + matchingPropertySource(PropertySource.class, "commandLineArgs")); } @Test @@ -485,9 +470,9 @@ public class SpringApplicationTests { SpringApplication application = new SpringApplication(CommandLineRunConfig.class); application.setWebEnvironment(false); this.context = application.run("arg"); - assertTrue(this.context.getBean("runnerA", TestCommandLineRunner.class).hasRun()); - assertTrue(this.context.getBean("runnerB", TestApplicationRunner.class).hasRun()); - assertTrue(this.context.getBean("runnerC", TestCommandLineRunner.class).hasRun()); + assertThat(this.context).has(runTestRunnerBean("runnerA")); + assertThat(this.context).has(runTestRunnerBean("runnerB")); + assertThat(this.context).has(runTestRunnerBean("runnerC")); } @Test @@ -498,7 +483,7 @@ public class SpringApplicationTests { application.setUseMockLoader(true); this.context = application.run(); Set initialSources = application.getSources(); - assertThat(initialSources.toArray(), equalTo(sources)); + assertThat(initialSources.toArray()).isEqualTo(sources); } @Test @@ -513,14 +498,14 @@ public class SpringApplicationTests { @Test public void run() throws Exception { this.context = SpringApplication.run(ExampleWebConfig.class); - assertNotNull(this.context); + assertThat(this.context).isNotNull(); } @Test public void runComponents() throws Exception { this.context = SpringApplication.run( new Object[] { ExampleWebConfig.class, Object.class }, new String[0]); - assertNotNull(this.context); + assertThat(this.context).isNotNull(); } @Test @@ -528,8 +513,8 @@ public class SpringApplicationTests { SpringApplication application = new SpringApplication(ExampleConfig.class); application.setWebEnvironment(false); this.context = application.run(); - assertNotNull(this.context); - assertEquals(0, SpringApplication.exit(this.context)); + assertThat(this.context).isNotNull(); + assertThat(SpringApplication.exit(this.context)).isEqualTo(0); } @Test @@ -539,16 +524,16 @@ public class SpringApplicationTests { application.addListeners(listener); application.setWebEnvironment(false); this.context = application.run(); - assertNotNull(this.context); - assertEquals(2, SpringApplication.exit(this.context, new ExitCodeGenerator() { + assertThat(this.context).isNotNull(); + assertThat(SpringApplication.exit(this.context, new ExitCodeGenerator() { @Override public int getExitCode() { return 2; } - })); - assertThat(listener.getExitCode(), equalTo(2)); + })).isEqualTo(2); + assertThat(listener.getExitCode()).isEqualTo(2); } @Test @@ -573,7 +558,7 @@ public class SpringApplicationTests { catch (IllegalStateException ex) { } verify(handler).registerExitCode(11); - assertThat(listener.getExitCode(), equalTo(11)); + assertThat(listener.getExitCode()).isEqualTo(11); } @Test @@ -598,7 +583,7 @@ public class SpringApplicationTests { catch (IllegalStateException ex) { } verify(handler).registerExitCode(11); - assertThat(listener.getExitCode(), equalTo(11)); + assertThat(listener.getExitCode()).isEqualTo(11); } @Test @@ -623,7 +608,7 @@ public class SpringApplicationTests { catch (RuntimeException ex) { } verify(handler).registerLoggedException(any(RefreshFailureException.class)); - assertThat(this.output.toString(), not(containsString("NullPointerException"))); + assertThat(this.output.toString()).doesNotContain("NullPointerException"); } @Test @@ -633,9 +618,9 @@ public class SpringApplicationTests { new String[] { "baz=", "bar=spam" }, "=")); application.setWebEnvironment(false); this.context = application.run("--bar=foo", "bucket", "crap"); - assertThat(this.context, instanceOf(AnnotationConfigApplicationContext.class)); - assertThat(getEnvironment().getProperty("bar"), equalTo("foo")); - assertThat(getEnvironment().getProperty("baz"), equalTo("")); + assertThat(this.context).isInstanceOf(AnnotationConfigApplicationContext.class); + assertThat(getEnvironment().getProperty("bar")).isEqualTo("foo"); + assertThat(getEnvironment().getProperty("baz")).isEqualTo(""); } @Test @@ -644,7 +629,7 @@ public class SpringApplicationTests { ExampleConfig.class); application.setWebEnvironment(false); this.context = application.run("--spring.main.banner-mode=OFF"); - assertThat(application.getBannerMode(), is(Banner.Mode.OFF)); + assertThat(application.getBannerMode()).isEqualTo(Banner.Mode.OFF); } @Test @@ -668,8 +653,8 @@ public class SpringApplicationTests { } }); this.context = application.run(); - assertThat(events, hasItem(isA(ApplicationPreparedEvent.class))); - assertThat(events, hasItem(isA(ContextRefreshedEvent.class))); + assertThat(events).hasAtLeastOneElementOfType(ApplicationPreparedEvent.class); + assertThat(events).hasAtLeastOneElementOfType(ContextRefreshedEvent.class); } @Test @@ -685,8 +670,8 @@ public class SpringApplicationTests { } }); this.context = application.run(); - assertThat(events, hasItem(isA(ApplicationPreparedEvent.class))); - assertThat(events, hasItem(isA(ContextRefreshedEvent.class))); + assertThat(events).hasAtLeastOneElementOfType(ApplicationPreparedEvent.class); + assertThat(events).hasAtLeastOneElementOfType(ContextRefreshedEvent.class); } @Test @@ -706,7 +691,7 @@ public class SpringApplicationTests { ExampleConfig.class); application.setWebEnvironment(false); this.context = application.run(); - assertThat(System.getProperty("java.awt.headless"), equalTo("true")); + assertThat(System.getProperty("java.awt.headless")).isEqualTo("true"); } @Test @@ -716,7 +701,7 @@ public class SpringApplicationTests { application.setWebEnvironment(false); application.setHeadless(false); this.context = application.run(); - assertThat(System.getProperty("java.awt.headless"), equalTo("false")); + assertThat(System.getProperty("java.awt.headless")).isEqualTo("false"); } @Test @@ -726,7 +711,7 @@ public class SpringApplicationTests { ExampleConfig.class); application.setWebEnvironment(false); this.context = application.run(); - assertThat(System.getProperty("java.awt.headless"), equalTo("false")); + assertThat(System.getProperty("java.awt.headless")).isEqualTo("false"); } @Test @@ -736,8 +721,8 @@ public class SpringApplicationTests { application.setWebEnvironment(false); this.context = application.run("--debug", "spring", "boot"); ApplicationArguments args = this.context.getBean(ApplicationArguments.class); - assertThat(args.getNonOptionArgs(), equalTo(Arrays.asList("spring", "boot"))); - assertThat(args.containsOption("debug"), equalTo(true)); + assertThat(args.getNonOptionArgs()).containsExactly("spring", "boot"); + assertThat(args.containsOption("debug")).isTrue(); } @Test @@ -750,8 +735,8 @@ public class SpringApplicationTests { @Override public void onApplicationEvent( ApplicationEnvironmentPreparedEvent event) { - assertTrue(event - .getEnvironment() instanceof StandardServletEnvironment); + assertThat(event.getEnvironment()) + .isInstanceOf(StandardServletEnvironment.class); EnvironmentTestUtils.addEnvironment(event.getEnvironment(), "foo=bar"); event.getSpringApplication().setWebEnvironment(false); @@ -759,10 +744,11 @@ public class SpringApplicationTests { }); this.context = application.run(); - assertFalse(this.context.getEnvironment() instanceof StandardServletEnvironment); - assertEquals("bar", this.context.getEnvironment().getProperty("foo")); - assertEquals("test", this.context.getEnvironment().getPropertySources().iterator() - .next().getName()); + assertThat(this.context.getEnvironment()) + .isNotInstanceOf(StandardServletEnvironment.class); + assertThat(this.context.getEnvironment().getProperty("foo")); + assertThat(this.context.getEnvironment().getPropertySources().iterator().next() + .getName()).isEqualTo("test"); } @Test @@ -781,18 +767,37 @@ public class SpringApplicationTests { thread.join(6000); int occurrences = StringUtils.countOccurrencesOf(this.output.toString(), "Caused by: java.lang.RuntimeException: ExpectedError"); - assertThat("Expected single stacktrace", occurrences, equalTo(1)); + assertThat(occurrences).as("Expected single stacktrace").isEqualTo(1); } - private boolean hasPropertySource(ConfigurableEnvironment environment, - Class propertySourceClass, String name) { - for (PropertySource source : environment.getPropertySources()) { - if (propertySourceClass.isInstance(source) - && (name == null || name.equals(source.getName()))) { - return true; + private Condition matchingPropertySource( + final Class propertySourceClass, final String name) { + return new Condition("has property source") { + + @Override + public boolean matches(ConfigurableEnvironment value) { + for (PropertySource source : value.getPropertySources()) { + if (propertySourceClass.isInstance(source) + && (name == null || name.equals(source.getName()))) { + return true; + } + } + return false; } - } - return false; + + }; + } + + private Condition runTestRunnerBean( + final String name) { + return new Condition("run testrunner bean") { + + @Override + public boolean matches(ConfigurableApplicationContext value) { + return value.getBean(name, AbstractTestRunner.class).hasRun(); + } + + }; } @Configuration @@ -1031,7 +1036,7 @@ public class SpringApplicationTests { for (String name : this.expectedBefore) { AbstractTestRunner bean = this.applicationContext.getBean(name, AbstractTestRunner.class); - assertTrue(bean.hasRun()); + assertThat(bean.hasRun()).isTrue(); } } diff --git a/spring-boot/src/test/java/org/springframework/boot/StartUpLoggerTests.java b/spring-boot/src/test/java/org/springframework/boot/StartUpLoggerTests.java index 1af849dfea..b9c4938b4c 100644 --- a/spring-boot/src/test/java/org/springframework/boot/StartUpLoggerTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/StartUpLoggerTests.java @@ -19,7 +19,7 @@ package org.springframework.boot; import org.apache.commons.logging.impl.SimpleLog; import org.junit.Test; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link StartupInfoLogger}. @@ -41,8 +41,8 @@ public class StartUpLoggerTests { @Test public void sourceClassIncluded() { new StartupInfoLogger(getClass()).logStarting(this.log); - assertTrue("Wrong output: " + this.output, this.output.toString() - .contains("Starting " + getClass().getSimpleName())); + assertThat(this.output.toString()) + .contains("Starting " + getClass().getSimpleName()); } } diff --git a/spring-boot/src/test/java/org/springframework/boot/admin/SpringApplicationAdminMXBeanRegistrarTests.java b/spring-boot/src/test/java/org/springframework/boot/admin/SpringApplicationAdminMXBeanRegistrarTests.java index 7db1fb689d..c73dd11873 100644 --- a/spring-boot/src/test/java/org/springframework/boot/admin/SpringApplicationAdminMXBeanRegistrarTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/admin/SpringApplicationAdminMXBeanRegistrarTests.java @@ -36,9 +36,7 @@ import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.event.ContextRefreshedEvent; -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.CoreMatchers.nullValue; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link SpringApplicationAdminMXBeanRegistrar}. @@ -77,7 +75,7 @@ public class SpringApplicationAdminMXBeanRegistrarTests { @Override public void onApplicationEvent(ContextRefreshedEvent event) { try { - assertThat(isApplicationReady(objectName), is(false)); + assertThat(isApplicationReady(objectName)).isFalse(); } catch (Exception ex) { throw new IllegalStateException( @@ -86,7 +84,7 @@ public class SpringApplicationAdminMXBeanRegistrarTests { } }); this.context = application.run(); - assertThat(isApplicationReady(objectName), is(true)); + assertThat(isApplicationReady(objectName)).isTrue(); } @Test @@ -95,10 +93,10 @@ public class SpringApplicationAdminMXBeanRegistrarTests { SpringApplication application = new SpringApplication(Config.class); application.setWebEnvironment(false); this.context = application.run("--foo.bar=blam"); - assertThat(isApplicationReady(objectName), is(true)); - assertThat(isApplicationEmbeddedWebApplication(objectName), is(false)); - assertThat(getProperty(objectName, "foo.bar"), is("blam")); - assertThat(getProperty(objectName, "does.not.exist.test"), is(nullValue())); + assertThat(isApplicationReady(objectName)).isTrue(); + assertThat(isApplicationEmbeddedWebApplication(objectName)).isFalse(); + assertThat(getProperty(objectName, "foo.bar")).isEqualTo("blam"); + assertThat(getProperty(objectName, "does.not.exist.test")).isNull(); } @Test @@ -107,9 +105,9 @@ public class SpringApplicationAdminMXBeanRegistrarTests { SpringApplication application = new SpringApplication(Config.class); application.setWebEnvironment(false); this.context = application.run(); - assertThat(this.context.isRunning(), is(true)); + assertThat(this.context.isRunning()).isTrue(); invokeShutdown(objectName); - assertThat(this.context.isRunning(), is(false)); + assertThat(this.context.isRunning()).isFalse(); this.thrown.expect(InstanceNotFoundException.class); // JMX cleanup this.mBeanServer.getObjectInstance(objectName); } @@ -135,7 +133,7 @@ public class SpringApplicationAdminMXBeanRegistrarTests { private T getAttribute(ObjectName objectName, Class type, String attribute) { try { Object value = this.mBeanServer.getAttribute(objectName, attribute); - assertThat((value == null || type.isInstance(value)), is(true)); + assertThat(value == null || type.isInstance(value)).isTrue(); return type.cast(value); } catch (Exception ex) { diff --git a/spring-boot/src/test/java/org/springframework/boot/ansi/AnsiOutputTests.java b/spring-boot/src/test/java/org/springframework/boot/ansi/AnsiOutputTests.java index 422fa6c7ee..fa9c6ef6fe 100644 --- a/spring-boot/src/test/java/org/springframework/boot/ansi/AnsiOutputTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/ansi/AnsiOutputTests.java @@ -22,8 +22,7 @@ import org.junit.Test; import org.springframework.boot.ansi.AnsiOutput.Enabled; -import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link AnsiOutput}. @@ -46,7 +45,7 @@ public class AnsiOutputTests { public void encoding() throws Exception { String encoded = AnsiOutput.toString("A", AnsiColor.RED, AnsiStyle.BOLD, "B", AnsiStyle.NORMAL, "D", AnsiColor.GREEN, "E", AnsiStyle.FAINT, "F"); - assertThat(encoded, equalTo("ABDEF")); + assertThat(encoded).isEqualTo("ABDEF"); } } diff --git a/spring-boot/src/test/java/org/springframework/boot/ansi/AnsiPropertySourceTests.java b/spring-boot/src/test/java/org/springframework/boot/ansi/AnsiPropertySourceTests.java index 2425e27ba7..9856066487 100644 --- a/spring-boot/src/test/java/org/springframework/boot/ansi/AnsiPropertySourceTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/ansi/AnsiPropertySourceTests.java @@ -21,9 +21,7 @@ import org.junit.Test; import org.springframework.boot.ansi.AnsiOutput.Enabled; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.nullValue; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link AnsiPropertySource}. @@ -41,48 +39,44 @@ public class AnsiPropertySourceTests { @Test public void getAnsiStyle() throws Exception { - assertThat(this.source.getProperty("AnsiStyle.BOLD"), - equalTo((Object) AnsiStyle.BOLD)); + assertThat(this.source.getProperty("AnsiStyle.BOLD")).isEqualTo(AnsiStyle.BOLD); } @Test public void getAnsiColor() throws Exception { - assertThat(this.source.getProperty("AnsiColor.RED"), - equalTo((Object) AnsiColor.RED)); + assertThat(this.source.getProperty("AnsiColor.RED")).isEqualTo(AnsiColor.RED); } @Test public void getAnsiBackground() throws Exception { - assertThat(this.source.getProperty("AnsiBackground.GREEN"), - equalTo((Object) AnsiBackground.GREEN)); + assertThat(this.source.getProperty("AnsiBackground.GREEN")) + .isEqualTo(AnsiBackground.GREEN); } @Test public void getAnsi() throws Exception { - assertThat(this.source.getProperty("Ansi.BOLD"), - equalTo((Object) AnsiStyle.BOLD)); - assertThat(this.source.getProperty("Ansi.RED"), equalTo((Object) AnsiColor.RED)); - assertThat(this.source.getProperty("Ansi.BG_RED"), - equalTo((Object) AnsiBackground.RED)); + assertThat(this.source.getProperty("Ansi.BOLD")).isEqualTo(AnsiStyle.BOLD); + assertThat(this.source.getProperty("Ansi.RED")).isEqualTo(AnsiColor.RED); + assertThat(this.source.getProperty("Ansi.BG_RED")).isEqualTo(AnsiBackground.RED); } @Test public void getMissing() throws Exception { - assertThat(this.source.getProperty("AnsiStyle.NOPE"), nullValue()); + assertThat(this.source.getProperty("AnsiStyle.NOPE")).isNull(); } @Test public void encodeEnabled() throws Exception { AnsiOutput.setEnabled(Enabled.ALWAYS); AnsiPropertySource source = new AnsiPropertySource("ansi", true); - assertThat(source.getProperty("Ansi.RED"), equalTo((Object) "\033[31m")); + assertThat(source.getProperty("Ansi.RED")).isEqualTo("\033[31m"); } @Test public void encodeDisabled() throws Exception { AnsiOutput.setEnabled(Enabled.NEVER); AnsiPropertySource source = new AnsiPropertySource("ansi", true); - assertThat(source.getProperty("Ansi.RED"), equalTo((Object) "")); + assertThat(source.getProperty("Ansi.RED")).isEqualTo(""); } } diff --git a/spring-boot/src/test/java/org/springframework/boot/bind/BindingPreparationTests.java b/spring-boot/src/test/java/org/springframework/boot/bind/BindingPreparationTests.java index c4748ecabb..30a304b160 100644 --- a/spring-boot/src/test/java/org/springframework/boot/bind/BindingPreparationTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/bind/BindingPreparationTests.java @@ -32,9 +32,7 @@ import org.springframework.expression.Expression; import org.springframework.expression.spel.standard.SpelExpressionParser; import org.springframework.expression.spel.support.StandardEvaluationContext; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Dave Syer @@ -48,7 +46,7 @@ public class BindingPreparationTests { wrapper.setAutoGrowNestedPaths(true); // For a nested map, you only have to get an element of it for it to be created wrapper.getPropertyValue("nested[foo]"); - assertNotNull(wrapper.getPropertyValue("nested")); + assertThat(wrapper.getPropertyValue("nested")).isNotNull(); } @Test @@ -59,8 +57,8 @@ public class BindingPreparationTests { // For a nested map, you only have to get an element of it for it to be created wrapper.getPropertyValue("nested[foo]"); wrapper.setPropertyValue("nested[foo].foo", "bar"); - assertNotNull(wrapper.getPropertyValue("nested")); - assertNotNull(wrapper.getPropertyValue("nested[foo]")); + assertThat(wrapper.getPropertyValue("nested")).isNotNull(); + assertThat(wrapper.getPropertyValue("nested[foo]")).isNotNull(); } @Test @@ -70,8 +68,8 @@ public class BindingPreparationTests { wrapper.setAutoGrowNestedPaths(true); RelaxedDataBinder binder = new RelaxedDataBinder(target); binder.normalizePath(wrapper, "nested[0].list[1]"); - assertNotNull(wrapper.getPropertyValue("nested")); - assertNotNull(wrapper.getPropertyValue("nested[0].list[1]")); + assertThat(wrapper.getPropertyValue("nested")).isNotNull(); + assertThat(wrapper.getPropertyValue("nested[0].list[1]")).isNotNull(); } @Test @@ -81,8 +79,8 @@ public class BindingPreparationTests { wrapper.setAutoGrowNestedPaths(true); RelaxedDataBinder binder = new RelaxedDataBinder(target); binder.normalizePath(wrapper, "nested[0]list[1]"); - assertNotNull(wrapper.getPropertyValue("nested")); - assertNotNull(wrapper.getPropertyValue("nested[0].list[1]")); + assertThat(wrapper.getPropertyValue("nested")).isNotNull(); + assertThat(wrapper.getPropertyValue("nested[0].list[1]")).isNotNull(); } @Test @@ -92,9 +90,9 @@ public class BindingPreparationTests { wrapper.setAutoGrowNestedPaths(true); RelaxedDataBinder binder = new RelaxedDataBinder(target); String result = binder.normalizePath(wrapper, "NESTED[foo][bar]"); - assertNotNull(wrapper.getPropertyValue("nested")); - assertEquals("nested[foo][bar]", result); - assertNotNull(wrapper.getPropertyValue("nested[foo][bar]")); + assertThat(wrapper.getPropertyValue("nested")).isNotNull(); + assertThat("nested[foo][bar]").isEqualTo(result); + assertThat(wrapper.getPropertyValue("nested[foo][bar]")).isNotNull(); } @Test @@ -104,9 +102,9 @@ public class BindingPreparationTests { wrapper.setAutoGrowNestedPaths(true); RelaxedDataBinder binder = new RelaxedDataBinder(target); String result = binder.normalizePath(wrapper, "nes_ted[foo][bar]"); - assertNotNull(wrapper.getPropertyValue("nested")); - assertEquals("nested[foo][bar]", result); - assertNotNull(wrapper.getPropertyValue("nested[foo][bar]")); + assertThat(wrapper.getPropertyValue("nested")).isNotNull(); + assertThat("nested[foo][bar]").isEqualTo(result); + assertThat(wrapper.getPropertyValue("nested[foo][bar]")).isNotNull(); } @Test @@ -116,9 +114,9 @@ public class BindingPreparationTests { wrapper.setAutoGrowNestedPaths(true); RelaxedDataBinder binder = new RelaxedDataBinder(target); String result = binder.normalizePath(wrapper, "nested[foo][bar]"); - assertNotNull(wrapper.getPropertyValue("nested")); - assertEquals("nested[foo][bar]", result); - assertNotNull(wrapper.getPropertyValue("nested[foo][bar]")); + assertThat(wrapper.getPropertyValue("nested")).isNotNull(); + assertThat("nested[foo][bar]").isEqualTo(result); + assertThat(wrapper.getPropertyValue("nested[foo][bar]")).isNotNull(); } @Test @@ -128,9 +126,9 @@ public class BindingPreparationTests { wrapper.setAutoGrowNestedPaths(true); RelaxedDataBinder binder = new RelaxedDataBinder(target); String result = binder.normalizePath(wrapper, "nested[foo].foo"); - assertNotNull(wrapper.getPropertyValue("nested")); - assertEquals("nested[foo].foo", result); - assertNotNull(wrapper.getPropertyValue("nested[foo]")); + assertThat(wrapper.getPropertyValue("nested")).isNotNull(); + assertThat("nested[foo].foo").isEqualTo(result); + assertThat(wrapper.getPropertyValue("nested[foo]")).isNotNull(); } @Test @@ -140,8 +138,8 @@ public class BindingPreparationTests { wrapper.setAutoGrowNestedPaths(true); RelaxedDataBinder binder = new RelaxedDataBinder(target); String result = binder.normalizePath(wrapper, "nested.foo.foo"); - assertNotNull(wrapper.getPropertyValue("nested")); - assertEquals("nested[foo].foo", result); + assertThat(wrapper.getPropertyValue("nested")).isNotNull(); + assertThat("nested[foo].foo").isEqualTo(result); } @Test @@ -151,8 +149,8 @@ public class BindingPreparationTests { wrapper.setAutoGrowNestedPaths(true); RelaxedDataBinder binder = new RelaxedDataBinder(target); binder.normalizePath(wrapper, "nested[foo][0]"); - assertNotNull(wrapper.getPropertyValue("nested")); - assertNotNull(wrapper.getPropertyValue("nested[foo]")); + assertThat(wrapper.getPropertyValue("nested")).isNotNull(); + assertThat(wrapper.getPropertyValue("nested[foo]")).isNotNull(); } @Test @@ -162,8 +160,8 @@ public class BindingPreparationTests { wrapper.setAutoGrowNestedPaths(true); RelaxedDataBinder binder = new RelaxedDataBinder(target); binder.normalizePath(wrapper, "nested[0][foo]"); - assertNotNull(wrapper.getPropertyValue("nested")); - assertNotNull(wrapper.getPropertyValue("nested[0]")); + assertThat(wrapper.getPropertyValue("nested")).isNotNull(); + assertThat(wrapper.getPropertyValue("nested[0]")).isNotNull(); } @Test @@ -173,8 +171,8 @@ public class BindingPreparationTests { wrapper.setAutoGrowNestedPaths(true); RelaxedDataBinder binder = new RelaxedDataBinder(target); binder.normalizePath(wrapper, "nested[0][1]"); - assertNotNull(wrapper.getPropertyValue("nested")); - assertNotNull(wrapper.getPropertyValue("nested[0][1]")); + assertThat(wrapper.getPropertyValue("nested")).isNotNull(); + assertThat(wrapper.getPropertyValue("nested[0][1]")).isNotNull(); } @Test @@ -191,7 +189,7 @@ public class BindingPreparationTests { wrapper.setPropertyValue("nested[foo]", new ArrayList()); // Then it would have to be actually bound to get the list to auto-grow wrapper.setPropertyValue("nested[foo][0]", "bar"); - assertNotNull(wrapper.getPropertyValue("nested[foo][0]")); + assertThat(wrapper.getPropertyValue("nested[foo][0]")).isNotNull(); } @Test @@ -202,7 +200,7 @@ public class BindingPreparationTests { // For a nested object, you have to set a property for it to be created wrapper.setPropertyValue("nested.foo", "bar"); wrapper.getPropertyValue("nested"); - assertNotNull(wrapper.getPropertyValue("nested")); + assertThat(wrapper.getPropertyValue("nested")).isNotNull(); } @Test @@ -211,13 +209,13 @@ public class BindingPreparationTests { BeanWrapperImpl wrapper = new BeanWrapperImpl(target); wrapper.setAutoGrowNestedPaths(true); TypeDescriptor descriptor = wrapper.getPropertyTypeDescriptor("nested"); - assertTrue(descriptor.isMap()); + assertThat(descriptor.isMap()).isTrue(); wrapper.getPropertyValue("nested[foo]"); - assertNotNull(wrapper.getPropertyValue("nested")); + assertThat(wrapper.getPropertyValue("nested")).isNotNull(); // You also need to bind to a value here wrapper.setPropertyValue("nested[foo][0]", "bar"); wrapper.getPropertyValue("nested[foo][0]"); - assertNotNull(wrapper.getPropertyValue("nested[foo]")); + assertThat(wrapper.getPropertyValue("nested[foo]")).isNotNull(); } @Test @@ -231,7 +229,7 @@ public class BindingPreparationTests { StandardEvaluationContext context = new StandardEvaluationContext(target); context.addPropertyAccessor(new MapAccessor()); Expression expression = parser.parseExpression("nested.foo"); - assertNotNull(expression.getValue(context)); + assertThat(expression.getValue(context)).isNotNull(); } public static class TargetWithNestedMap { diff --git a/spring-boot/src/test/java/org/springframework/boot/bind/ConverterBindingTests.java b/spring-boot/src/test/java/org/springframework/boot/bind/ConverterBindingTests.java index 7d4177e004..0741ba00e8 100644 --- a/spring-boot/src/test/java/org/springframework/boot/bind/ConverterBindingTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/bind/ConverterBindingTests.java @@ -38,8 +38,7 @@ import org.springframework.core.convert.converter.Converter; import org.springframework.core.convert.converter.GenericConverter; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import static org.hamcrest.Matchers.is; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link ConfigurationProperties} binding with custom converters. @@ -63,8 +62,8 @@ public class ConverterBindingTests { @Test public void overridingOfPropertiesOrderOfAtPropertySources() { - assertThat(this.properties.getFoo().name, is(this.foo)); - assertThat(this.properties.getBar().name, is(this.bar)); + assertThat(this.properties.getFoo().name).isEqualTo(this.foo); + assertThat(this.properties.getBar().name).isEqualTo(this.bar); } @Configuration diff --git a/spring-boot/src/test/java/org/springframework/boot/bind/DefaultPropertyNamePatternsMatcherTests.java b/spring-boot/src/test/java/org/springframework/boot/bind/DefaultPropertyNamePatternsMatcherTests.java index 7380119385..5071b14274 100644 --- a/spring-boot/src/test/java/org/springframework/boot/bind/DefaultPropertyNamePatternsMatcherTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/bind/DefaultPropertyNamePatternsMatcherTests.java @@ -18,8 +18,7 @@ package org.springframework.boot.bind; import org.junit.Test; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link DefaultPropertyNamePatternsMatcher}. @@ -32,43 +31,43 @@ public class DefaultPropertyNamePatternsMatcherTests { @Test public void namesShorter() { - assertFalse(new DefaultPropertyNamePatternsMatcher(DELIMITERS, "aaaa", "bbbb") - .matches("zzzzz")); + assertThat(new DefaultPropertyNamePatternsMatcher(DELIMITERS, "aaaa", "bbbb") + .matches("zzzzz")).isFalse(); } @Test public void namesExactMatch() { - assertTrue( + assertThat( new DefaultPropertyNamePatternsMatcher(DELIMITERS, "aaaa", "bbbb", "cccc") - .matches("bbbb")); + .matches("bbbb")).isTrue(); } @Test public void namesLonger() { - assertFalse(new DefaultPropertyNamePatternsMatcher(DELIMITERS, "aaaaa", "bbbbb", - "ccccc").matches("bbbb")); + assertThat(new DefaultPropertyNamePatternsMatcher(DELIMITERS, "aaaaa", "bbbbb", + "ccccc").matches("bbbb")).isFalse(); } @Test public void nameWithDot() throws Exception { - assertTrue( + assertThat( new DefaultPropertyNamePatternsMatcher(DELIMITERS, "aaaa", "bbbb", "cccc") - .matches("bbbb.anything")); + .matches("bbbb.anything")).isTrue(); } @Test public void nameWithUnderscore() throws Exception { - assertTrue( + assertThat( new DefaultPropertyNamePatternsMatcher(DELIMITERS, "aaaa", "bbbb", "cccc") - .matches("bbbb_anything")); + .matches("bbbb_anything")).isTrue(); } @Test public void namesMatchWithDifferentLengths() throws Exception { - assertTrue( + assertThat( new DefaultPropertyNamePatternsMatcher(DELIMITERS, "aaa", "bbbb", "ccccc") - .matches("bbbb")); + .matches("bbbb")).isTrue(); } @Test @@ -76,9 +75,9 @@ public class DefaultPropertyNamePatternsMatcherTests { char[] delimiters = "._[".toCharArray(); PropertyNamePatternsMatcher matcher = new DefaultPropertyNamePatternsMatcher( delimiters, "aaa", "bbbb", "ccccc"); - assertTrue(matcher.matches("bbbb")); - assertTrue(matcher.matches("bbbb[4]")); - assertFalse(matcher.matches("bbb[4]")); + assertThat(matcher.matches("bbbb")).isTrue(); + assertThat(matcher.matches("bbbb[4]")).isTrue(); + assertThat(matcher.matches("bbb[4]")).isFalse(); } } diff --git a/spring-boot/src/test/java/org/springframework/boot/bind/PropertiesConfigurationFactoryMapTests.java b/spring-boot/src/test/java/org/springframework/boot/bind/PropertiesConfigurationFactoryMapTests.java index 0540175999..9d43db1d73 100644 --- a/spring-boot/src/test/java/org/springframework/boot/bind/PropertiesConfigurationFactoryMapTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/bind/PropertiesConfigurationFactoryMapTests.java @@ -31,7 +31,7 @@ import org.springframework.core.io.ByteArrayResource; import org.springframework.core.io.support.PropertiesLoaderUtils; import org.springframework.validation.Validator; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link PropertiesConfigurationFactory} binding to a map. @@ -51,15 +51,15 @@ public class PropertiesConfigurationFactoryMapTests { @Test public void testValidPropertiesLoadsWithNoErrors() throws Exception { Foo foo = createFoo("map.name: blah\nmap.bar: blah"); - assertEquals("blah", foo.map.get("bar")); - assertEquals("blah", foo.map.get("name")); + assertThat(foo.map.get("bar")).isEqualTo("blah"); + assertThat(foo.map.get("name")).isEqualTo("blah"); } @Test public void testBindToNamedTarget() throws Exception { this.targetName = "foo"; Foo foo = createFoo("hi: hello\nfoo.map.name: foo\nfoo.map.bar: blah"); - assertEquals("blah", foo.map.get("bar")); + assertThat(foo.map.get("bar")).isEqualTo("blah"); } @Test @@ -72,7 +72,7 @@ public class PropertiesConfigurationFactoryMapTests { this.factory.setPropertySources(sources); this.factory.afterPropertiesSet(); Foo foo = this.factory.getObject(); - assertEquals("blah", foo.map.get("name")); + assertThat(foo.map.get("name")).isEqualTo("blah"); } @Test @@ -87,7 +87,7 @@ public class PropertiesConfigurationFactoryMapTests { this.factory.setPropertySources(sources); this.factory.afterPropertiesSet(); Foo foo = this.factory.getObject(); - assertEquals("blah", foo.map.get("name")); + assertThat(foo.map.get("name")).isEqualTo("blah"); } private Foo createFoo(final String values) throws Exception { diff --git a/spring-boot/src/test/java/org/springframework/boot/bind/PropertiesConfigurationFactoryParameterizedTests.java b/spring-boot/src/test/java/org/springframework/boot/bind/PropertiesConfigurationFactoryParameterizedTests.java index 2995229341..6937486e01 100644 --- a/spring-boot/src/test/java/org/springframework/boot/bind/PropertiesConfigurationFactoryParameterizedTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/bind/PropertiesConfigurationFactoryParameterizedTests.java @@ -32,7 +32,7 @@ import org.springframework.core.env.PropertiesPropertySource; import org.springframework.core.io.ByteArrayResource; import org.springframework.core.io.support.PropertiesLoaderUtils; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * Parameterized tests for {@link PropertiesConfigurationFactory} @@ -65,36 +65,36 @@ public class PropertiesConfigurationFactoryParameterizedTests { @Test public void testValidPropertiesLoadsWithNoErrors() throws Exception { Foo foo = createFoo("name: blah\nbar: blah"); - assertEquals("blah", foo.bar); - assertEquals("blah", foo.name); + assertThat(foo.bar).isEqualTo("blah"); + assertThat(foo.name).isEqualTo("blah"); } @Test public void testValidPropertiesLoadsWithUpperCase() throws Exception { Foo foo = createFoo("NAME: blah\nbar: blah"); - assertEquals("blah", foo.bar); - assertEquals("blah", foo.name); + assertThat(foo.bar).isEqualTo("blah"); + assertThat(foo.name).isEqualTo("blah"); } @Test public void testUnderscore() throws Exception { Foo foo = createFoo("spring_foo_baz: blah\nname: blah"); - assertEquals("blah", foo.spring_foo_baz); - assertEquals("blah", foo.name); + assertThat(foo.spring_foo_baz).isEqualTo("blah"); + assertThat(foo.name).isEqualTo("blah"); } @Test public void testBindToNamedTarget() throws Exception { this.targetName = "foo"; Foo foo = createFoo("hi: hello\nfoo.name: foo\nfoo.bar: blah"); - assertEquals("blah", foo.bar); + assertThat(foo.bar).isEqualTo("blah"); } @Test public void testBindToNamedTargetUppercaseUnderscores() throws Exception { this.targetName = "foo"; Foo foo = createFoo("FOO_NAME: foo\nFOO_BAR: blah"); - assertEquals("blah", foo.bar); + assertThat(foo.bar).isEqualTo("blah"); } private Foo createFoo(final String values) throws Exception { diff --git a/spring-boot/src/test/java/org/springframework/boot/bind/PropertiesConfigurationFactoryPerformanceTests.java b/spring-boot/src/test/java/org/springframework/boot/bind/PropertiesConfigurationFactoryPerformanceTests.java index a55411cbf7..d227ea2686 100644 --- a/spring-boot/src/test/java/org/springframework/boot/bind/PropertiesConfigurationFactoryPerformanceTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/bind/PropertiesConfigurationFactoryPerformanceTests.java @@ -31,7 +31,7 @@ import org.springframework.context.support.StaticMessageSource; import org.springframework.core.env.StandardEnvironment; import org.springframework.validation.Validator; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * Performance tests for {@link PropertiesConfigurationFactory}. @@ -62,8 +62,8 @@ public class PropertiesConfigurationFactoryPerformanceTests { @Theory public void testValidProperties(String value) throws Exception { Foo foo = createFoo(); - assertEquals("blah", foo.bar); - assertEquals("blah", foo.name); + assertThat(foo.bar).isEqualTo("blah"); + assertThat(foo.name).isEqualTo("blah"); } private Foo createFoo() throws Exception { diff --git a/spring-boot/src/test/java/org/springframework/boot/bind/PropertiesConfigurationFactoryTests.java b/spring-boot/src/test/java/org/springframework/boot/bind/PropertiesConfigurationFactoryTests.java index dbe8e70d69..f2db7d00d7 100644 --- a/spring-boot/src/test/java/org/springframework/boot/bind/PropertiesConfigurationFactoryTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/bind/PropertiesConfigurationFactoryTests.java @@ -37,7 +37,7 @@ import org.springframework.validation.BindException; import org.springframework.validation.Validator; import org.springframework.validation.beanvalidation.SpringValidatorAdapter; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link PropertiesConfigurationFactory}. @@ -57,14 +57,14 @@ public class PropertiesConfigurationFactoryTests { @Test public void testValidPropertiesLoadsWithDash() throws Exception { Foo foo = createFoo("na-me: blah\nbar: blah"); - assertEquals("blah", foo.bar); - assertEquals("blah", foo.name); + assertThat(foo.bar).isEqualTo("blah"); + assertThat(foo.name).isEqualTo("blah"); } @Test public void testUnknownPropertyOkByDefault() throws Exception { Foo foo = createFoo("hi: hello\nname: foo\nbar: blah"); - assertEquals("blah", foo.bar); + assertThat(foo.bar).isEqualTo("blah"); } @Test(expected = NotWritablePropertyException.class) @@ -102,7 +102,7 @@ public class PropertiesConfigurationFactoryTests { this.factory.setIgnoreUnknownFields(false); this.factory.afterPropertiesSet(); Foo foo = this.factory.getObject(); - assertEquals("bar", foo.name); + assertThat(foo.name).isEqualTo("bar"); } @Test @@ -131,7 +131,7 @@ public class PropertiesConfigurationFactoryTests { this.factory.setPropertySources(propertySources); this.factory.afterPropertiesSet(); Foo foo = this.factory.getObject(); - assertEquals("blah", foo.name); + assertThat(foo.name).isEqualTo("blah"); } @Test @@ -146,7 +146,7 @@ public class PropertiesConfigurationFactoryTests { this.factory.setPropertySources(propertySources); this.factory.afterPropertiesSet(); Foo foo = this.factory.getObject(); - assertEquals("blah", foo.name); + assertThat(foo.name).isEqualTo("blah"); } @Test @@ -161,7 +161,7 @@ public class PropertiesConfigurationFactoryTests { this.factory.setPropertySources(propertySources); this.factory.afterPropertiesSet(); Foo foo = this.factory.getObject(); - assertEquals("blah", foo.name); + assertThat(foo.name).isEqualTo("blah"); } private Foo createFoo(final String values) throws Exception { diff --git a/spring-boot/src/test/java/org/springframework/boot/bind/PropertySourcesBindingTests.java b/spring-boot/src/test/java/org/springframework/boot/bind/PropertySourcesBindingTests.java index 091394a27d..7313a54c04 100644 --- a/spring-boot/src/test/java/org/springframework/boot/bind/PropertySourcesBindingTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/bind/PropertySourcesBindingTests.java @@ -34,8 +34,7 @@ import org.springframework.context.annotation.PropertySources; import org.springframework.context.support.PropertySourcesPlaceholderConfigurer; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import static org.hamcrest.Matchers.is; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link PropertySourcesPropertyValues} binding. @@ -55,27 +54,28 @@ public class PropertySourcesBindingTests { @Test public void overridingOfPropertiesOrderOfAtPropertySources() { - assertThat(this.properties.getBar(), is("override")); + assertThat(this.properties.getBar()).isEqualTo("override"); + } @Test public void overridingOfPropertiesOrderOfAtPropertySourcesWherePropertyIsCapitalized() { - assertThat(this.properties.getSpam(), is("BUCKET")); + assertThat(this.properties.getSpam()).isEqualTo("BUCKET"); } @Test public void overridingOfPropertiesOrderOfAtPropertySourcesWherePropertyNamesDiffer() { - assertThat(this.properties.getTheName(), is("NAME")); + assertThat(this.properties.getTheName()).isEqualTo("NAME"); } @Test public void overridingOfPropertiesAndBindToAtValue() { - assertThat(this.foo, is(this.properties.getFoo())); + assertThat(this.foo).isEqualTo(this.properties.getFoo()); } @Test public void overridingOfPropertiesOrderOfApplicationProperties() { - assertThat(this.properties.getFoo(), is("bucket")); + assertThat(this.properties.getFoo()).isEqualTo("bucket"); } @Import({ SomeConfig.class }) diff --git a/spring-boot/src/test/java/org/springframework/boot/bind/PropertySourcesPropertyValuesTests.java b/spring-boot/src/test/java/org/springframework/boot/bind/PropertySourcesPropertyValuesTests.java index 7390807345..54e6f23676 100644 --- a/spring-boot/src/test/java/org/springframework/boot/bind/PropertySourcesPropertyValuesTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/bind/PropertySourcesPropertyValuesTests.java @@ -17,7 +17,6 @@ package org.springframework.boot.bind; import java.util.ArrayList; -import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.LinkedHashMap; @@ -34,9 +33,7 @@ import org.springframework.core.env.MutablePropertySources; import org.springframework.core.env.PropertySource; import org.springframework.validation.DataBinder; -import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link PropertySourcesPropertyValues}. @@ -71,14 +68,14 @@ public class PropertySourcesPropertyValuesTests { this.propertySources.replace("map", new MapPropertySource("map", map)); PropertySourcesPropertyValues propertyValues = new PropertySourcesPropertyValues( this.propertySources); - assertEquals(123, propertyValues.getPropertyValues()[0].getValue()); + assertThat(propertyValues.getPropertyValues()[0].getValue()).isEqualTo(123); } @Test public void testSize() { PropertySourcesPropertyValues propertyValues = new PropertySourcesPropertyValues( this.propertySources); - assertEquals(1, propertyValues.getPropertyValues().length); + assertThat(propertyValues.getPropertyValues().length).isEqualTo(1); } @Test @@ -93,19 +90,19 @@ public class PropertySourcesPropertyValuesTests { PropertySourcesPropertyValues propertyValues = new PropertySourcesPropertyValues( this.propertySources); PropertyValue[] values = propertyValues.getPropertyValues(); - assertEquals(6, values.length); + assertThat(values).hasSize(6); Collection names = new ArrayList(); for (PropertyValue value : values) { names.add(value.getName()); } - assertEquals("[one, two, three, four, five, name]", names.toString()); + assertThat(names).containsExactly("one", "two", "three", "four", "five", "name"); } @Test public void testNonEnumeratedValue() { PropertySourcesPropertyValues propertyValues = new PropertySourcesPropertyValues( this.propertySources); - assertEquals("bar", propertyValues.getPropertyValue("foo").getValue()); + assertThat(propertyValues.getPropertyValue("foo").getValue()).isEqualTo("bar"); } @Test @@ -116,14 +113,14 @@ public class PropertySourcesPropertyValuesTests { this.propertySources.replace("map", composite); PropertySourcesPropertyValues propertyValues = new PropertySourcesPropertyValues( this.propertySources); - assertEquals("bar", propertyValues.getPropertyValue("foo").getValue()); + assertThat(propertyValues.getPropertyValue("foo").getValue()).isEqualTo("bar"); } @Test public void testEnumeratedValue() { PropertySourcesPropertyValues propertyValues = new PropertySourcesPropertyValues( this.propertySources); - assertEquals("bar", propertyValues.getPropertyValue("name").getValue()); + assertThat(propertyValues.getPropertyValue("name").getValue()).isEqualTo("bar"); } @Test @@ -142,7 +139,7 @@ public class PropertySourcesPropertyValuesTests { PropertySourcesPropertyValues propertyValues = new PropertySourcesPropertyValues( this.propertySources, (Collection) null, Collections.singleton("baz")); - assertEquals("bar", propertyValues.getPropertyValue("baz").getValue()); + assertThat(propertyValues.getPropertyValue("baz").getValue()).isEqualTo("bar"); } @Test @@ -151,7 +148,7 @@ public class PropertySourcesPropertyValuesTests { Collections.singletonMap("name", "spam"))); PropertySourcesPropertyValues propertyValues = new PropertySourcesPropertyValues( this.propertySources); - assertEquals("spam", propertyValues.getPropertyValue("name").getValue()); + assertThat(propertyValues.getPropertyValue("name").getValue()).isEqualTo("spam"); } @Test @@ -159,7 +156,7 @@ public class PropertySourcesPropertyValuesTests { TestBean target = new TestBean(); DataBinder binder = new DataBinder(target); binder.bind(new PropertySourcesPropertyValues(this.propertySources)); - assertEquals("bar", target.getName()); + assertThat(target.getName()).isEqualTo("bar"); } @Test @@ -168,7 +165,7 @@ public class PropertySourcesPropertyValuesTests { DataBinder binder = new DataBinder(target); binder.bind(new PropertySourcesPropertyValues(this.propertySources, (Collection) null, Collections.singleton("foo"))); - assertEquals("bar", target.getFoo()); + assertThat(target.getFoo()).isEqualTo("bar"); } @Test @@ -178,7 +175,7 @@ public class PropertySourcesPropertyValuesTests { this.propertySources.addFirst(new MapPropertySource("another", Collections.singletonMap("something", "${nonexistent}"))); binder.bind(new PropertySourcesPropertyValues(this.propertySources)); - assertEquals("bar", target.getName()); + assertThat(target.getName()).isEqualTo("bar"); } @Test @@ -195,7 +192,7 @@ public class PropertySourcesPropertyValuesTests { }); binder.bind(new PropertySourcesPropertyValues(this.propertySources, (Collection) null, Collections.singleton("name"))); - assertEquals(null, target.getName()); + assertThat(target.getName()).isNull(); } @Test @@ -207,7 +204,7 @@ public class PropertySourcesPropertyValuesTests { map.put("list[1]", "v1"); this.propertySources.addFirst(new MapPropertySource("values", map)); binder.bind(new PropertySourcesPropertyValues(this.propertySources)); - assertThat(target.getList(), equalTo(Arrays.asList("v0", "v1"))); + assertThat(target.getList()).containsExactly("v0", "v1"); } @Test @@ -222,7 +219,7 @@ public class PropertySourcesPropertyValuesTests { this.propertySources.addFirst(new MapPropertySource("s", second)); this.propertySources.addFirst(new MapPropertySource("f", first)); binder.bind(new PropertySourcesPropertyValues(this.propertySources)); - assertThat(target.getList(), equalTo(Collections.singletonList("f0"))); + assertThat(target.getList()).containsExactly("f0"); } public static class TestBean { diff --git a/spring-boot/src/test/java/org/springframework/boot/bind/RelaxedDataBinderTests.java b/spring-boot/src/test/java/org/springframework/boot/bind/RelaxedDataBinderTests.java index 5e035e7e10..bbf491e9db 100644 --- a/spring-boot/src/test/java/org/springframework/boot/bind/RelaxedDataBinderTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/bind/RelaxedDataBinderTests.java @@ -53,14 +53,7 @@ import org.springframework.validation.DataBinder; import org.springframework.validation.FieldError; import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean; -import static org.hamcrest.Matchers.contains; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.nullValue; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link RelaxedDataBinder}. @@ -80,112 +73,112 @@ public class RelaxedDataBinderTests { public void testBindString() throws Exception { VanillaTarget target = new VanillaTarget(); bind(target, "foo: bar"); - assertEquals("bar", target.getFoo()); + assertThat(target.getFoo()).isEqualTo("bar"); } @Test public void testBindChars() throws Exception { VanillaTarget target = new VanillaTarget(); bind(target, "bar: foo"); - assertEquals("foo", new String(target.getBar())); + assertThat(new String(target.getBar())).isEqualTo("foo"); } @Test public void testBindStringWithPrefix() throws Exception { VanillaTarget target = new VanillaTarget(); bind(target, "test.foo: bar", "test"); - assertEquals("bar", target.getFoo()); + assertThat(target.getFoo()).isEqualTo("bar"); } @Test public void testBindStringWithPrefixDotSuffix() throws Exception { VanillaTarget target = new VanillaTarget(); bind(target, "some.test.foo: bar", "some.test."); - assertEquals("bar", target.getFoo()); + assertThat(target.getFoo()).isEqualTo("bar"); } @Test public void testBindFromEnvironmentStyleWithPrefix() throws Exception { VanillaTarget target = new VanillaTarget(); bind(target, "TEST_FOO: bar", "test"); - assertEquals("bar", target.getFoo()); + assertThat(target.getFoo()).isEqualTo("bar"); } @Test public void testBindToCamelCaseFromEnvironmentStyleWithPrefix() throws Exception { VanillaTarget target = new VanillaTarget(); bind(target, "TEST_FOO_BAZ: bar", "test"); - assertEquals("bar", target.getFooBaz()); + assertThat(target.getFooBaz()).isEqualTo("bar"); } @Test public void testBindToCamelCaseFromEnvironmentStyle() throws Exception { VanillaTarget target = new VanillaTarget(); bind(target, "test.FOO_BAZ: bar", "test"); - assertEquals("bar", target.getFooBaz()); + assertThat(target.getFooBaz()).isEqualTo("bar"); } @Test public void testBindFromEnvironmentStyleWithNestedPrefix() throws Exception { VanillaTarget target = new VanillaTarget(); bind(target, "TEST_IT_FOO: bar", "test.it"); - assertEquals("bar", target.getFoo()); + assertThat(target.getFoo()).isEqualTo("bar"); } @Test public void testBindCapitals() throws Exception { VanillaTarget target = new VanillaTarget(); bind(target, "FOO: bar"); - assertEquals("bar", target.getFoo()); + assertThat(target.getFoo()).isEqualTo("bar"); } @Test public void testBindUnderscoreInActualPropertyName() throws Exception { VanillaTarget target = new VanillaTarget(); bind(target, "foo-bar: bar"); - assertEquals("bar", target.getFoo_bar()); + assertThat(target.getFoo_bar()).isEqualTo("bar"); } @Test public void testBindUnderscoreToCamelCase() throws Exception { VanillaTarget target = new VanillaTarget(); bind(target, "foo_baz: bar"); - assertEquals("bar", target.getFooBaz()); + assertThat(target.getFooBaz()).isEqualTo("bar"); } @Test public void testBindHyphen() throws Exception { VanillaTarget target = new VanillaTarget(); bind(target, "foo-baz: bar"); - assertEquals("bar", target.getFooBaz()); + assertThat(target.getFooBaz()).isEqualTo("bar"); } @Test public void testBindCamelCase() throws Exception { VanillaTarget target = new VanillaTarget(); bind(target, "fooBaz: bar"); - assertEquals("bar", target.getFooBaz()); + assertThat(target.getFooBaz()).isEqualTo("bar"); } @Test public void testBindNumber() throws Exception { VanillaTarget target = new VanillaTarget(); bind(target, "foo: bar\n" + "value: 123"); - assertEquals(123, target.getValue()); + assertThat(target.getValue()).isEqualTo(123); } @Test public void testSimpleValidation() throws Exception { ValidatedTarget target = new ValidatedTarget(); BindingResult result = bind(target, ""); - assertEquals(1, result.getErrorCount()); + assertThat(result.getErrorCount()).isEqualTo(1); } @Test public void testRequiredFieldsValidation() throws Exception { TargetWithValidatedMap target = new TargetWithValidatedMap(); BindingResult result = bind(target, "info[foo]: bar"); - assertEquals(2, result.getErrorCount()); + assertThat(result.getErrorCount()).isEqualTo(2); for (FieldError error : result.getFieldErrors()) { System.err.println( new StaticMessageSource().getMessage(error, Locale.getDefault())); @@ -200,9 +193,9 @@ public class RelaxedDataBinderTests { binder.setIgnoreUnknownFields(false); BindingResult result = bind(binder, target, "foo: bar\n" + "value: 123\n" + "bar: spam"); - assertEquals(0, target.getValue()); - assertEquals("bar", target.getFoo()); - assertEquals(0, result.getErrorCount()); + assertThat(target.getValue()).isEqualTo(0); + assertThat(target.getFoo()).isEqualTo("bar"); + assertThat(result.getErrorCount()).isEqualTo(0); } @Test @@ -214,60 +207,61 @@ public class RelaxedDataBinderTests { binder.setIgnoreUnknownFields(false); BindingResult result = bind(binder, target, "foo: bar\n" + "value: 123\n" + "bar: spam"); - assertEquals(123, target.getValue()); - assertNull(target.getFoo()); - assertEquals(0, result.getErrorCount()); + assertThat(target.getValue()).isEqualTo(123); + assertThat(target.getFoo()).isNull(); + assertThat(result.getErrorCount()).isEqualTo(0); } @Test public void testBindNested() throws Exception { TargetWithNestedObject target = new TargetWithNestedObject(); bind(target, "nested.foo: bar\n" + "nested.value: 123"); - assertEquals(123, target.getNested().getValue()); + assertThat(target.getNested().getValue()).isEqualTo(123); } @Test public void testBindRelaxedNestedValue() throws Exception { TargetWithNestedObject target = new TargetWithNestedObject(); bind(target, "nested_foo_Baz: bar\n" + "nested_value: 123"); - assertEquals("bar", target.getNested().getFooBaz()); - assertEquals(123, target.getNested().getValue()); + assertThat(target.getNested().getFooBaz()).isEqualTo("bar"); + assertThat(target.getNested().getValue()).isEqualTo(123); } @Test public void testBindRelaxedNestedCamelValue() throws Exception { TargetWithNestedObject target = new TargetWithNestedObject(); bind(target, "another_nested_foo_Baz: bar\n" + "another-nested_value: 123"); - assertEquals("bar", target.getAnotherNested().getFooBaz()); - assertEquals(123, target.getAnotherNested().getValue()); + assertThat(target.getAnotherNested().getFooBaz()).isEqualTo("bar"); + assertThat(target.getAnotherNested().getValue()).isEqualTo(123); } @Test public void testBindNestedWithEnvironmentStyle() throws Exception { TargetWithNestedObject target = new TargetWithNestedObject(); bind(target, "nested_foo: bar\n" + "nested_value: 123"); - assertEquals(123, target.getNested().getValue()); + assertThat(target.getNested().getValue()).isEqualTo(123); } @Test public void testBindNestedList() throws Exception { TargetWithNestedList target = new TargetWithNestedList(); bind(target, "nested[0]: bar\nnested[1]: foo"); - assertEquals("[bar, foo]", target.getNested().toString()); + assertThat(target.getNested().toString()).isEqualTo("[bar, foo]"); } @Test public void testBindNestedListOfBean() throws Exception { TargetWithNestedListOfBean target = new TargetWithNestedListOfBean(); bind(target, "nested[0].foo: bar\nnested[1].foo: foo"); - assertEquals("bar", target.getNested().get(0).getFoo()); + assertThat(target.getNested().get(0).getFoo()).isEqualTo("bar"); } @Test public void testBindNestedListOfBeanWithList() throws Exception { TargetWithNestedListOfBeanWithList target = new TargetWithNestedListOfBeanWithList(); bind(target, "nested[0].nested[0].foo: bar\nnested[1].nested[0].foo: foo"); - assertEquals("bar", target.getNested().get(0).getNested().get(0).getFoo()); + assertThat(target.getNested().get(0).getNested().get(0).getFoo()) + .isEqualTo("bar"); } @Test @@ -275,7 +269,7 @@ public class RelaxedDataBinderTests { TargetWithNestedList target = new TargetWithNestedList(); this.conversionService = new DefaultConversionService(); bind(target, "nested: bar,foo"); - assertEquals("[bar, foo]", target.getNested().toString()); + assertThat(target.getNested().toString()).isEqualTo("[bar, foo]"); } @Test @@ -283,7 +277,7 @@ public class RelaxedDataBinderTests { TargetWithNestedSet target = new TargetWithNestedSet(); this.conversionService = new DefaultConversionService(); bind(target, "nested: bar,foo"); - assertEquals("[bar, foo]", target.getNested().toString()); + assertThat(target.getNested().toString()).isEqualTo("[bar, foo]"); } @Test(expected = NotWritablePropertyException.class) @@ -291,7 +285,7 @@ public class RelaxedDataBinderTests { TargetWithReadOnlyNestedList target = new TargetWithReadOnlyNestedList(); this.conversionService = new DefaultConversionService(); bind(target, "nested: bar,foo"); - assertEquals("[bar, foo]", target.getNested().toString()); + assertThat(target.getNested().toString()).isEqualTo("[bar, foo]"); } @Test @@ -299,7 +293,7 @@ public class RelaxedDataBinderTests { TargetWithReadOnlyNestedList target = new TargetWithReadOnlyNestedList(); this.conversionService = new DefaultConversionService(); bind(target, "nested[0]: bar\nnested[1]:foo"); - assertEquals("[bar, foo]", target.getNested().toString()); + assertThat(target.getNested().toString()).isEqualTo("[bar, foo]"); } @Test @@ -307,7 +301,7 @@ public class RelaxedDataBinderTests { TargetWithReadOnlyDoubleNestedList target = new TargetWithReadOnlyDoubleNestedList(); this.conversionService = new DefaultConversionService(); bind(target, "bean.nested[0]:bar\nbean.nested[1]:foo"); - assertEquals("[bar, foo]", target.getBean().getNested().toString()); + assertThat(target.getBean().getNested().toString()).isEqualTo("[bar, foo]"); } @Test @@ -315,69 +309,69 @@ public class RelaxedDataBinderTests { TargetWithReadOnlyNestedCollection target = new TargetWithReadOnlyNestedCollection(); this.conversionService = new DefaultConversionService(); bind(target, "nested[0]: bar\nnested[1]:foo"); - assertEquals("[bar, foo]", target.getNested().toString()); + assertThat(target.getNested().toString()).isEqualTo("[bar, foo]"); } @Test public void testBindNestedMap() throws Exception { TargetWithNestedMap target = new TargetWithNestedMap(); bind(target, "nested.foo: bar\n" + "nested.value: 123"); - assertEquals("123", target.getNested().get("value")); + assertThat(target.getNested().get("value")).isEqualTo("123"); } @Test public void testBindNestedMapPropsWithUnderscores() throws Exception { TargetWithNestedMap target = new TargetWithNestedMap(); bind(target, "nested_foo: bar\n" + "nested_value: 123"); - assertEquals("123", target.getNested().get("value")); - assertEquals("bar", target.getNested().get("foo")); + assertThat(target.getNested().get("value")).isEqualTo("123"); + assertThat(target.getNested().get("foo")).isEqualTo("bar"); } @Test public void testBindNestedUntypedMap() throws Exception { TargetWithNestedUntypedMap target = new TargetWithNestedUntypedMap(); bind(target, "nested.foo: bar\n" + "nested.value: 123"); - assertEquals("123", target.getNested().get("value")); + assertThat(target.getNested().get("value")).isEqualTo("123"); } @Test public void testBindNestedMapOfString() throws Exception { TargetWithNestedMapOfString target = new TargetWithNestedMapOfString(); bind(target, "nested.foo: bar\n" + "nested.value.foo: 123"); - assertEquals("bar", target.getNested().get("foo")); - assertEquals("123", target.getNested().get("value.foo")); + assertThat(target.getNested().get("foo")).isEqualTo("bar"); + assertThat(target.getNested().get("value.foo")).isEqualTo("123"); } @Test public void testBindNestedMapOfStringWithUnderscore() throws Exception { TargetWithNestedMapOfString target = new TargetWithNestedMapOfString(); bind(target, "nested_foo: bar\n" + "nested_value_foo: 123"); - assertEquals("bar", target.getNested().get("foo")); - assertEquals("123", target.getNested().get("value_foo")); + assertThat(target.getNested().get("foo")).isEqualTo("bar"); + assertThat(target.getNested().get("value_foo")).isEqualTo("123"); } @Test public void testBindNestedMapOfStringWithUnderscoreAndUpperCase() throws Exception { TargetWithNestedMapOfString target = new TargetWithNestedMapOfString(); bind(target, "NESTED_FOO: bar\n" + "NESTED_VALUE_FOO: 123"); - assertEquals("bar", target.getNested().get("FOO")); - assertEquals("123", target.getNested().get("VALUE_FOO")); + assertThat(target.getNested().get("FOO")).isEqualTo("bar"); + assertThat(target.getNested().get("VALUE_FOO")).isEqualTo("123"); } @Test public void testBindNestedMapOfStringReferenced() throws Exception { TargetWithNestedMapOfString target = new TargetWithNestedMapOfString(); bind(target, "nested.foo: bar\n" + "nested[value.foo]: 123"); - assertEquals("bar", target.getNested().get("foo")); - assertEquals("123", target.getNested().get("value.foo")); + assertThat(target.getNested().get("foo")).isEqualTo("bar"); + assertThat(target.getNested().get("value.foo")).isEqualTo("123"); } @Test public void testBindNestedProperties() throws Exception { TargetWithNestedProperties target = new TargetWithNestedProperties(); bind(target, "nested.foo: bar\n" + "nested.value.foo: 123"); - assertEquals("bar", target.getNested().get("foo")); - assertEquals("123", target.getNested().get("value.foo")); + assertThat(target.getNested().get("foo")).isEqualTo("bar"); + assertThat(target.getNested().get("value.foo")).isEqualTo("123"); } @Test @@ -385,8 +379,8 @@ public class RelaxedDataBinderTests { this.conversionService = new DefaultConversionService(); TargetWithNestedMapOfEnum target = new TargetWithNestedMapOfEnum(); bind(target, "nested.this: bar\n" + "nested.ThAt: 123"); - assertEquals("bar", target.getNested().get(Bingo.THIS)); - assertEquals("123", target.getNested().get(Bingo.THAT)); + assertThat(target.getNested().get(Bingo.THIS)).isEqualTo("bar"); + assertThat(target.getNested().get(Bingo.THAT)).isEqualTo("123"); } @Test @@ -394,22 +388,22 @@ public class RelaxedDataBinderTests { this.conversionService = new DefaultConversionService(); TargetWithNestedMapOfEnum target = new TargetWithNestedMapOfEnum(); bind(target, "nested.the-other: bar\n" + "nested.that_other: 123"); - assertEquals("bar", target.getNested().get(Bingo.THE_OTHER)); - assertEquals("123", target.getNested().get(Bingo.THAT_OTHER)); + assertThat(target.getNested().get(Bingo.THE_OTHER)).isEqualTo("bar"); + assertThat(target.getNested().get(Bingo.THAT_OTHER)).isEqualTo("123"); } @Test public void testBindNestedMapBracketReferenced() throws Exception { TargetWithNestedMap target = new TargetWithNestedMap(); bind(target, "nested[foo]: bar\n" + "nested[value]: 123"); - assertEquals("123", target.getNested().get("value")); + assertThat(target.getNested().get("value")).isEqualTo("123"); } @Test public void testBindNestedMapBracketReferencedAndPeriods() throws Exception { TargetWithNestedMap target = new TargetWithNestedMap(); bind(target, "nested[foo]: bar\n" + "nested[foo.value]: 123"); - assertEquals("123", target.getNested().get("foo.value")); + assertThat(target.getNested().get("foo.value")).isEqualTo("123"); } @SuppressWarnings("unchecked") @@ -418,14 +412,15 @@ public class RelaxedDataBinderTests { TargetWithNestedMap target = new TargetWithNestedMap(); bind(target, "nested.foo: bar.key\n" + "nested[bar.key].spam: bucket\n" + "nested[bar.key].value: 123\nnested[bar.key].foo: crap"); - assertEquals(2, target.getNested().size()); + assertThat(target.getNested()).hasSize(2); Map nestedMap = (Map) target.getNested() .get("bar.key"); - assertNotNull("nested map should be registered with 'bar.key'", nestedMap); - assertEquals(3, nestedMap.size()); - assertEquals("123", nestedMap.get("value")); - assertEquals("bar.key", target.getNested().get("foo")); - assertFalse(target.getNested().containsValue(target.getNested())); + assertThat(nestedMap).as("nested map should be registered with 'bar.key'") + .isNotNull(); + assertThat(nestedMap).hasSize(3); + assertThat(nestedMap.get("value")).isEqualTo("123"); + assertThat(target.getNested().get("foo")).isEqualTo("bar.key"); + assertThat(target.getNested().containsValue(target.getNested())).isFalse(); } @SuppressWarnings("unchecked") @@ -434,12 +429,12 @@ public class RelaxedDataBinderTests { TargetWithNestedMap target = new TargetWithNestedMap(); bind(target, "nested.foo: bar\n" + "nested.bar.spam: bucket\n" + "nested.bar.value: 123\nnested.bar.foo: crap"); - assertEquals(2, target.getNested().size()); - assertEquals(3, ((Map) target.getNested().get("bar")).size()); - assertEquals("123", - ((Map) target.getNested().get("bar")).get("value")); - assertEquals("bar", target.getNested().get("foo")); - assertFalse(target.getNested().containsValue(target.getNested())); + assertThat(target.getNested()).hasSize(2); + assertThat(((Map) target.getNested().get("bar"))).hasSize(3); + assertThat(((Map) target.getNested().get("bar")).get("value")) + .isEqualTo("123"); + assertThat(target.getNested().get("foo")).isEqualTo("bar"); + assertThat(target.getNested().containsValue(target.getNested())).isFalse(); } @Test @@ -447,18 +442,18 @@ public class RelaxedDataBinderTests { TargetWithNestedMapOfListOfString target = new TargetWithNestedMapOfListOfString(); bind(target, "nested.foo[0]: bar\n" + "nested.bar[0]: bucket\n" + "nested.bar[1]: 123\nnested.bar[2]: crap"); - assertEquals(2, target.getNested().size()); - assertEquals(3, target.getNested().get("bar").size()); - assertEquals("123", target.getNested().get("bar").get(1)); - assertEquals("[bar]", target.getNested().get("foo").toString()); + assertThat(target.getNested()).hasSize(2); + assertThat(target.getNested().get("bar")).hasSize(3); + assertThat(target.getNested().get("bar").get(1)).isEqualTo("123"); + assertThat(target.getNested().get("foo").toString()).isEqualTo("[bar]"); } @Test public void testBindNestedMapOfBean() throws Exception { TargetWithNestedMapOfBean target = new TargetWithNestedMapOfBean(); bind(target, "nested.foo.foo: bar\n" + "nested.bar.foo: bucket"); - assertEquals(2, target.getNested().size()); - assertEquals("bucket", target.getNested().get("bar").getFoo()); + assertThat(target.getNested()).hasSize(2); + assertThat(target.getNested().get("bar").getFoo()).isEqualTo("bucket"); } @Test @@ -466,17 +461,17 @@ public class RelaxedDataBinderTests { TargetWithNestedMapOfListOfBean target = new TargetWithNestedMapOfListOfBean(); bind(target, "nested.foo[0].foo: bar\n" + "nested.bar[0].foo: bucket\n" + "nested.bar[1].value: 123\nnested.bar[2].foo: crap"); - assertEquals(2, target.getNested().size()); - assertEquals(3, target.getNested().get("bar").size()); - assertEquals(123, target.getNested().get("bar").get(1).getValue()); - assertEquals("bar", target.getNested().get("foo").get(0).getFoo()); + assertThat(target.getNested()).hasSize(2); + assertThat(target.getNested().get("bar")).hasSize(3); + assertThat(target.getNested().get("bar").get(1).getValue()).isEqualTo(123); + assertThat(target.getNested().get("foo").get(0).getFoo()).isEqualTo("bar"); } @Test public void testBindErrorTypeMismatch() throws Exception { VanillaTarget target = new VanillaTarget(); BindingResult result = bind(target, "foo: bar\n" + "value: foo"); - assertEquals(1, result.getErrorCount()); + assertThat(result.getErrorCount()).isEqualTo(1); } @Test @@ -485,7 +480,7 @@ public class RelaxedDataBinderTests { this.expected.expectMessage("not writable"); VanillaTarget target = new VanillaTarget(); BindingResult result = bind(target, "spam: bar\n" + "value: 123"); - assertEquals(1, result.getErrorCount()); + assertThat(result.getErrorCount()).isEqualTo(1); } @Test @@ -493,8 +488,8 @@ public class RelaxedDataBinderTests { VanillaTarget target = new VanillaTarget(); BindingResult result = bind(target, "spam: bar\n" + "vanilla.value: 123", "vanilla"); - assertEquals(0, result.getErrorCount()); - assertEquals(123, target.getValue()); + assertThat(result.getErrorCount()).isEqualTo(0); + assertThat(target.getValue()).isEqualTo(123); } @Test @@ -505,9 +500,9 @@ public class RelaxedDataBinderTests { binder.setIgnoreNestedProperties(true); BindingResult result = bind(binder, target, "foo: bar\n" + "value: 123\n" + "nested.bar: spam"); - assertEquals(123, target.getValue()); - assertEquals("bar", target.getFoo()); - assertEquals(0, result.getErrorCount()); + assertThat(target.getValue()).isEqualTo(123); + assertThat(target.getFoo()).isEqualTo("bar"); + assertThat(result.getErrorCount()).isEqualTo(0); } @Test @@ -518,9 +513,9 @@ public class RelaxedDataBinderTests { binder.setIgnoreNestedProperties(true); BindingResult result = bind(binder, target, "foo.foo: bar\n" + "foo.value: 123\n" + "foo.nested.bar: spam"); - assertEquals(123, target.getValue()); - assertEquals("bar", target.getFoo()); - assertEquals(0, result.getErrorCount()); + assertThat(target.getValue()).isEqualTo(123); + assertThat(target.getFoo()).isEqualTo("bar"); + assertThat(result.getErrorCount()).isEqualTo(0); } @Test @@ -528,8 +523,8 @@ public class RelaxedDataBinderTests { Map target = new LinkedHashMap(); BindingResult result = bind(target, "spam: bar\n" + "vanilla.value: 123", "vanilla"); - assertEquals(0, result.getErrorCount()); - assertEquals("123", target.get("value")); + assertThat(result.getErrorCount()).isEqualTo(0); + assertThat(target.get("value")).isEqualTo("123"); } @Test @@ -537,10 +532,10 @@ public class RelaxedDataBinderTests { Map target = new LinkedHashMap(); BindingResult result = bind(target, "vanilla.spam: bar\n" + "vanilla.spam.value: 123", "vanilla"); - assertEquals(0, result.getErrorCount()); - assertEquals(2, target.size()); - assertEquals("bar", target.get("spam")); - assertEquals("123", target.get("spam.value")); + assertThat(result.getErrorCount()).isEqualTo(0); + assertThat(target).hasSize(2); + assertThat(target.get("spam")).isEqualTo("bar"); + assertThat(target.get("spam.value")).isEqualTo("123"); } @Test @@ -548,10 +543,10 @@ public class RelaxedDataBinderTests { Map target = new LinkedHashMap(); BindingResult result = bind(target, "vanilla.spam.foo: bar\n" + "vanilla.spam.foo.value: 123", "vanilla"); - assertEquals(0, result.getErrorCount()); + assertThat(result.getErrorCount()).isEqualTo(0); @SuppressWarnings("unchecked") Map map = (Map) target.get("spam"); - assertEquals("123", map.get("foo.value")); + assertThat(map.get("foo.value")).isEqualTo("123"); } @Test @@ -559,10 +554,10 @@ public class RelaxedDataBinderTests { Map target = new LinkedHashMap(); BindingResult result = bind(target, "vanilla.spam.bar: bar\n" + "vanilla.spam.bar.value: 123", "vanilla"); - assertEquals(0, result.getErrorCount()); + assertThat(result.getErrorCount()).isEqualTo(0); @SuppressWarnings("unchecked") Map map = (Map) target.get("spam"); - assertEquals("123", map.get("bar.value")); + assertThat(map.get("bar.value")).isEqualTo("123"); } @Test @@ -570,8 +565,8 @@ public class RelaxedDataBinderTests { Map target = new LinkedHashMap(); BindingResult result = bind(target, "vanilla.spam: bar\n" + "vanilla.value: 123", "vanilla"); - assertEquals(0, result.getErrorCount()); - assertEquals("123", target.get("value")); + assertThat(result.getErrorCount()).isEqualTo(0); + assertThat(target.get("value")).isEqualTo("123"); } @Test @@ -579,10 +574,10 @@ public class RelaxedDataBinderTests { Map target = new LinkedHashMap(); BindingResult result = bind(target, "spam: bar\n" + "vanilla.foo.value: 123", "vanilla"); - assertEquals(0, result.getErrorCount()); + assertThat(result.getErrorCount()).isEqualTo(0); @SuppressWarnings("unchecked") Map map = (Map) target.get("foo"); - assertEquals("123", map.get("value")); + assertThat(map.get("value")).isEqualTo("123"); } @SuppressWarnings("unchecked") @@ -590,15 +585,15 @@ public class RelaxedDataBinderTests { public void testBindOverlappingNestedMaps() throws Exception { Map target = new LinkedHashMap(); BindingResult result = bind(target, "a.b.c.d: abc\na.b.c1.d1: efg"); - assertEquals(0, result.getErrorCount()); + assertThat(result.getErrorCount()).isEqualTo(0); Map a = (Map) target.get("a"); Map b = (Map) a.get("b"); Map c = (Map) b.get("c"); - assertEquals("abc", c.get("d")); + assertThat(c.get("d")).isEqualTo("abc"); Map c1 = (Map) b.get("c1"); - assertEquals("efg", c1.get("d1")); + assertThat(c1.get("d1")).isEqualTo("efg"); } @Test @@ -621,8 +616,8 @@ public class RelaxedDataBinderTests { properties.add("flub", "a"); properties.add("foo", "b"); new RelaxedDataBinder(target).bind(properties); - assertThat(target.getFooBaz(), nullValue()); - assertThat(target.getFoo(), equalTo("b")); + assertThat(target.getFooBaz()).isNull(); + assertThat(target.getFoo()).isEqualTo("b"); } @Test @@ -632,8 +627,8 @@ public class RelaxedDataBinderTests { properties.add("flub", "a"); properties.add("foo", "b"); new RelaxedDataBinder(target).withAlias("flub", "fooBaz").bind(properties); - assertThat(target.getFooBaz(), equalTo("a")); - assertThat(target.getFoo(), equalTo("b")); + assertThat(target.getFooBaz()).isEqualTo("a"); + assertThat(target.getFoo()).isEqualTo("b"); } @Test @@ -645,41 +640,41 @@ public class RelaxedDataBinderTests { values.add("test.FOO_BAZ", "boo"); values.add("test.foo-baz", "bar"); binder.bind(values); - assertEquals("boo", target.getFooBaz()); + assertThat(target.getFooBaz()).isEqualTo("boo"); } private void doTestBindCaseInsensitiveEnums(VanillaTarget target) throws Exception { BindingResult result = bind(target, "bingo: THIS"); - assertThat(result.getErrorCount(), equalTo(0)); - assertThat(target.getBingo(), equalTo(Bingo.THIS)); + assertThat(result.getErrorCount()).isEqualTo(0); + assertThat(target.getBingo()).isEqualTo(Bingo.THIS); result = bind(target, "bingo: oR"); - assertThat(result.getErrorCount(), equalTo(0)); - assertThat(target.getBingo(), equalTo(Bingo.or)); + assertThat(result.getErrorCount()).isEqualTo(0); + assertThat(target.getBingo()).isEqualTo(Bingo.or); result = bind(target, "bingo: that"); - assertThat(result.getErrorCount(), equalTo(0)); - assertThat(target.getBingo(), equalTo(Bingo.THAT)); + assertThat(result.getErrorCount()).isEqualTo(0); + assertThat(target.getBingo()).isEqualTo(Bingo.THAT); result = bind(target, "bingo: the-other"); - assertThat(result.getErrorCount(), equalTo(0)); - assertThat(target.getBingo(), equalTo(Bingo.THE_OTHER)); + assertThat(result.getErrorCount()).isEqualTo(0); + assertThat(target.getBingo()).isEqualTo(Bingo.THE_OTHER); result = bind(target, "bingo: the_other"); - assertThat(result.getErrorCount(), equalTo(0)); - assertThat(target.getBingo(), equalTo(Bingo.THE_OTHER)); + assertThat(result.getErrorCount()).isEqualTo(0); + assertThat(target.getBingo()).isEqualTo(Bingo.THE_OTHER); result = bind(target, "bingo: The_Other"); - assertThat(result.getErrorCount(), equalTo(0)); - assertThat(target.getBingo(), equalTo(Bingo.THE_OTHER)); + assertThat(result.getErrorCount()).isEqualTo(0); + assertThat(target.getBingo()).isEqualTo(Bingo.THE_OTHER); result = bind(target, "bingos: The_Other"); - assertThat(result.getErrorCount(), equalTo(0)); - assertThat(target.getBingos(), contains(Bingo.THE_OTHER)); + assertThat(result.getErrorCount()).isEqualTo(0); + assertThat(target.getBingos()).contains(Bingo.THE_OTHER); result = bind(target, "bingos: The_Other, that"); - assertThat(result.getErrorCount(), equalTo(0)); - assertThat(target.getBingos(), contains(Bingo.THE_OTHER, Bingo.THAT)); + assertThat(result.getErrorCount()).isEqualTo(0); + assertThat(target.getBingos()).contains(Bingo.THE_OTHER, Bingo.THAT); } private BindingResult bind(Object target, String values) throws Exception { diff --git a/spring-boot/src/test/java/org/springframework/boot/bind/RelaxedNamesTests.java b/spring-boot/src/test/java/org/springframework/boot/bind/RelaxedNamesTests.java index 20296592a0..3d6d2b9460 100644 --- a/spring-boot/src/test/java/org/springframework/boot/bind/RelaxedNamesTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/bind/RelaxedNamesTests.java @@ -20,8 +20,7 @@ import java.util.Iterator; import org.junit.Test; -import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link RelaxedNames}. @@ -34,94 +33,94 @@ public class RelaxedNamesTests { @Test public void iterator() throws Exception { Iterator iterator = new RelaxedNames("my-RELAXED-property").iterator(); - assertThat(iterator.next(), equalTo("my-RELAXED-property")); - assertThat(iterator.next(), equalTo("my_RELAXED_property")); - assertThat(iterator.next(), equalTo("myRELAXEDProperty")); - assertThat(iterator.next(), equalTo("myRelaxedProperty")); - assertThat(iterator.next(), equalTo("my-relaxed-property")); - assertThat(iterator.next(), equalTo("my_relaxed_property")); - assertThat(iterator.next(), equalTo("myrelaxedproperty")); - assertThat(iterator.next(), equalTo("MY-RELAXED-PROPERTY")); - assertThat(iterator.next(), equalTo("MY_RELAXED_PROPERTY")); - assertThat(iterator.next(), equalTo("MYRELAXEDPROPERTY")); - assertThat(iterator.hasNext(), equalTo(false)); + assertThat(iterator.next()).isEqualTo("my-RELAXED-property"); + assertThat(iterator.next()).isEqualTo("my_RELAXED_property"); + assertThat(iterator.next()).isEqualTo("myRELAXEDProperty"); + assertThat(iterator.next()).isEqualTo("myRelaxedProperty"); + assertThat(iterator.next()).isEqualTo("my-relaxed-property"); + assertThat(iterator.next()).isEqualTo("my_relaxed_property"); + assertThat(iterator.next()).isEqualTo("myrelaxedproperty"); + assertThat(iterator.next()).isEqualTo("MY-RELAXED-PROPERTY"); + assertThat(iterator.next()).isEqualTo("MY_RELAXED_PROPERTY"); + assertThat(iterator.next()).isEqualTo("MYRELAXEDPROPERTY"); + assertThat(iterator.hasNext()).isFalse(); } @Test public void fromUnderscores() throws Exception { Iterator iterator = new RelaxedNames("nes_ted").iterator(); - assertThat(iterator.next(), equalTo("nes_ted")); - assertThat(iterator.next(), equalTo("nes.ted")); - assertThat(iterator.next(), equalTo("nesTed")); - assertThat(iterator.next(), equalTo("nested")); - assertThat(iterator.next(), equalTo("NES_TED")); - assertThat(iterator.next(), equalTo("NES.TED")); - assertThat(iterator.next(), equalTo("NESTED")); - assertThat(iterator.hasNext(), equalTo(false)); + assertThat(iterator.next()).isEqualTo("nes_ted"); + assertThat(iterator.next()).isEqualTo("nes.ted"); + assertThat(iterator.next()).isEqualTo("nesTed"); + assertThat(iterator.next()).isEqualTo("nested"); + assertThat(iterator.next()).isEqualTo("NES_TED"); + assertThat(iterator.next()).isEqualTo("NES.TED"); + assertThat(iterator.next()).isEqualTo("NESTED"); + assertThat(iterator.hasNext()).isFalse(); } @Test public void fromPlain() throws Exception { Iterator iterator = new RelaxedNames("plain").iterator(); - assertThat(iterator.next(), equalTo("plain")); - assertThat(iterator.next(), equalTo("PLAIN")); - assertThat(iterator.hasNext(), equalTo(false)); + assertThat(iterator.next()).isEqualTo("plain"); + assertThat(iterator.next()).isEqualTo("PLAIN"); + assertThat(iterator.hasNext()).isFalse(); } @Test public void fromCamelCase() throws Exception { Iterator iterator = new RelaxedNames("caMel").iterator(); - assertThat(iterator.next(), equalTo("caMel")); - assertThat(iterator.next(), equalTo("ca_mel")); - assertThat(iterator.next(), equalTo("ca-mel")); - assertThat(iterator.next(), equalTo("camel")); - assertThat(iterator.next(), equalTo("CAMEL")); - assertThat(iterator.next(), equalTo("CA_MEL")); - assertThat(iterator.next(), equalTo("CA-MEL")); - assertThat(iterator.hasNext(), equalTo(false)); + assertThat(iterator.next()).isEqualTo("caMel"); + assertThat(iterator.next()).isEqualTo("ca_mel"); + assertThat(iterator.next()).isEqualTo("ca-mel"); + assertThat(iterator.next()).isEqualTo("camel"); + assertThat(iterator.next()).isEqualTo("CAMEL"); + assertThat(iterator.next()).isEqualTo("CA_MEL"); + assertThat(iterator.next()).isEqualTo("CA-MEL"); + assertThat(iterator.hasNext()).isFalse(); } @Test public void fromCompoundCamelCase() throws Exception { Iterator iterator = new RelaxedNames("caMelCase").iterator(); - assertThat(iterator.next(), equalTo("caMelCase")); - assertThat(iterator.next(), equalTo("ca_mel_case")); - assertThat(iterator.next(), equalTo("ca-mel-case")); - assertThat(iterator.next(), equalTo("camelcase")); - assertThat(iterator.next(), equalTo("CAMELCASE")); - assertThat(iterator.next(), equalTo("CA_MEL_CASE")); - assertThat(iterator.next(), equalTo("CA-MEL-CASE")); - assertThat(iterator.hasNext(), equalTo(false)); + assertThat(iterator.next()).isEqualTo("caMelCase"); + assertThat(iterator.next()).isEqualTo("ca_mel_case"); + assertThat(iterator.next()).isEqualTo("ca-mel-case"); + assertThat(iterator.next()).isEqualTo("camelcase"); + assertThat(iterator.next()).isEqualTo("CAMELCASE"); + assertThat(iterator.next()).isEqualTo("CA_MEL_CASE"); + assertThat(iterator.next()).isEqualTo("CA-MEL-CASE"); + assertThat(iterator.hasNext()).isFalse(); } @Test public void fromPeriods() throws Exception { Iterator iterator = new RelaxedNames("spring.value").iterator(); - assertThat(iterator.next(), equalTo("spring.value")); - assertThat(iterator.next(), equalTo("spring_value")); - assertThat(iterator.next(), equalTo("springValue")); - assertThat(iterator.next(), equalTo("springvalue")); - assertThat(iterator.next(), equalTo("SPRING.VALUE")); - assertThat(iterator.next(), equalTo("SPRING_VALUE")); - assertThat(iterator.next(), equalTo("SPRINGVALUE")); - assertThat(iterator.hasNext(), equalTo(false)); + assertThat(iterator.next()).isEqualTo("spring.value"); + assertThat(iterator.next()).isEqualTo("spring_value"); + assertThat(iterator.next()).isEqualTo("springValue"); + assertThat(iterator.next()).isEqualTo("springvalue"); + assertThat(iterator.next()).isEqualTo("SPRING.VALUE"); + assertThat(iterator.next()).isEqualTo("SPRING_VALUE"); + assertThat(iterator.next()).isEqualTo("SPRINGVALUE"); + assertThat(iterator.hasNext()).isFalse(); } @Test public void fromPrefixEndingInPeriod() throws Exception { Iterator iterator = new RelaxedNames("spring.").iterator(); - assertThat(iterator.next(), equalTo("spring.")); - assertThat(iterator.next(), equalTo("spring_")); - assertThat(iterator.next(), equalTo("SPRING.")); - assertThat(iterator.next(), equalTo("SPRING_")); - assertThat(iterator.hasNext(), equalTo(false)); + assertThat(iterator.next()).isEqualTo("spring."); + assertThat(iterator.next()).isEqualTo("spring_"); + assertThat(iterator.next()).isEqualTo("SPRING."); + assertThat(iterator.next()).isEqualTo("SPRING_"); + assertThat(iterator.hasNext()).isFalse(); } @Test public void fromEmpty() throws Exception { Iterator iterator = new RelaxedNames("").iterator(); - assertThat(iterator.next(), equalTo("")); - assertThat(iterator.hasNext(), equalTo(false)); + assertThat(iterator.next()).isEqualTo(""); + assertThat(iterator.hasNext()).isFalse(); } } diff --git a/spring-boot/src/test/java/org/springframework/boot/bind/RelaxedPropertyResolverTests.java b/spring-boot/src/test/java/org/springframework/boot/bind/RelaxedPropertyResolverTests.java index 538d66d293..bfe3527f56 100644 --- a/spring-boot/src/test/java/org/springframework/boot/bind/RelaxedPropertyResolverTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/bind/RelaxedPropertyResolverTests.java @@ -30,10 +30,7 @@ import org.springframework.core.env.MutablePropertySources; import org.springframework.core.env.PropertiesPropertySource; import org.springframework.core.env.StandardEnvironment; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.nullValue; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link RelaxedPropertyResolver}. @@ -74,7 +71,7 @@ public class RelaxedPropertyResolverTests { @Test public void getRequiredProperty() throws Exception { - assertThat(this.resolver.getRequiredProperty("my-string"), equalTo("value")); + assertThat(this.resolver.getRequiredProperty("my-string")).isEqualTo("value"); this.thrown.expect(IllegalStateException.class); this.thrown.expectMessage("required key [my-missing] not found"); this.resolver.getRequiredProperty("my-missing"); @@ -82,8 +79,8 @@ public class RelaxedPropertyResolverTests { @Test public void getRequiredPropertyWithType() throws Exception { - assertThat(this.resolver.getRequiredProperty("my-integer", Integer.class), - equalTo(123)); + assertThat(this.resolver.getRequiredProperty("my-integer", Integer.class)) + .isEqualTo(123); this.thrown.expect(IllegalStateException.class); this.thrown.expectMessage("required key [my-missing] not found"); this.resolver.getRequiredProperty("my-missing", Integer.class); @@ -91,50 +88,49 @@ public class RelaxedPropertyResolverTests { @Test public void getProperty() throws Exception { - assertThat(this.resolver.getProperty("my-string"), equalTo("value")); - assertThat(this.resolver.getProperty("my-missing"), nullValue()); + assertThat(this.resolver.getProperty("my-string")).isEqualTo("value"); + assertThat(this.resolver.getProperty("my-missing")).isNull(); } @Test public void getPropertyNoSeparator() throws Exception { - assertThat(this.resolver.getProperty("myobject"), equalTo("object")); - assertThat(this.resolver.getProperty("my-object"), equalTo("object")); + assertThat(this.resolver.getProperty("myobject")).isEqualTo("object"); + assertThat(this.resolver.getProperty("my-object")).isEqualTo("object"); } @Test public void getPropertyWithDefault() throws Exception { - assertThat(this.resolver.getProperty("my-string", "a"), equalTo("value")); - assertThat(this.resolver.getProperty("my-missing", "a"), equalTo("a")); + assertThat(this.resolver.getProperty("my-string", "a")).isEqualTo("value"); + assertThat(this.resolver.getProperty("my-missing", "a")).isEqualTo("a"); } @Test public void getPropertyWithType() throws Exception { - assertThat(this.resolver.getProperty("my-integer", Integer.class), equalTo(123)); - assertThat(this.resolver.getProperty("my-missing", Integer.class), nullValue()); + assertThat(this.resolver.getProperty("my-integer", Integer.class)).isEqualTo(123); + assertThat(this.resolver.getProperty("my-missing", Integer.class)).isNull(); } @Test public void getPropertyWithTypeAndDefault() throws Exception { - assertThat(this.resolver.getProperty("my-integer", Integer.class, 345), - equalTo(123)); - assertThat(this.resolver.getProperty("my-missing", Integer.class, 345), - equalTo(345)); + assertThat(this.resolver.getProperty("my-integer", Integer.class, 345)) + .isEqualTo(123); + assertThat(this.resolver.getProperty("my-missing", Integer.class, 345)) + .isEqualTo(345); } @Test public void getPropertyAsClass() throws Exception { - assertThat(this.resolver.getPropertyAsClass("my-class", String.class), - equalTo(String.class)); - assertThat(this.resolver.getPropertyAsClass("my-missing", String.class), - nullValue()); + assertThat(this.resolver.getPropertyAsClass("my-class", String.class)) + .isEqualTo(String.class); + assertThat(this.resolver.getPropertyAsClass("my-missing", String.class)).isNull(); } @Test public void containsProperty() throws Exception { - assertThat(this.resolver.containsProperty("my-string"), equalTo(true)); - assertThat(this.resolver.containsProperty("myString"), equalTo(true)); - assertThat(this.resolver.containsProperty("my_string"), equalTo(true)); - assertThat(this.resolver.containsProperty("my-missing"), equalTo(false)); + assertThat(this.resolver.containsProperty("my-string")).isTrue(); + assertThat(this.resolver.containsProperty("myString")).isTrue(); + assertThat(this.resolver.containsProperty("my_string")).isTrue(); + assertThat(this.resolver.containsProperty("my-missing")).isFalse(); } @Test @@ -153,8 +149,8 @@ public class RelaxedPropertyResolverTests { public void prefixed() throws Exception { this.resolver = new RelaxedPropertyResolver(this.environment, "a.b.c."); this.source.put("a.b.c.d", "test"); - assertThat(this.resolver.containsProperty("d"), equalTo(true)); - assertThat(this.resolver.getProperty("d"), equalTo("test")); + assertThat(this.resolver.containsProperty("d")).isTrue(); + assertThat(this.resolver.getProperty("d")).isEqualTo("test"); } @Test @@ -162,9 +158,9 @@ public class RelaxedPropertyResolverTests { this.resolver = new RelaxedPropertyResolver(this.environment, "a."); this.source.put("A_B", "test"); this.source.put("a.foobar", "spam"); - assertThat(this.resolver.containsProperty("b"), equalTo(true)); - assertThat(this.resolver.getProperty("b"), equalTo("test")); - assertThat(this.resolver.getProperty("foo-bar"), equalTo("spam")); + assertThat(this.resolver.containsProperty("b")).isTrue(); + assertThat(this.resolver.getProperty("b")).isEqualTo("test"); + assertThat(this.resolver.getProperty("foo-bar")).isEqualTo("spam"); } @Test @@ -174,10 +170,10 @@ public class RelaxedPropertyResolverTests { this.source.put("x.y.MY_SUB.a.d", "3"); this.resolver = new RelaxedPropertyResolver(this.environment, "x.y."); Map subProperties = this.resolver.getSubProperties("my-sub."); - assertThat(subProperties.size(), equalTo(3)); - assertThat(subProperties.get("a.b"), equalTo((Object) "1")); - assertThat(subProperties.get("a.c"), equalTo((Object) "2")); - assertThat(subProperties.get("a.d"), equalTo((Object) "3")); + assertThat(subProperties.size()).isEqualTo(3); + assertThat(subProperties.get("a.b")).isEqualTo("1"); + assertThat(subProperties.get("a.c")).isEqualTo("2"); + assertThat(subProperties.get("a.d")).isEqualTo("3"); } @Test @@ -202,7 +198,7 @@ public class RelaxedPropertyResolverTests { String directProperty = propertyResolver.getProperty(propertyName); Map subProperties = propertyResolver.getSubProperties(""); String subProperty = (String) subProperties.get(propertyName); - assertEquals(directProperty, subProperty); + assertThat(subProperty).isEqualTo(directProperty); } } diff --git a/spring-boot/src/test/java/org/springframework/boot/bind/SimplerPropertySourcesBindingTests.java b/spring-boot/src/test/java/org/springframework/boot/bind/SimplerPropertySourcesBindingTests.java index 44f7d6275f..d61155b480 100644 --- a/spring-boot/src/test/java/org/springframework/boot/bind/SimplerPropertySourcesBindingTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/bind/SimplerPropertySourcesBindingTests.java @@ -33,8 +33,7 @@ import org.springframework.context.annotation.PropertySources; import org.springframework.context.support.PropertySourcesPlaceholderConfigurer; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import static org.hamcrest.Matchers.is; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link PropertySourcesPropertyValues} binding. @@ -54,7 +53,7 @@ public class SimplerPropertySourcesBindingTests { @Test public void overridingOfPropertiesWorksAsExpected() { - assertThat(this.foo, is(this.properties.getFoo())); + assertThat(this.foo).isEqualTo(this.properties.getFoo()); } @PropertySources({ @PropertySource("classpath:/override.properties"), diff --git a/spring-boot/src/test/java/org/springframework/boot/bind/YamlConfigurationFactoryTests.java b/spring-boot/src/test/java/org/springframework/boot/bind/YamlConfigurationFactoryTests.java index f22be60ca8..b18e347ac0 100644 --- a/spring-boot/src/test/java/org/springframework/boot/bind/YamlConfigurationFactoryTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/bind/YamlConfigurationFactoryTests.java @@ -31,7 +31,7 @@ import org.springframework.validation.BindException; import org.springframework.validation.Validator; import org.springframework.validation.beanvalidation.SpringValidatorAdapter; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link YamlConfigurationFactory} @@ -71,14 +71,14 @@ public class YamlConfigurationFactoryTests { @Test public void testValidYamlLoadsWithNoErrors() throws Exception { Foo foo = createFoo("name: blah\nbar: blah"); - assertEquals("blah", foo.bar); + assertThat(foo.bar).isEqualTo("blah"); } @Test public void testValidYamlWithAliases() throws Exception { this.aliases.put(Foo.class, Collections.singletonMap("foo-name", "name")); Foo foo = createFoo("foo-name: blah\nbar: blah"); - assertEquals("blah", foo.name); + assertThat(foo.name).isEqualTo("blah"); } @Test(expected = YAMLException.class) @@ -96,7 +96,7 @@ public class YamlConfigurationFactoryTests { @Test public void testWithPeriodInKey() throws Exception { Jee jee = createJee("mymap:\n ? key1.key2\n : value"); - assertEquals("value", jee.mymap.get("key1.key2")); + assertThat(jee.mymap.get("key1.key2")).isEqualTo("value"); } private static class Foo { diff --git a/spring-boot/src/test/java/org/springframework/boot/builder/SpringApplicationBuilderTests.java b/spring-boot/src/test/java/org/springframework/boot/builder/SpringApplicationBuilderTests.java index f6dbb00d8a..ed9e3dc5a0 100644 --- a/spring-boot/src/test/java/org/springframework/boot/builder/SpringApplicationBuilderTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/builder/SpringApplicationBuilderTests.java @@ -35,11 +35,7 @@ import org.springframework.core.io.DefaultResourceLoader; import org.springframework.core.io.ResourceLoader; import org.springframework.util.StringUtils; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.instanceOf; -import static org.hamcrest.Matchers.is; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Matchers.any; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.verify; @@ -64,10 +60,9 @@ public class SpringApplicationBuilderTests { .sources(ExampleConfig.class).contextClass(StaticApplicationContext.class) .profiles("foo").properties("foo=bar"); this.context = application.run(); - assertThat(this.context, is(instanceOf(StaticApplicationContext.class))); - assertThat(this.context.getEnvironment().getProperty("foo"), - is(equalTo("bucket"))); - assertThat(this.context.getEnvironment().acceptsProfiles("foo"), is(true)); + assertThat(this.context).isInstanceOf(StaticApplicationContext.class); + assertThat(this.context.getEnvironment().getProperty("foo")).isEqualTo("bucket"); + assertThat(this.context.getEnvironment().acceptsProfiles("foo")).isTrue(); } @Test @@ -76,7 +71,7 @@ public class SpringApplicationBuilderTests { .sources(ExampleConfig.class).contextClass(StaticApplicationContext.class) .properties(Collections.singletonMap("bar", "foo")); this.context = application.run(); - assertThat(this.context.getEnvironment().getProperty("bar"), is(equalTo("foo"))); + assertThat(this.context.getEnvironment().getProperty("bar")).isEqualTo("foo"); } @Test @@ -86,7 +81,7 @@ public class SpringApplicationBuilderTests { .properties(StringUtils.splitArrayElementsIntoProperties( new String[] { "bar=foo" }, "=")); this.context = application.run(); - assertThat(this.context.getEnvironment().getProperty("bar"), is(equalTo("foo"))); + assertThat(this.context.getEnvironment().getProperty("bar")).isEqualTo("foo"); } @Test @@ -95,7 +90,7 @@ public class SpringApplicationBuilderTests { .sources(ExampleConfig.class) .contextClass(StaticApplicationContext.class); this.context = application.run(); - assertThat(this.context, is(instanceOf(StaticApplicationContext.class))); + assertThat(this.context).isInstanceOf(StaticApplicationContext.class); } @Test @@ -106,8 +101,8 @@ public class SpringApplicationBuilderTests { this.context = application.run(); verify(((SpyApplicationContext) this.context).getApplicationContext()) .setParent(any(ApplicationContext.class)); - assertThat(((SpyApplicationContext) this.context).getRegisteredShutdownHook(), - equalTo(false)); + assertThat(((SpyApplicationContext) this.context).getRegisteredShutdownHook()) + .isFalse(); } @Test @@ -118,8 +113,8 @@ public class SpringApplicationBuilderTests { this.context = application.build().run(); verify(((SpyApplicationContext) this.context).getApplicationContext()) .setParent(any(ApplicationContext.class)); - assertThat(((SpyApplicationContext) this.context).getRegisteredShutdownHook(), - equalTo(false)); + assertThat(((SpyApplicationContext) this.context).getRegisteredShutdownHook()) + .isFalse(); } @Test @@ -131,8 +126,8 @@ public class SpringApplicationBuilderTests { this.context = application.run(); verify(((SpyApplicationContext) this.context).getApplicationContext()) .setParent(any(ApplicationContext.class)); - assertThat(((SpyApplicationContext) this.context).getRegisteredShutdownHook(), - equalTo(true)); + assertThat(((SpyApplicationContext) this.context).getRegisteredShutdownHook()) + .isTrue(); } @Test @@ -143,8 +138,8 @@ public class SpringApplicationBuilderTests { getClass().getClassLoader()); application.resourceLoader(new DefaultResourceLoader(classLoader)); this.context = application.run(); - assertThat(((SpyApplicationContext) this.context).getClassLoader(), - is(equalTo(classLoader))); + assertThat(((SpyApplicationContext) this.context).getClassLoader()) + .isEqualTo(classLoader); } @Test @@ -157,7 +152,7 @@ public class SpringApplicationBuilderTests { application.parent(ExampleConfig.class); this.context = application.run(); assertThat(((SpyApplicationContext) this.context).getResourceLoader() - .getClassLoader(), is(equalTo(classLoader))); + .getClassLoader()).isEqualTo(classLoader); } @Test @@ -168,8 +163,8 @@ public class SpringApplicationBuilderTests { this.context = application.run(); verify(((SpyApplicationContext) this.context).getApplicationContext()) .setParent(any(ApplicationContext.class)); - assertThat(((SpyApplicationContext) this.context).getRegisteredShutdownHook(), - equalTo(false)); + assertThat(((SpyApplicationContext) this.context).getRegisteredShutdownHook()) + .isFalse(); } @Test @@ -178,15 +173,15 @@ public class SpringApplicationBuilderTests { ExampleConfig.class).profiles("node").properties("transport=redis") .child(ChildConfig.class).web(false); this.context = application.run(); - assertThat(this.context.getEnvironment().acceptsProfiles("node"), is(true)); - assertThat(this.context.getEnvironment().getProperty("transport"), - is(equalTo("redis"))); - assertThat(this.context.getParent().getEnvironment().acceptsProfiles("node"), - is(true)); - assertThat(this.context.getParent().getEnvironment().getProperty("transport"), - is(equalTo("redis"))); + assertThat(this.context.getEnvironment().acceptsProfiles("node")).isTrue(); + assertThat(this.context.getEnvironment().getProperty("transport")) + .isEqualTo("redis"); + assertThat(this.context.getParent().getEnvironment().acceptsProfiles("node")) + .isTrue(); + assertThat(this.context.getParent().getEnvironment().getProperty("transport")) + .isEqualTo("redis"); // only defined in node profile - assertThat(this.context.getEnvironment().getProperty("bar"), is(equalTo("spam"))); + assertThat(this.context.getEnvironment().getProperty("bar")).isEqualTo("spam"); } @Test @@ -195,10 +190,10 @@ public class SpringApplicationBuilderTests { ExampleConfig.class).profiles("node").properties("transport=redis") .child(ChildConfig.class).profiles("admin").web(false); this.context = application.run(); - assertThat(this.context.getEnvironment().acceptsProfiles("node", "admin"), - is(true)); - assertThat(this.context.getParent().getEnvironment().acceptsProfiles("admin"), - is(false)); + assertThat(this.context.getEnvironment().acceptsProfiles("node", "admin")) + .isTrue(); + assertThat(this.context.getParent().getEnvironment().acceptsProfiles("admin")) + .isFalse(); } @Test @@ -209,12 +204,12 @@ public class SpringApplicationBuilderTests { .profiles("admin").web(false); shared.profiles("parent"); this.context = application.run(); - assertThat(this.context.getEnvironment().acceptsProfiles("node", "admin"), - is(true)); + assertThat(this.context.getEnvironment().acceptsProfiles("node", "admin")) + .isTrue(); assertThat(this.context.getParent().getEnvironment().acceptsProfiles("node", - "parent"), is(true)); - assertThat(this.context.getParent().getEnvironment().acceptsProfiles("admin"), - is(false)); + "parent")).isTrue(); + assertThat(this.context.getParent().getEnvironment().acceptsProfiles("admin")) + .isFalse(); } @Test @@ -224,12 +219,12 @@ public class SpringApplicationBuilderTests { .profiles("node").properties("transport=redis") .child(ChildConfig.class).profiles("admin").web(false); this.context = application.run(); - assertThat(this.context.getEnvironment().acceptsProfiles("node", "admin"), - is(true)); + assertThat(this.context.getEnvironment().acceptsProfiles("node", "admin")) + .isTrue(); // Now they share an Environment explicitly so there's no way to keep the profiles // separate - assertThat(this.context.getParent().getEnvironment().acceptsProfiles("admin"), - is(true)); + assertThat(this.context.getParent().getEnvironment().acceptsProfiles("admin")) + .isTrue(); } @Test @@ -248,7 +243,7 @@ public class SpringApplicationBuilderTests { SpringApplicationBuilder application = new SpringApplicationBuilder( ExampleConfig.class).web(false); this.context = application.run(); - assertEquals(4, application.application().getInitializers().size()); + assertThat(application.application().getInitializers()).hasSize(4); } @Test @@ -256,7 +251,7 @@ public class SpringApplicationBuilderTests { SpringApplicationBuilder application = new SpringApplicationBuilder( ExampleConfig.class).child(ChildConfig.class).web(false); this.context = application.run(); - assertEquals(5, application.application().getInitializers().size()); + assertThat(application.application().getInitializers()).hasSize(5); } @Test @@ -270,7 +265,7 @@ public class SpringApplicationBuilderTests { } }); this.context = application.run(); - assertEquals(5, application.application().getInitializers().size()); + assertThat(application.application().getInitializers()).hasSize(5); } @Configuration diff --git a/spring-boot/src/test/java/org/springframework/boot/cloud/CloudPlatformTests.java b/spring-boot/src/test/java/org/springframework/boot/cloud/CloudPlatformTests.java index 4f6f66d16c..1bdc852158 100644 --- a/spring-boot/src/test/java/org/springframework/boot/cloud/CloudPlatformTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/cloud/CloudPlatformTests.java @@ -21,9 +21,7 @@ import org.junit.Test; import org.springframework.core.env.Environment; import org.springframework.mock.env.MockEnvironment; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.nullValue; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link CloudPlatform}. @@ -35,14 +33,14 @@ public class CloudPlatformTests { @Test public void getActiveWhenEnvironmentIsNullShouldReturnNull() throws Exception { CloudPlatform platform = CloudPlatform.getActive(null); - assertThat(platform, nullValue()); + assertThat(platform).isNull(); } @Test public void getActiveWhenNotInCloudShouldReturnNull() throws Exception { Environment environment = new MockEnvironment(); CloudPlatform platform = CloudPlatform.getActive(environment); - assertThat(platform, nullValue()); + assertThat(platform).isNull(); } @@ -52,8 +50,8 @@ public class CloudPlatformTests { Environment environment = new MockEnvironment().withProperty("VCAP_APPLICATION", "---"); CloudPlatform platform = CloudPlatform.getActive(environment); - assertThat(platform, equalTo(CloudPlatform.CLOUD_FOUNDRY)); - assertThat(platform.isActive(environment), equalTo(true)); + assertThat(platform).isEqualTo(CloudPlatform.CLOUD_FOUNDRY); + assertThat(platform.isActive(environment)).isTrue(); } @Test @@ -61,16 +59,16 @@ public class CloudPlatformTests { Environment environment = new MockEnvironment().withProperty("VCAP_SERVICES", "---"); CloudPlatform platform = CloudPlatform.getActive(environment); - assertThat(platform, equalTo(CloudPlatform.CLOUD_FOUNDRY)); - assertThat(platform.isActive(environment), equalTo(true)); + assertThat(platform).isEqualTo(CloudPlatform.CLOUD_FOUNDRY); + assertThat(platform.isActive(environment)).isTrue(); } @Test public void getActiveWhenHasDynoShouldReturnHeroku() throws Exception { Environment environment = new MockEnvironment().withProperty("DYNO", "---"); CloudPlatform platform = CloudPlatform.getActive(environment); - assertThat(platform, equalTo(CloudPlatform.HEROKU)); - assertThat(platform.isActive(environment), equalTo(true)); + assertThat(platform).isEqualTo(CloudPlatform.HEROKU); + assertThat(platform.isActive(environment)).isTrue(); } } diff --git a/spring-boot/src/test/java/org/springframework/boot/cloud/cloudfoundry/CloudFoundryVcapEnvironmentPostProcessorTests.java b/spring-boot/src/test/java/org/springframework/boot/cloud/cloudfoundry/CloudFoundryVcapEnvironmentPostProcessorTests.java index 442ce96feb..714162bb62 100644 --- a/spring-boot/src/test/java/org/springframework/boot/cloud/cloudfoundry/CloudFoundryVcapEnvironmentPostProcessorTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/cloud/cloudfoundry/CloudFoundryVcapEnvironmentPostProcessorTests.java @@ -23,8 +23,7 @@ import org.springframework.boot.test.EnvironmentTestUtils; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.annotation.AnnotationConfigApplicationContext; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link CloudFoundryVcapEnvironmentPostProcessor}. @@ -54,8 +53,9 @@ public class CloudFoundryVcapEnvironmentPostProcessorTests { + "\"users\":[],\"start\":\"2013-05-29 02:37:59 +0000\"," + "\"state_timestamp\":1369795079}"); this.initializer.postProcessEnvironment(this.context.getEnvironment(), null); - assertEquals("bb7935245adf3e650dfb7c58a06e9ece", this.context.getEnvironment() - .getProperty("vcap.application.instance_id")); + assertThat( + this.context.getEnvironment().getProperty("vcap.application.instance_id")) + .isEqualTo("bb7935245adf3e650dfb7c58a06e9ece"); } @Test @@ -63,15 +63,15 @@ public class CloudFoundryVcapEnvironmentPostProcessorTests { EnvironmentTestUtils.addEnvironment(this.context, "VCAP_APPLICATION:{\"instance_id\":\"bb7935245adf3e650dfb7c58a06e9ece\",\"instance_index\":0,\"uris\":[\"foo.cfapps.io\"]}"); this.initializer.postProcessEnvironment(this.context.getEnvironment(), null); - assertEquals("foo.cfapps.io", - this.context.getEnvironment().getProperty("vcap.application.uris[0]")); + assertThat(this.context.getEnvironment().getProperty("vcap.application.uris[0]")) + .isEqualTo("foo.cfapps.io"); } @Test public void testUnparseableApplicationProperties() { EnvironmentTestUtils.addEnvironment(this.context, "VCAP_APPLICATION:"); this.initializer.postProcessEnvironment(this.context.getEnvironment(), null); - assertNull(getProperty("vcap")); + assertThat(getProperty("vcap")).isNull(); } @Test @@ -90,7 +90,7 @@ public class CloudFoundryVcapEnvironmentPostProcessorTests { + "\"users\":[],\"start\":\"2013-05-29 02:37:59 +0000\"," + "\"state_timestamp\":1369795079}"); this.initializer.postProcessEnvironment(this.context.getEnvironment(), null); - assertNull(getProperty("vcap")); + assertThat(getProperty("vcap")).isNull(); } @Test @@ -106,10 +106,10 @@ public class CloudFoundryVcapEnvironmentPostProcessorTests { + "\"port\":3306,\"user\":\"urpRuqTf8Cpe6\",\"username\":" + "\"urpRuqTf8Cpe6\",\"password\":\"pxLsGVpsC9A5S\"}}]}"); this.initializer.postProcessEnvironment(this.context.getEnvironment(), null); - assertEquals("mysql", getProperty("vcap.services.mysql.name")); - assertEquals("3306", getProperty("vcap.services.mysql.credentials.port")); - assertEquals("true", getProperty("vcap.services.mysql.credentials.ssl")); - assertEquals("", getProperty("vcap.services.mysql.credentials.location")); + assertThat(getProperty("vcap.services.mysql.name")).isEqualTo("mysql"); + assertThat(getProperty("vcap.services.mysql.credentials.port")).isEqualTo("3306"); + assertThat(getProperty("vcap.services.mysql.credentials.ssl")).isEqualTo("true"); + assertThat(getProperty("vcap.services.mysql.credentials.location")).isEqualTo(""); } @Test @@ -124,8 +124,8 @@ public class CloudFoundryVcapEnvironmentPostProcessorTests { + "\"username\":\"urpRuqTf8Cpe6\"," + "\"password\":\"pxLsGVpsC9A5S\"}}]}"); this.initializer.postProcessEnvironment(this.context.getEnvironment(), null); - assertEquals("mysql", getProperty("vcap.services.mysql.name")); - assertEquals("3306", getProperty("vcap.services.mysql.credentials.port")); + assertThat(getProperty("vcap.services.mysql.name")).isEqualTo("mysql"); + assertThat(getProperty("vcap.services.mysql.credentials.port")).isEqualTo("3306"); } private String getProperty(String key) { diff --git a/spring-boot/src/test/java/org/springframework/boot/context/ConfigurationWarningsApplicationContextInitializerTests.java b/spring-boot/src/test/java/org/springframework/boot/context/ConfigurationWarningsApplicationContextInitializerTests.java index c9d7559742..76636c69a4 100644 --- a/spring-boot/src/test/java/org/springframework/boot/context/ConfigurationWarningsApplicationContextInitializerTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/context/ConfigurationWarningsApplicationContextInitializerTests.java @@ -36,9 +36,7 @@ import org.springframework.boot.context.configwarnings.real.InRealPackageConfigu import org.springframework.boot.test.OutputCapture; import org.springframework.context.annotation.AnnotationConfigApplicationContext; -import static org.hamcrest.Matchers.containsString; -import static org.hamcrest.Matchers.not; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link ConfigurationWarningsApplicationContextInitializer}. @@ -59,57 +57,57 @@ public class ConfigurationWarningsApplicationContextInitializerTests { @Test public void logWarningInDefaultPackage() { load(InDefaultPackageConfiguration.class); - assertThat(this.output.toString(), containsString(DEFAULT_SCAN_WARNING)); + assertThat(this.output.toString()).contains(DEFAULT_SCAN_WARNING); } @Test public void logWarningInDefaultPackageAndMetaAnnotation() { load(InDefaultPackageWithMetaAnnotationConfiguration.class); - assertThat(this.output.toString(), containsString(DEFAULT_SCAN_WARNING)); + assertThat(this.output.toString()).contains(DEFAULT_SCAN_WARNING); } @Test public void noLogIfInRealPackage() throws Exception { load(InRealPackageConfiguration.class); - assertThat(this.output.toString(), not(containsString(DEFAULT_SCAN_WARNING))); + assertThat(this.output.toString()).doesNotContain(DEFAULT_SCAN_WARNING); } @Test public void noLogWithoutComponentScanAnnotation() throws Exception { load(InDefaultPackageWithoutScanConfiguration.class); - assertThat(this.output.toString(), not(containsString(DEFAULT_SCAN_WARNING))); + assertThat(this.output.toString()).doesNotContain(DEFAULT_SCAN_WARNING); } @Test public void noLogIfHasValue() throws Exception { load(InDefaultPackageWithValueConfiguration.class); - assertThat(this.output.toString(), not(containsString(DEFAULT_SCAN_WARNING))); + assertThat(this.output.toString()).doesNotContain(DEFAULT_SCAN_WARNING); } @Test public void noLogIfHasBasePackages() throws Exception { load(InDefaultPackageWithBasePackagesConfiguration.class); - assertThat(this.output.toString(), not(containsString(DEFAULT_SCAN_WARNING))); + assertThat(this.output.toString()).doesNotContain(DEFAULT_SCAN_WARNING); } @Test public void noLogIfHasBasePackageClasses() throws Exception { load(InDefaultPackageWithBasePackageClassesConfiguration.class); - assertThat(this.output.toString(), not(containsString(DEFAULT_SCAN_WARNING))); + assertThat(this.output.toString()).doesNotContain(DEFAULT_SCAN_WARNING); } @Test public void logWarningInOrgSpringPackage() { load(InOrgSpringPackageConfiguration.class); - assertThat(this.output.toString(), containsString(ORGSPRING_SCAN_WARNING)); + assertThat(this.output.toString()).contains(ORGSPRING_SCAN_WARNING); } @Test public void logWarningIfScanningProblemPackages() throws Exception { load(InRealButScanningProblemPackages.class); - assertThat(this.output.toString(), - containsString("Your ApplicationContext is unlikely to start due to a " - + "@ComponentScan of the default package, 'org.springframework'.")); + assertThat(this.output.toString()) + .contains("Your ApplicationContext is unlikely to start due to a " + + "@ComponentScan of the default package, 'org.springframework'."); } diff --git a/spring-boot/src/test/java/org/springframework/boot/context/ContextIdApplicationContextInitializerTests.java b/spring-boot/src/test/java/org/springframework/boot/context/ContextIdApplicationContextInitializerTests.java index 48df45a08c..e1720f2558 100644 --- a/spring-boot/src/test/java/org/springframework/boot/context/ContextIdApplicationContextInitializerTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/context/ContextIdApplicationContextInitializerTests.java @@ -22,7 +22,7 @@ import org.springframework.boot.test.EnvironmentTestUtils; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.annotation.AnnotationConfigApplicationContext; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link ContextIdApplicationContextInitializer}. @@ -37,7 +37,7 @@ public class ContextIdApplicationContextInitializerTests { public void testDefaults() { ConfigurableApplicationContext context = new AnnotationConfigApplicationContext(); this.initializer.initialize(context); - assertEquals("application", context.getId()); + assertThat(context.getId()).isEqualTo("application"); } @Test @@ -46,7 +46,7 @@ public class ContextIdApplicationContextInitializerTests { EnvironmentTestUtils.addEnvironment(context, "spring.application.name:foo", "PORT:8080"); this.initializer.initialize(context); - assertEquals("foo:8080", context.getId()); + assertThat(context.getId()).isEqualTo("foo:8080"); } @Test @@ -55,7 +55,7 @@ public class ContextIdApplicationContextInitializerTests { EnvironmentTestUtils.addEnvironment(context, "spring.application.name:foo", "spring.profiles.active: spam,bar", "spring.application.index:12"); this.initializer.initialize(context); - assertEquals("foo:spam,bar:12", context.getId()); + assertThat(context.getId()).isEqualTo("foo:spam,bar:12"); } @Test @@ -65,7 +65,7 @@ public class ContextIdApplicationContextInitializerTests { "PORT:8080", "vcap.application.name:bar", "vcap.application.instance_index:2"); this.initializer.initialize(context); - assertEquals("bar:2", context.getId()); + assertThat(context.getId()).isEqualTo("bar:2"); } @Test @@ -75,7 +75,7 @@ public class ContextIdApplicationContextInitializerTests { "spring.config.name:foo", "PORT:8080", "vcap.application.name:bar", "vcap.application.instance_index:2"); this.initializer.initialize(context); - assertEquals("spam:2", context.getId()); + assertThat(context.getId()).isEqualTo("spam:2"); } } diff --git a/spring-boot/src/test/java/org/springframework/boot/context/config/ConfigFileApplicationListenerTests.java b/spring-boot/src/test/java/org/springframework/boot/context/config/ConfigFileApplicationListenerTests.java index 3b64e4b5f2..e1d28a8d92 100644 --- a/spring-boot/src/test/java/org/springframework/boot/context/config/ConfigFileApplicationListenerTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/context/config/ConfigFileApplicationListenerTests.java @@ -30,9 +30,7 @@ import java.util.Properties; import ch.qos.logback.classic.BasicConfigurator; import ch.qos.logback.classic.Logger; import ch.qos.logback.classic.LoggerContext; -import org.hamcrest.Description; -import org.hamcrest.Matcher; -import org.hamcrest.TypeSafeDiagnosingMatcher; +import org.assertj.core.api.Condition; import org.junit.After; import org.junit.Before; import org.junit.Rule; @@ -68,16 +66,7 @@ import org.springframework.core.io.ResourceLoader; import org.springframework.util.ReflectionUtils; import org.springframework.util.StringUtils; -import static org.hamcrest.Matchers.contains; -import static org.hamcrest.Matchers.containsInAnyOrder; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.not; -import static org.hamcrest.Matchers.notNullValue; -import static org.hamcrest.Matchers.nullValue; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link ConfigFileApplicationListener}. @@ -145,7 +134,7 @@ public class ConfigFileApplicationListenerTests { this.initializer.setSearchNames("custom"); this.initializer.postProcessEnvironment(this.environment, this.application); String property = this.environment.getProperty("the.property"); - assertThat(property, equalTo("fromcustom")); + assertThat(property).isEqualTo("fromcustom"); } @Test @@ -153,7 +142,7 @@ public class ConfigFileApplicationListenerTests { this.initializer.setSearchNames("testproperties"); this.initializer.postProcessEnvironment(this.environment, this.application); String property = this.environment.getProperty("the.property"); - assertThat(property, equalTo("frompropertiesfile")); + assertThat(property).isEqualTo("frompropertiesfile"); } @Test @@ -162,7 +151,7 @@ public class ConfigFileApplicationListenerTests { this.initializer.setSearchNames("testprofiles"); this.initializer.postProcessEnvironment(this.environment, this.application); String property = this.environment.getProperty("the.property"); - assertThat(property, equalTo("fromdefaultpropertiesfile")); + assertThat(property).isEqualTo("fromdefaultpropertiesfile"); } @Test @@ -171,7 +160,7 @@ public class ConfigFileApplicationListenerTests { + "classpath:application.properties,classpath:testproperties.properties"); this.initializer.postProcessEnvironment(this.environment, this.application); String property = this.environment.getProperty("the.property"); - assertThat(property, equalTo("frompropertiesfile")); + assertThat(property).isEqualTo("frompropertiesfile"); } @Test @@ -179,10 +168,9 @@ public class ConfigFileApplicationListenerTests { EnvironmentTestUtils.addEnvironment(this.environment, "spring.config.location:" + "classpath:enableprofile.properties,classpath:enableother.properties"); this.initializer.postProcessEnvironment(this.environment, this.application); - assertEquals("other", StringUtils - .arrayToCommaDelimitedString(this.environment.getActiveProfiles())); + assertThat(this.environment.getActiveProfiles()).containsExactly("other"); String property = this.environment.getProperty("my.property"); - assertThat(property, equalTo("fromotherpropertiesfile")); + assertThat(property).isEqualTo("fromotherpropertiesfile"); } @Test @@ -191,12 +179,11 @@ public class ConfigFileApplicationListenerTests { "spring.config.location:" + "classpath:enabletwoprofiles.properties," + "classpath:enableprofile.properties"); this.initializer.postProcessEnvironment(this.environment, this.application); - assertEquals("myprofile", StringUtils - .arrayToCommaDelimitedString(this.environment.getActiveProfiles())); + assertThat(this.environment.getActiveProfiles()).containsExactly("myprofile"); String property = this.environment.getProperty("the.property"); // The value from the second file wins (no profile-specific configuration is // actually loaded) - assertThat(property, equalTo("frompropertiesfile")); + assertThat(property).isEqualTo("frompropertiesfile"); } @Test @@ -206,18 +193,17 @@ public class ConfigFileApplicationListenerTests { "spring.config.name:enabletwoprofiles", "spring.config.location:classpath:enableprofile.properties"); this.initializer.postProcessEnvironment(this.environment, this.application); - assertEquals("myprofile", StringUtils - .arrayToCommaDelimitedString(this.environment.getActiveProfiles())); + assertThat(this.environment.getActiveProfiles()).containsExactly("myprofile"); String property = this.environment.getProperty("the.property"); // The value from the second file wins (no profile-specific configuration is // actually loaded) - assertThat(property, equalTo("frompropertiesfile")); + assertThat(property).isEqualTo("frompropertiesfile"); } @Test public void localFileTakesPrecedenceOverClasspath() throws Exception { File localFile = new File(new File("."), "application.properties"); - assertThat(localFile.exists(), equalTo(false)); + assertThat(localFile.exists()).isFalse(); try { Properties properties = new Properties(); properties.put("the.property", "fromlocalfile"); @@ -230,7 +216,7 @@ public class ConfigFileApplicationListenerTests { } this.initializer.postProcessEnvironment(this.environment, this.application); String property = this.environment.getProperty("the.property"); - assertThat(property, equalTo("fromlocalfile")); + assertThat(property).isEqualTo("fromlocalfile"); } finally { localFile.delete(); @@ -243,7 +229,7 @@ public class ConfigFileApplicationListenerTests { "spring.config.name:specific"); this.initializer.postProcessEnvironment(this.environment, this.application); String property = this.environment.getProperty("my.property"); - assertThat(property, equalTo("specific")); + assertThat(property).isEqualTo("specific"); } @Test @@ -254,14 +240,14 @@ public class ConfigFileApplicationListenerTests { + "classpath:nonexistent.properties"); this.initializer.postProcessEnvironment(this.environment, this.application); String property = this.environment.getProperty("the.property"); - assertThat(property, equalTo("frompropertiesfile")); + assertThat(property).isEqualTo("frompropertiesfile"); } @Test public void randomValue() throws Exception { this.initializer.postProcessEnvironment(this.environment, this.application); String property = this.environment.getProperty("random.value"); - assertThat(property, notNullValue()); + assertThat(property).isNotNull(); } @Test @@ -270,7 +256,7 @@ public class ConfigFileApplicationListenerTests { this.initializer.postProcessEnvironment(this.environment, this.application); String property = this.environment.getProperty("the.property"); // The search order has highest precedence last (like merging a map) - assertThat(property, equalTo("frompropertiesfile")); + assertThat(property).isEqualTo("frompropertiesfile"); } @Test @@ -278,9 +264,9 @@ public class ConfigFileApplicationListenerTests { this.initializer.setSearchNames("testyaml"); this.initializer.postProcessEnvironment(this.environment, this.application); String property = this.environment.getProperty("my.property"); - assertThat(property, equalTo("fromyamlfile")); - assertThat(this.environment.getProperty("my.array[0]"), equalTo("1")); - assertThat(this.environment.getProperty("my.array"), nullValue(String.class)); + assertThat(property).isEqualTo("fromyamlfile"); + assertThat(this.environment.getProperty("my.array[0]")).isEqualTo("1"); + assertThat(this.environment.getProperty("my.array")).isNull(); } @Test @@ -288,7 +274,7 @@ public class ConfigFileApplicationListenerTests { this.initializer.setSearchNames("testprofilesempty"); this.initializer.postProcessEnvironment(this.environment, this.application); String property = this.environment.getProperty("my.property"); - assertThat(property, equalTo("fromemptyprofile")); + assertThat(property).isEqualTo("fromemptyprofile"); } @Test @@ -297,7 +283,7 @@ public class ConfigFileApplicationListenerTests { this.initializer.setSearchNames("testprofilesdocument"); this.initializer.postProcessEnvironment(this.environment, this.application); String property = this.environment.getProperty("my.property"); - assertThat(property, equalTo("fromdefaultprofile")); + assertThat(property).isEqualTo("fromdefaultprofile"); } @Test @@ -307,7 +293,7 @@ public class ConfigFileApplicationListenerTests { this.initializer.setSearchNames("testprofilesdocument"); this.initializer.postProcessEnvironment(this.environment, this.application); String property = this.environment.getProperty("my.property"); - assertThat(property, equalTo("fromotherprofile")); + assertThat(property).isEqualTo("fromotherprofile"); } @Test @@ -317,7 +303,7 @@ public class ConfigFileApplicationListenerTests { this.initializer.setSearchNames("testproperties"); this.initializer.postProcessEnvironment(this.environment, this.application); String property = this.environment.getProperty("the.property"); - assertThat(property, equalTo("fromcommandline")); + assertThat(property).isEqualTo("fromcommandline"); } @Test @@ -326,7 +312,7 @@ public class ConfigFileApplicationListenerTests { this.initializer.setSearchNames("testproperties"); this.initializer.postProcessEnvironment(this.environment, this.application); String property = this.environment.getProperty("the.property"); - assertThat(property, equalTo("fromsystem")); + assertThat(property).isEqualTo("fromsystem"); } @Test @@ -336,7 +322,7 @@ public class ConfigFileApplicationListenerTests { Collections.singletonMap("my.fallback", (Object) "foo"))); this.initializer.postProcessEnvironment(this.environment, this.application); String property = this.environment.getProperty("my.fallback"); - assertThat(property, equalTo("foo")); + assertThat(property).isEqualTo("foo"); } @Test @@ -346,7 +332,7 @@ public class ConfigFileApplicationListenerTests { .singletonMap("spring.config.name", (Object) "testproperties"))); this.initializer.postProcessEnvironment(this.environment, this.application); String property = this.environment.getProperty("the.property"); - assertThat(property, equalTo("frompropertiesfile")); + assertThat(property).isEqualTo("frompropertiesfile"); } @Test @@ -359,7 +345,7 @@ public class ConfigFileApplicationListenerTests { String property = this.environment.getProperty("my.property"); // The "other" profile is activated in SpringApplication so it should take // precedence over the default profile - assertThat(property, equalTo("fromotherpropertiesfile")); + assertThat(property).isEqualTo("fromotherpropertiesfile"); } @Test @@ -371,7 +357,7 @@ public class ConfigFileApplicationListenerTests { String property = this.environment.getProperty("my.property"); // The "dev" profile is activated in SpringApplication so it should take // precedence over the default profile - assertThat(property, equalTo("fromdevpropertiesfile")); + assertThat(property).isEqualTo("fromdevpropertiesfile"); } @Test @@ -381,7 +367,7 @@ public class ConfigFileApplicationListenerTests { String property = this.environment.getProperty("the.property"); // The "myprofile" profile is activated in enableprofile.properties so its value // should show up here - assertThat(property, equalTo("fromprofilepropertiesfile")); + assertThat(property).isEqualTo("fromprofilepropertiesfile"); } @Test @@ -393,12 +379,12 @@ public class ConfigFileApplicationListenerTests { this.initializer.postProcessEnvironment(this.environment, this.application); String property = this.environment.getProperty("other.property"); // The "other" profile is activated before any processing starts - assertThat(property, equalTo("fromotherpropertiesfile")); + assertThat(property).isEqualTo("fromotherpropertiesfile"); property = this.environment.getProperty("the.property"); // The "myprofile" profile is activated in enableprofile.properties and "other" // was not activated by setting spring.profiles.active so "myprofile" should still // be activated - assertThat(property, equalTo("fromprofilepropertiesfile")); + assertThat(property).isEqualTo("fromprofilepropertiesfile"); } @Test @@ -406,7 +392,7 @@ public class ConfigFileApplicationListenerTests { this.initializer.setSearchNames("enableprofile"); this.initializer.postProcessEnvironment(this.environment, this.application); String property = this.environment.getProperty("one.more"); - assertThat(property, equalTo("fromprofilepropertiesfile")); + assertThat(property).isEqualTo("fromprofilepropertiesfile"); } @Test @@ -416,10 +402,9 @@ public class ConfigFileApplicationListenerTests { "spring.profiles.active:other"); this.environment.addActiveProfile("dev"); this.initializer.postProcessEnvironment(this.environment, this.application); - assertThat(Arrays.asList(this.environment.getActiveProfiles()), - containsInAnyOrder("dev", "other")); - assertThat(this.environment.getProperty("my.property"), - equalTo("fromotherpropertiesfile")); + assertThat(this.environment.getActiveProfiles()).contains("dev", "other"); + assertThat(this.environment.getProperty("my.property")) + .isEqualTo("fromotherpropertiesfile"); validateProfilePrecedence(null, "dev", "other"); } @@ -429,10 +414,9 @@ public class ConfigFileApplicationListenerTests { "spring.profiles.active:dev,other"); this.environment.addActiveProfile("dev"); this.initializer.postProcessEnvironment(this.environment, this.application); - assertThat(Arrays.asList(this.environment.getActiveProfiles()), - containsInAnyOrder("dev", "other")); - assertThat(this.environment.getProperty("my.property"), - equalTo("fromotherpropertiesfile")); + assertThat(this.environment.getActiveProfiles()).contains("dev", "other"); + assertThat(this.environment.getProperty("my.property")) + .isEqualTo("fromotherpropertiesfile"); validateProfilePrecedence(null, "dev", "other"); } @@ -443,10 +427,9 @@ public class ConfigFileApplicationListenerTests { "spring.profiles.active:other,dev"); this.environment.addActiveProfile("other"); this.initializer.postProcessEnvironment(this.environment, this.application); - assertThat(Arrays.asList(this.environment.getActiveProfiles()), - containsInAnyOrder("dev", "other")); - assertThat(this.environment.getProperty("my.property"), - equalTo("fromdevpropertiesfile")); + assertThat(this.environment.getActiveProfiles()).contains("dev", "other"); + assertThat(this.environment.getProperty("my.property")) + .isEqualTo("fromdevpropertiesfile"); validateProfilePrecedence(null, "other", "dev"); } @@ -468,16 +451,16 @@ public class ConfigFileApplicationListenerTests { for (String profile : profiles) { String reason = "Wrong number of occurrences for profile '" + profile + "' --> " + log; - assertThat(reason, - StringUtils.countOccurrencesOf(log, createLogForProfile(profile)), - equalTo(1)); + assertThat(StringUtils.countOccurrencesOf(log, createLogForProfile(profile))) + .as(reason).isEqualTo(1); } // Make sure the order of loading is the right one for (String profile : profiles) { String line = createLogForProfile(profile); int index = log.indexOf(line); - assertTrue("Loading profile '" + profile + "' not found in '" + log + "'", - index != -1); + assertThat(index) + .as("Loading profile '" + profile + "' not found in '" + log + "'") + .isNotEqualTo(-1); log = log.substring(index + line.length(), log.length()); } } @@ -493,9 +476,9 @@ public class ConfigFileApplicationListenerTests { this.environment.setActiveProfiles("dev"); this.initializer.postProcessEnvironment(this.environment, this.application); String property = this.environment.getProperty("my.property"); - assertThat(property, equalTo("fromdevprofile")); + assertThat(property).isEqualTo("fromdevprofile"); property = this.environment.getProperty("my.other"); - assertThat(property, equalTo("notempty")); + assertThat(property).isEqualTo("notempty"); } @Test @@ -504,26 +487,25 @@ public class ConfigFileApplicationListenerTests { this.environment.setActiveProfiles("other", "dev"); this.initializer.postProcessEnvironment(this.environment, this.application); String property = this.environment.getProperty("my.property"); - assertThat(property, equalTo("fromdevprofile")); + assertThat(property).isEqualTo("fromdevprofile"); property = this.environment.getProperty("my.other"); - assertThat(property, equalTo("notempty")); + assertThat(property).isEqualTo("notempty"); } @Test public void yamlSetsProfiles() throws Exception { this.initializer.setSearchNames("testsetprofiles"); this.initializer.postProcessEnvironment(this.environment, this.application); - assertEquals("dev", StringUtils - .arrayToCommaDelimitedString(this.environment.getActiveProfiles())); + assertThat(this.environment.getActiveProfiles()).containsExactly("dev"); String property = this.environment.getProperty("my.property"); - assertThat(Arrays.asList(this.environment.getActiveProfiles()), contains("dev")); - assertThat(property, equalTo("fromdevprofile")); + assertThat(this.environment.getActiveProfiles()).contains("dev"); + assertThat(property).isEqualTo("fromdevprofile"); ConfigurationPropertySources propertySource = (ConfigurationPropertySources) this.environment .getPropertySources() .get(ConfigFileApplicationListener.APPLICATION_CONFIGURATION_PROPERTY_SOURCE_NAME); Collection> sources = propertySource .getSource(); - assertEquals(2, sources.size()); + assertThat(sources).hasSize(2); List names = new ArrayList(); for (org.springframework.core.env.PropertySource source : sources) { if (source instanceof EnumerableCompositePropertySource) { @@ -536,9 +518,9 @@ public class ConfigFileApplicationListenerTests { names.add(source.getName()); } } - assertThat(names, - contains("applicationConfig: [classpath:/testsetprofiles.yml]#dev", - "applicationConfig: [classpath:/testsetprofiles.yml]")); + assertThat(names).contains( + "applicationConfig: [classpath:/testsetprofiles.yml]#dev", + "applicationConfig: [classpath:/testsetprofiles.yml]"); } @Test @@ -547,8 +529,7 @@ public class ConfigFileApplicationListenerTests { "spring.profiles.active:prod"); this.initializer.setSearchNames("testsetprofiles"); this.initializer.postProcessEnvironment(this.environment, this.application); - assertThat(this.environment.getActiveProfiles(), - equalTo(new String[] { "prod" })); + assertThat(this.environment.getActiveProfiles()).containsExactly("prod"); } @Test @@ -558,7 +539,7 @@ public class ConfigFileApplicationListenerTests { "spring.config.name=specificfile"); this.initializer.postProcessEnvironment(this.environment, this.application); String property = this.environment.getProperty("my.property"); - assertThat(property, equalTo("fromspecificpropertiesfile")); + assertThat(property).isEqualTo("fromspecificpropertiesfile"); } @Test @@ -568,13 +549,13 @@ public class ConfigFileApplicationListenerTests { "spring.config.location:" + location); this.initializer.postProcessEnvironment(this.environment, this.application); String property = this.environment.getProperty("the.property"); - assertThat(property, equalTo("fromspecificlocation")); - assertThat(this.environment, containsPropertySource( + assertThat(property).isEqualTo("fromspecificlocation"); + assertThat(this.environment).has(matchingPropertySource( "applicationConfig: " + "[classpath:specificlocation.properties]")); // The default property source is still there - assertThat(this.environment, containsPropertySource( + assertThat(this.environment).has(matchingPropertySource( "applicationConfig: " + "[classpath:/application.properties]")); - assertThat(this.environment.getProperty("foo"), equalTo("bucket")); + assertThat(this.environment.getProperty("foo")).isEqualTo("bucket"); } @Test @@ -583,8 +564,8 @@ public class ConfigFileApplicationListenerTests { EnvironmentTestUtils.addEnvironment(this.environment, "spring.config.location:" + location); this.initializer.postProcessEnvironment(this.environment, this.application); - assertThat(this.environment, - containsPropertySource("applicationConfig: [" + location + "]")); + assertThat(this.environment) + .has(matchingPropertySource("applicationConfig: [" + location + "]")); } @Test @@ -593,8 +574,8 @@ public class ConfigFileApplicationListenerTests { EnvironmentTestUtils.addEnvironment(this.environment, "spring.config.location:" + location); this.initializer.postProcessEnvironment(this.environment, this.application); - assertThat(this.environment, - containsPropertySource("applicationConfig: [file:" + location + "]")); + assertThat(this.environment).has( + matchingPropertySource("applicationConfig: [file:" + location + "]")); } @Test @@ -604,8 +585,9 @@ public class ConfigFileApplicationListenerTests { EnvironmentTestUtils.addEnvironment(this.environment, "spring.config.location:" + location); this.initializer.postProcessEnvironment(this.environment, this.application); - assertThat(this.environment, containsPropertySource("applicationConfig: [file:" - + location.replace(File.separatorChar, '/') + "]")); + assertThat(this.environment) + .has(matchingPropertySource("applicationConfig: [file:" + + location.replace(File.separatorChar, '/') + "]")); } @Test @@ -614,10 +596,10 @@ public class ConfigFileApplicationListenerTests { application.setWebEnvironment(false); ConfigurableApplicationContext context = application.run(); String property = context.getEnvironment().getProperty("the.property"); - assertThat(property, equalTo("fromspecificlocation")); + assertThat(property).isEqualTo("fromspecificlocation"); property = context.getEnvironment().getProperty("my.property"); - assertThat(property, equalTo("fromapplicationproperties")); - assertThat(context.getEnvironment(), containsPropertySource( + assertThat(property).isEqualTo("fromapplicationproperties"); + assertThat(context.getEnvironment()).has(matchingPropertySource( "class path resource " + "[specificlocation.properties]")); context.close(); } @@ -632,8 +614,8 @@ public class ConfigFileApplicationListenerTests { application.setWebEnvironment(false); ConfigurableApplicationContext context = application.run(); String property = context.getEnvironment().getProperty("the.property"); - assertThat(property, equalTo("fromspecificlocation")); - assertThat(context.getEnvironment(), containsPropertySource( + assertThat(property).isEqualTo("fromspecificlocation"); + assertThat(context.getEnvironment()).has(matchingPropertySource( "class path resource " + "[specificlocation.properties]")); context.close(); } @@ -645,8 +627,8 @@ public class ConfigFileApplicationListenerTests { application.setWebEnvironment(false); ConfigurableApplicationContext context = application.run(); String property = context.getEnvironment().getProperty("the.property"); - assertThat(property, equalTo("fromspecificlocation")); - assertThat(context.getEnvironment(), containsPropertySource("foo")); + assertThat(property).isEqualTo("fromspecificlocation"); + assertThat(context.getEnvironment()).has(matchingPropertySource("foo")); context.close(); } @@ -658,11 +640,11 @@ public class ConfigFileApplicationListenerTests { ConfigurableApplicationContext context = application .run("--spring.profiles.active=myprofile"); String property = context.getEnvironment().getProperty("the.property"); - assertThat(property, equalTo("frompropertiesfile")); - assertThat(context.getEnvironment(), containsPropertySource( + assertThat(property).isEqualTo("frompropertiesfile"); + assertThat(context.getEnvironment()).has(matchingPropertySource( "class path resource " + "[enableprofile.properties]")); - assertThat(context.getEnvironment(), not(containsPropertySource( - "classpath:/" + "enableprofile-myprofile.properties"))); + assertThat(context.getEnvironment()).doesNotHave(matchingPropertySource( + "classpath:/" + "enableprofile-myprofile.properties")); context.close(); } @@ -673,9 +655,9 @@ public class ConfigFileApplicationListenerTests { application.setWebEnvironment(false); ConfigurableApplicationContext context = application.run(); String property = context.getEnvironment().getProperty("my.property"); - assertThat(property, equalTo("fromapplicationproperties")); - assertThat(context.getEnvironment(), not(containsPropertySource( - "classpath:" + "/enableprofile-myprofile.properties"))); + assertThat(property).isEqualTo("fromapplicationproperties"); + assertThat(context.getEnvironment()).doesNotHave(matchingPropertySource( + "classpath:" + "/enableprofile-myprofile.properties")); context.close(); } @@ -686,8 +668,8 @@ public class ConfigFileApplicationListenerTests { application.setWebEnvironment(false); ConfigurableApplicationContext context = application.run(); String property = context.getEnvironment().getProperty("the.property"); - assertThat(property, equalTo("frommorepropertiesfile")); - assertThat(context.getEnvironment(), containsPropertySource( + assertThat(property).isEqualTo("frommorepropertiesfile"); + assertThat(context.getEnvironment()).has(matchingPropertySource( "class path resource " + "[specificlocation.properties]")); context.close(); } @@ -699,8 +681,8 @@ public class ConfigFileApplicationListenerTests { application.setWebEnvironment(false); ConfigurableApplicationContext context = application.run(); String property = context.getEnvironment().getProperty("the.property"); - assertThat(property, equalTo("frommorepropertiesfile")); - assertThat(context.getEnvironment(), containsPropertySource("foo")); + assertThat(property).isEqualTo("frommorepropertiesfile"); + assertThat(context.getEnvironment()).has(matchingPropertySource("foo")); context.close(); } @@ -709,11 +691,11 @@ public class ConfigFileApplicationListenerTests { SpringApplication application = new SpringApplication(Config.class); application.setWebEnvironment(false); this.context = application.run("--spring.profiles.active=includeprofile"); - assertThat(this.context.getEnvironment(), acceptsProfiles("includeprofile")); - assertThat(this.context.getEnvironment(), acceptsProfiles("specific")); - assertThat(this.context.getEnvironment(), acceptsProfiles("morespecific")); - assertThat(this.context.getEnvironment(), acceptsProfiles("yetmorespecific")); - assertThat(this.context.getEnvironment(), not(acceptsProfiles("missing"))); + assertThat(this.context.getEnvironment()).has(matchingProfile("includeprofile")); + assertThat(this.context.getEnvironment()).has(matchingProfile("specific")); + assertThat(this.context.getEnvironment()).has(matchingProfile("morespecific")); + assertThat(this.context.getEnvironment()).has(matchingProfile("yetmorespecific")); + assertThat(this.context.getEnvironment()).doesNotHave(matchingProfile("missing")); } @Test @@ -724,7 +706,7 @@ public class ConfigFileApplicationListenerTests { this.context = application .run("--spring.profiles.active=activeprofilewithsubdoc"); String property = this.context.getEnvironment().getProperty("foobar"); - assertThat(property, equalTo("baz")); + assertThat(property).isEqualTo("baz"); } @Test @@ -734,7 +716,7 @@ public class ConfigFileApplicationListenerTests { this.initializer.postProcessEnvironment(this.environment, this.application); Field field = ReflectionUtils.findField(SpringApplication.class, "bannerMode"); field.setAccessible(true); - assertThat((Banner.Mode) field.get(this.application), equalTo(Banner.Mode.OFF)); + assertThat((Banner.Mode) field.get(this.application)).isEqualTo(Banner.Mode.OFF); } @Test @@ -744,7 +726,7 @@ public class ConfigFileApplicationListenerTests { this.initializer.postProcessEnvironment(this.environment, this.application); Field field = ReflectionUtils.findField(SpringApplication.class, "bannerMode"); field.setAccessible(true); - assertThat((Banner.Mode) field.get(this.application), equalTo(Banner.Mode.OFF)); + assertThat((Banner.Mode) field.get(this.application)).isEqualTo(Banner.Mode.OFF); } @Test @@ -755,7 +737,7 @@ public class ConfigFileApplicationListenerTests { this.context = application.run( "--spring.profiles.active=activeprofilewithdifferentsubdoc,activeprofilewithdifferentsubdoc2"); String property = this.context.getEnvironment().getProperty("foobar"); - assertThat(property, equalTo("baz")); + assertThat(property).isEqualTo("baz"); } @Test @@ -764,7 +746,7 @@ public class ConfigFileApplicationListenerTests { this.initializer.postProcessEnvironment(this.environment, this.application); String property = System .getProperty(CachedIntrospectionResults.IGNORE_BEANINFO_PROPERTY_NAME); - assertThat(property, equalTo("true")); + assertThat(property).isEqualTo("true"); } @Test @@ -775,7 +757,7 @@ public class ConfigFileApplicationListenerTests { this.initializer.postProcessEnvironment(this.environment, this.application); String property = System .getProperty(CachedIntrospectionResults.IGNORE_BEANINFO_PROPERTY_NAME); - assertThat(property, equalTo("false")); + assertThat(property).isEqualTo("false"); } @Test @@ -787,47 +769,33 @@ public class ConfigFileApplicationListenerTests { this.initializer.setSearchNames("testproperties"); this.initializer.postProcessEnvironment(this.environment, this.application); String property = this.environment.getProperty("the.property"); - assertThat(property, equalTo("frompropertiesfile")); + assertThat(property).isEqualTo("frompropertiesfile"); } - private static Matcher containsPropertySource( + private Condition matchingPropertySource( final String sourceName) { - return new TypeSafeDiagnosingMatcher() { - @Override - public void describeTo(Description description) { - description.appendText("environment containing property source ") - .appendValue(sourceName); - } + return new Condition( + "environment containing property source " + sourceName) { @Override - protected boolean matchesSafely(ConfigurableEnvironment item, - Description mismatchDescription) { + public boolean matches(ConfigurableEnvironment value) { MutablePropertySources sources = new MutablePropertySources( - item.getPropertySources()); + value.getPropertySources()); ConfigurationPropertySources.finishAndRelocate(sources); - mismatchDescription.appendText("Not matched against: ") - .appendValue(sources); return sources.contains(sourceName); } + }; } - private static Matcher acceptsProfiles( - final String... profiles) { - return new TypeSafeDiagnosingMatcher() { - @Override - public void describeTo(Description description) { - description.appendText("environment accepting profiles ") - .appendValue(profiles); - } + private Condition matchingProfile(final String profile) { + return new Condition("accepts profile " + profile) { @Override - protected boolean matchesSafely(ConfigurableEnvironment item, - Description mismatchDescription) { - mismatchDescription.appendText("Not matched against: ") - .appendValue(item.getActiveProfiles()); - return item.acceptsProfiles(profiles); + public boolean matches(ConfigurableEnvironment value) { + return value.acceptsProfiles(profile); } + }; } @@ -899,7 +867,7 @@ public class ConfigFileApplicationListenerTests { @Override public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) { - assertThat(environment.getPropertySources().size(), is(equalTo(4))); + assertThat(environment.getPropertySources()).hasSize(4); } } diff --git a/spring-boot/src/test/java/org/springframework/boot/context/config/DelegatingApplicationContextInitializerTests.java b/spring-boot/src/test/java/org/springframework/boot/context/config/DelegatingApplicationContextInitializerTests.java index bc79f2d57a..9f7dc82ee8 100644 --- a/spring-boot/src/test/java/org/springframework/boot/context/config/DelegatingApplicationContextInitializerTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/context/config/DelegatingApplicationContextInitializerTests.java @@ -29,8 +29,7 @@ import org.springframework.core.Ordered; import org.springframework.core.annotation.Order; import org.springframework.web.context.ConfigurableWebApplicationContext; -import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link DelegatingApplicationContextInitializer}. @@ -50,8 +49,8 @@ public class DelegatingApplicationContextInitializerTests { EnvironmentTestUtils.addEnvironment(context, "context.initializer.classes:" + MockInitB.class.getName() + "," + MockInitA.class.getName()); this.initializer.initialize(context); - assertThat(context.getBeanFactory().getSingleton("a"), equalTo((Object) "a")); - assertThat(context.getBeanFactory().getSingleton("b"), equalTo((Object) "b")); + assertThat(context.getBeanFactory().getSingleton("a")).isEqualTo("a"); + assertThat(context.getBeanFactory().getSingleton("b")).isEqualTo("b"); } @Test @@ -98,27 +97,34 @@ public class DelegatingApplicationContextInitializerTests { @Order(Ordered.HIGHEST_PRECEDENCE) private static class MockInitA implements ApplicationContextInitializer { + @Override public void initialize(ConfigurableApplicationContext applicationContext) { applicationContext.getBeanFactory().registerSingleton("a", "a"); } + } @Order(Ordered.LOWEST_PRECEDENCE) private static class MockInitB implements ApplicationContextInitializer { + @Override public void initialize(ConfigurableApplicationContext applicationContext) { - assertThat(applicationContext.getBeanFactory().getSingleton("a"), - equalTo((Object) "a")); + assertThat(applicationContext.getBeanFactory().getSingleton("a")) + .isEqualTo("a"); applicationContext.getBeanFactory().registerSingleton("b", "b"); } + } private static class NotSuitableInit implements ApplicationContextInitializer { + @Override public void initialize(ConfigurableWebApplicationContext applicationContext) { } + } + } diff --git a/spring-boot/src/test/java/org/springframework/boot/context/config/DelegatingApplicationListenerTests.java b/spring-boot/src/test/java/org/springframework/boot/context/config/DelegatingApplicationListenerTests.java index dc2446018b..beccb15b31 100644 --- a/spring-boot/src/test/java/org/springframework/boot/context/config/DelegatingApplicationListenerTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/context/config/DelegatingApplicationListenerTests.java @@ -31,8 +31,7 @@ import org.springframework.context.support.StaticApplicationContext; import org.springframework.core.Ordered; import org.springframework.core.annotation.Order; -import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link DelegatingApplicationListener}. @@ -63,10 +62,8 @@ public class DelegatingApplicationListenerTests { new SpringApplication(), new String[0], this.context.getEnvironment())); this.context.getBeanFactory().registerSingleton("testListener", this.listener); this.context.refresh(); - assertThat(this.context.getBeanFactory().getSingleton("a"), - equalTo((Object) "a")); - assertThat(this.context.getBeanFactory().getSingleton("b"), - equalTo((Object) "b")); + assertThat(this.context.getBeanFactory().getSingleton("a")).isEqualTo("a"); + assertThat(this.context.getBeanFactory().getSingleton("b")).isEqualTo("b"); } @Test @@ -99,8 +96,8 @@ public class DelegatingApplicationListenerTests { public void onApplicationEvent(ContextRefreshedEvent event) { ConfigurableApplicationContext applicationContext = (ConfigurableApplicationContext) event .getApplicationContext(); - assertThat(applicationContext.getBeanFactory().getSingleton("a"), - equalTo((Object) "a")); + assertThat(applicationContext.getBeanFactory().getSingleton("a")) + .isEqualTo("a"); applicationContext.getBeanFactory().registerSingleton("b", "b"); } } diff --git a/spring-boot/src/test/java/org/springframework/boot/context/config/RandomValuePropertySourceTests.java b/spring-boot/src/test/java/org/springframework/boot/context/config/RandomValuePropertySourceTests.java index 0d316c314b..febe1f9e36 100644 --- a/spring-boot/src/test/java/org/springframework/boot/context/config/RandomValuePropertySourceTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/context/config/RandomValuePropertySourceTests.java @@ -21,9 +21,7 @@ import java.util.Random; import org.junit.Test; import org.mockito.Mockito; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link RandomValuePropertySource}. @@ -37,54 +35,50 @@ public class RandomValuePropertySourceTests { @Test public void notRandom() { - assertNull(this.source.getProperty("foo")); + assertThat(this.source.getProperty("foo")).isNull(); } @Test public void string() { - assertNotNull(this.source.getProperty("random.string")); + assertThat(this.source.getProperty("random.string")).isNotNull(); } @Test public void intValue() { Integer value = (Integer) this.source.getProperty("random.int"); - assertNotNull(value); + assertThat(value).isNotNull(); } @Test public void intRange() { Integer value = (Integer) this.source.getProperty("random.int[4,10]"); - assertNotNull(value); - assertTrue(value >= 4); - assertTrue(value < 10); + assertThat(value).isNotNull(); + assertThat(value >= 4).isTrue(); + assertThat(value < 10).isTrue(); } @Test public void intMax() { Integer value = (Integer) this.source.getProperty("random.int(10)"); - assertNotNull(value); - assertTrue(value < 10); + assertThat(value).isNotNull().isLessThan(10); } @Test public void longValue() { Long value = (Long) this.source.getProperty("random.long"); - assertNotNull(value); + assertThat(value).isNotNull(); } @Test public void longRange() { Long value = (Long) this.source.getProperty("random.long[4,10]"); - assertNotNull(value); - assertTrue(Long.toString(value), value >= 4L); - assertTrue(Long.toString(value), value < 10L); + assertThat(value).isNotNull().isBetween(4L, 10L); } @Test public void longMax() { Long value = (Long) this.source.getProperty("random.long(10)"); - assertNotNull(value); - assertTrue(value < 10L); + assertThat(value).isNotNull().isLessThan(10L); } @Test @@ -100,13 +94,9 @@ public class RandomValuePropertySourceTests { }); Long value = (Long) source.getProperty("random.long(10)"); - assertNotNull(value); - assertTrue(value + " is less than 0", value >= 0L); - assertTrue(value + " is more than 10", value < 10L); - + assertThat(value).isNotNull().isGreaterThanOrEqualTo(0L).isLessThan(10L); value = (Long) source.getProperty("random.long[4,10]"); - assertNotNull(value); - assertTrue(value + " is less than 4", value >= 4L); - assertTrue(value + " is more than 10", value < 10L); + assertThat(value).isNotNull().isGreaterThanOrEqualTo(4L).isLessThan(10L); } + } diff --git a/spring-boot/src/test/java/org/springframework/boot/context/embedded/AbstractEmbeddedServletContainerFactoryTests.java b/spring-boot/src/test/java/org/springframework/boot/context/embedded/AbstractEmbeddedServletContainerFactoryTests.java index ac997d3604..13cfc068cb 100644 --- a/spring-boot/src/test/java/org/springframework/boot/context/embedded/AbstractEmbeddedServletContainerFactoryTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/context/embedded/AbstractEmbeddedServletContainerFactoryTests.java @@ -80,20 +80,7 @@ import org.springframework.util.SocketUtils; import org.springframework.util.StreamUtils; import org.springframework.util.concurrent.ListenableFuture; -import static org.hamcrest.Matchers.containsString; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.greaterThan; -import static org.hamcrest.Matchers.hasEntry; -import static org.hamcrest.Matchers.hasItem; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.lessThan; -import static org.hamcrest.Matchers.not; -import static org.hamcrest.Matchers.notNullValue; -import static org.hamcrest.Matchers.nullValue; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Matchers.anyObject; import static org.mockito.Mockito.inOrder; import static org.mockito.Mockito.mock; @@ -135,7 +122,7 @@ public abstract class AbstractEmbeddedServletContainerFactoryTests { this.container = factory .getEmbeddedServletContainer(exampleServletRegistration()); this.container.start(); - assertThat(getResponse(getLocalUrl("/hello")), equalTo("Hello World")); + assertThat(getResponse(getLocalUrl("/hello"))).isEqualTo("Hello World"); } @Test @@ -145,7 +132,7 @@ public abstract class AbstractEmbeddedServletContainerFactoryTests { this.container = factory .getEmbeddedServletContainer(exampleServletRegistration()); this.container.start(); - assertThat(this.container.getPort(), lessThan(0)); // Jetty is -2 + assertThat(this.container.getPort()).isLessThan(0); // Jetty is -2 } @Test @@ -172,7 +159,7 @@ public abstract class AbstractEmbeddedServletContainerFactoryTests { ListenableFuture response1 = clientHttpRequestFactory .createAsyncRequest(new URI(getLocalUrl("/hello")), HttpMethod.GET) .executeAsync(); - assertThat(response1.get(10, TimeUnit.SECONDS).getRawStatusCode(), equalTo(200)); + assertThat(response1.get(10, TimeUnit.SECONDS).getRawStatusCode()).isEqualTo(200); this.container.stop(); this.container = factory @@ -182,7 +169,7 @@ public abstract class AbstractEmbeddedServletContainerFactoryTests { ListenableFuture response2 = clientHttpRequestFactory .createAsyncRequest(new URI(getLocalUrl("/hello")), HttpMethod.GET) .executeAsync(); - assertThat(response2.get(10, TimeUnit.SECONDS).getRawStatusCode(), equalTo(200)); + assertThat(response2.get(10, TimeUnit.SECONDS).getRawStatusCode()).isEqualTo(200); } @Test @@ -191,7 +178,7 @@ public abstract class AbstractEmbeddedServletContainerFactoryTests { this.container = factory.getEmbeddedServletContainer(exampleServletRegistration(), new FilterRegistrationBean(new ExampleFilter())); this.container.start(); - assertThat(getResponse(getLocalUrl("/hello")), equalTo("[Hello World]")); + assertThat(getResponse(getLocalUrl("/hello"))).isEqualTo("[Hello World]"); } @Test @@ -213,7 +200,7 @@ public abstract class AbstractEmbeddedServletContainerFactoryTests { } }); this.container.start(); - assertThat(date[0], notNullValue()); + assertThat(date[0]).isNotNull(); } @Test @@ -228,9 +215,9 @@ public abstract class AbstractEmbeddedServletContainerFactoryTests { servletContext.addServlet("test", servlet).setLoadOnStartup(1); } }); - assertThat(servlet.getInitCount(), equalTo(0)); + assertThat(servlet.getInitCount()).isEqualTo(0); this.container.start(); - assertThat(servlet.getInitCount(), equalTo(1)); + assertThat(servlet.getInitCount()).isEqualTo(1); } @Test @@ -241,9 +228,9 @@ public abstract class AbstractEmbeddedServletContainerFactoryTests { this.container = factory .getEmbeddedServletContainer(exampleServletRegistration()); this.container.start(); - assertThat(getResponse("http://localhost:" + specificPort + "/hello"), - equalTo("Hello World")); - assertEquals(specificPort, this.container.getPort()); + assertThat(getResponse("http://localhost:" + specificPort + "/hello")) + .isEqualTo("Hello World"); + assertThat(this.container.getPort()).isEqualTo(specificPort); } @Test @@ -253,7 +240,7 @@ public abstract class AbstractEmbeddedServletContainerFactoryTests { this.container = factory .getEmbeddedServletContainer(exampleServletRegistration()); this.container.start(); - assertThat(getResponse(getLocalUrl("/say/hello")), equalTo("Hello World")); + assertThat(getResponse(getLocalUrl("/say/hello"))).isEqualTo("Hello World"); } @Test @@ -312,7 +299,7 @@ public abstract class AbstractEmbeddedServletContainerFactoryTests { addTestTxtFile(factory); this.container = factory.getEmbeddedServletContainer(); this.container.start(); - assertThat(getResponse(getLocalUrl("/test.txt")), equalTo("test")); + assertThat(getResponse(getLocalUrl("/test.txt"))).isEqualTo("test"); } @Test @@ -327,8 +314,8 @@ public abstract class AbstractEmbeddedServletContainerFactoryTests { this.container = factory.getEmbeddedServletContainer(); this.container.start(); ClientHttpResponse response = getClientResponse(getLocalUrl("/test.xxcss")); - assertThat(response.getHeaders().getContentType().toString(), - equalTo("text/css")); + assertThat(response.getHeaders().getContentType().toString()) + .isEqualTo("text/css"); response.close(); } @@ -339,8 +326,8 @@ public abstract class AbstractEmbeddedServletContainerFactoryTests { this.container = factory.getEmbeddedServletContainer(exampleServletRegistration(), errorServletRegistration()); this.container.start(); - assertThat(getResponse(getLocalUrl("/hello")), equalTo("Hello World")); - assertThat(getResponse(getLocalUrl("/bang")), equalTo("Hello World")); + assertThat(getResponse(getLocalUrl("/hello"))).isEqualTo("Hello World"); + assertThat(getResponse(getLocalUrl("/bang"))).isEqualTo("Hello World"); } @Test @@ -387,8 +374,8 @@ public abstract class AbstractEmbeddedServletContainerFactoryTests { .build(); HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory( httpClient); - assertThat(getResponse(getLocalUrl("https", "/hello"), requestFactory), - containsString("scheme=https")); + assertThat(getResponse(getLocalUrl("https", "/hello"), requestFactory)) + .contains("scheme=https"); } protected final void testBasicSslWithKeyStore(String keyStore) throws Exception { @@ -404,8 +391,8 @@ public abstract class AbstractEmbeddedServletContainerFactoryTests { .build(); HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory( httpClient); - assertThat(getResponse(getLocalUrl("https", "/test.txt"), requestFactory), - equalTo("test")); + assertThat(getResponse(getLocalUrl("https", "/test.txt"), requestFactory)) + .isEqualTo("test"); } @Test @@ -427,8 +414,8 @@ public abstract class AbstractEmbeddedServletContainerFactoryTests { .build(); HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory( httpClient); - assertThat(getResponse(getLocalUrl("https", "/test.txt"), requestFactory), - equalTo("test")); + assertThat(getResponse(getLocalUrl("https", "/test.txt"), requestFactory)) + .isEqualTo("test"); } @Test @@ -451,8 +438,8 @@ public abstract class AbstractEmbeddedServletContainerFactoryTests { .build(); HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory( httpClient); - assertThat(getResponse(getLocalUrl("https", "/test.txt"), requestFactory), - equalTo("test")); + assertThat(getResponse(getLocalUrl("https", "/test.txt"), requestFactory)) + .isEqualTo("test"); } @Test(expected = IOException.class) @@ -492,8 +479,8 @@ public abstract class AbstractEmbeddedServletContainerFactoryTests { .build(); HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory( httpClient); - assertThat(getResponse(getLocalUrl("https", "/test.txt"), requestFactory), - equalTo("test")); + assertThat(getResponse(getLocalUrl("https", "/test.txt"), requestFactory)) + .isEqualTo("test"); } @Test @@ -511,8 +498,8 @@ public abstract class AbstractEmbeddedServletContainerFactoryTests { .build(); HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory( httpClient); - assertThat(getResponse(getLocalUrl("https", "/test.txt"), requestFactory), - equalTo("test")); + assertThat(getResponse(getLocalUrl("https", "/test.txt"), requestFactory)) + .isEqualTo("test"); } @Test @@ -520,7 +507,7 @@ public abstract class AbstractEmbeddedServletContainerFactoryTests { AbstractEmbeddedServletContainerFactory factory = getFactory(); factory.getJspServlet().setRegistered(false); this.container = factory.getEmbeddedServletContainer(); - assertThat(getJspServlet(), is(nullValue())); + assertThat(getJspServlet()).isNull(); } @Test @@ -531,7 +518,7 @@ public abstract class AbstractEmbeddedServletContainerFactoryTests { this.container.start(); ClientHttpResponse response = getClientResponse( getLocalUrl("/org/springframework/boot/SpringApplication.class")); - assertThat(response.getStatusCode(), equalTo(HttpStatus.NOT_FOUND)); + assertThat(response.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND); } private Ssl getSsl(ClientAuth clientAuth, String keyPassword, String keyStore) { @@ -564,7 +551,7 @@ public abstract class AbstractEmbeddedServletContainerFactoryTests { @Test public void defaultSessionTimeout() throws Exception { - assertThat(getFactory().getSessionTimeout(), equalTo(30 * 60)); + assertThat(getFactory().getSessionTimeout()).isEqualTo(30 * 60); } @Test @@ -585,8 +572,8 @@ public abstract class AbstractEmbeddedServletContainerFactoryTests { System.out.println(s2); System.out.println(s3); String message = "Session error s1=" + s1 + " s2=" + s2 + " s3=" + s3; - assertThat(message, s2.split(":")[0], equalTo(s1.split(":")[1])); - assertThat(message, s3.split(":")[0], equalTo(s2.split(":")[1])); + assertThat(s2.split(":")[0]).as(message).isEqualTo(s1.split(":")[1]); + assertThat(s3.split(":")[0]).as(message).isEqualTo(s2.split(":")[1]); } @Test @@ -608,15 +595,15 @@ public abstract class AbstractEmbeddedServletContainerFactoryTests { } }); - assertThat(dirContents.length, greaterThan(0)); + assertThat(dirContents.length).isGreaterThan(0); } @Test public void getValidSessionStoreWhenSessionStoreNotSet() throws Exception { AbstractEmbeddedServletContainerFactory factory = getFactory(); File dir = factory.getValidSessionStoreDir(false); - assertThat(dir.getName(), equalTo("servlet-sessions")); - assertThat(dir.getParentFile(), equalTo(new ApplicationTemp().getDir())); + assertThat(dir.getName()).isEqualTo("servlet-sessions"); + assertThat(dir.getParentFile()).isEqualTo(new ApplicationTemp().getDir()); } @Test @@ -624,8 +611,8 @@ public abstract class AbstractEmbeddedServletContainerFactoryTests { AbstractEmbeddedServletContainerFactory factory = getFactory(); factory.setSessionStoreDir(new File("sessions")); File dir = factory.getValidSessionStoreDir(false); - assertThat(dir.getName(), equalTo("sessions")); - assertThat(dir.getParentFile(), equalTo(new ApplicationHome().getDir())); + assertThat(dir.getName()).isEqualTo("sessions"); + assertThat(dir.getParentFile()).isEqualTo(new ApplicationHome().getDir()); } @Test @@ -639,23 +626,24 @@ public abstract class AbstractEmbeddedServletContainerFactoryTests { @Test public void compression() throws Exception { - assertTrue(doTestCompression(10000, null, null)); + assertThat(doTestCompression(10000, null, null)).isTrue(); } @Test public void noCompressionForSmallResponse() throws Exception { - assertFalse(doTestCompression(100, null, null)); + assertThat(doTestCompression(100, null, null)).isFalse(); } @Test public void noCompressionForMimeType() throws Exception { String[] mimeTypes = new String[] { "text/html", "text/xml", "text/css" }; - assertFalse(doTestCompression(10000, mimeTypes, null)); + assertThat(doTestCompression(10000, mimeTypes, null)).isFalse(); } @Test public void noCompressionForUserAgent() throws Exception { - assertFalse(doTestCompression(10000, null, new String[] { "testUserAgent" })); + assertThat(doTestCompression(10000, null, new String[] { "testUserAgent" })) + .isFalse(); } @Test @@ -673,7 +661,7 @@ public abstract class AbstractEmbeddedServletContainerFactoryTests { getResponse(getLocalUrl("/hello"), new HttpComponentsClientHttpRequestFactory(HttpClientBuilder.create() .setContentDecoderRegistry(contentDecoderMap).build())); - assertThat(inputStreamFactory.wasCompressionUsed(), equalTo(true)); + assertThat(inputStreamFactory.wasCompressionUsed()).isTrue(); } @Test @@ -684,15 +672,14 @@ public abstract class AbstractEmbeddedServletContainerFactoryTests { Set> entrySet = configuredMimeMappings.entrySet(); Collection expectedMimeMappings = getExpectedMimeMappings(); for (Entry entry : entrySet) { - assertThat(expectedMimeMappings, - hasItem(new MimeMappings.Mapping(entry.getKey(), entry.getValue()))); + assertThat(expectedMimeMappings) + .contains(new MimeMappings.Mapping(entry.getKey(), entry.getValue())); } for (MimeMappings.Mapping mapping : expectedMimeMappings) { - assertThat(configuredMimeMappings, - hasEntry(mapping.getExtension(), mapping.getMimeType())); + assertThat(configuredMimeMappings).containsEntry(mapping.getExtension(), + mapping.getMimeType()); } - assertThat(configuredMimeMappings.size(), - is(equalTo(expectedMimeMappings.size()))); + assertThat(configuredMimeMappings.size()).isEqualTo(expectedMimeMappings.size()); } @Test @@ -713,7 +700,7 @@ public abstract class AbstractEmbeddedServletContainerFactoryTests { } }); this.container.start(); - assertThat(rootResource.get(), is(not(nullValue()))); + assertThat(rootResource.get()).isNotNull(); } @Test @@ -724,7 +711,7 @@ public abstract class AbstractEmbeddedServletContainerFactoryTests { .getEmbeddedServletContainer(exampleServletRegistration()); this.container.start(); ClientHttpResponse response = getClientResponse(getLocalUrl("/hello")); - assertThat(response.getHeaders().getFirst("server"), equalTo("MyServer")); + assertThat(response.getHeaders().getFirst("server")).isEqualTo("MyServer"); } private boolean doTestCompression(int contentSize, String[] mimeTypes, @@ -738,7 +725,7 @@ public abstract class AbstractEmbeddedServletContainerFactoryTests { new HttpComponentsClientHttpRequestFactory( HttpClientBuilder.create().setUserAgent("testUserAgent") .setContentDecoderRegistry(contentDecoderMap).build())); - assertThat(response, equalTo(testContent)); + assertThat(response).isEqualTo(testContent); return inputStreamFactory.wasCompressionUsed(); } @@ -844,8 +831,8 @@ public abstract class AbstractEmbeddedServletContainerFactoryTests { this.container = factory.getEmbeddedServletContainer( new ServletRegistrationBean(new ExampleServlet(true, false), "/hello")); this.container.start(); - assertThat(getResponse(getLocalUrl("/hello"), "X-Forwarded-For:140.211.11.130"), - containsString("remoteaddr=140.211.11.130")); + assertThat(getResponse(getLocalUrl("/hello"), "X-Forwarded-For:140.211.11.130")) + .contains("remoteaddr=140.211.11.130"); } protected abstract AbstractEmbeddedServletContainerFactory getFactory(); diff --git a/spring-boot/src/test/java/org/springframework/boot/context/embedded/AnnotationConfigEmbeddedWebApplicationContextTests.java b/spring-boot/src/test/java/org/springframework/boot/context/embedded/AnnotationConfigEmbeddedWebApplicationContextTests.java index 3a2fdadd2b..fcae446d55 100644 --- a/spring-boot/src/test/java/org/springframework/boot/context/embedded/AnnotationConfigEmbeddedWebApplicationContextTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/context/embedded/AnnotationConfigEmbeddedWebApplicationContextTests.java @@ -37,8 +37,7 @@ import org.springframework.stereotype.Component; import org.springframework.web.context.ServletContextAware; import org.springframework.web.servlet.config.annotation.EnableWebMvc; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.verify; /** @@ -71,7 +70,7 @@ public class AnnotationConfigEmbeddedWebApplicationContextTests { ExampleEmbeddedWebApplicationConfiguration.class, ExampleServletWithAutowired.class, SessionScopedComponent.class); Servlet servlet = this.context.getBean(ExampleServletWithAutowired.class); - assertNotNull(servlet); + assertThat(servlet).isNotNull(); } @Test @@ -105,8 +104,8 @@ public class AnnotationConfigEmbeddedWebApplicationContextTests { verifyContext(); // You can't initialize the application context and inject the servlet context // because of a cycle - we'd like this to be not null but it never will be - assertNull(this.context.getBean(ServletContextAwareEmbeddedConfiguration.class) - .getServletContext()); + assertThat(this.context.getBean(ServletContextAwareEmbeddedConfiguration.class) + .getServletContext()).isNull(); } @Test @@ -119,8 +118,8 @@ public class AnnotationConfigEmbeddedWebApplicationContextTests { this.context.setParent(parent); this.context.refresh(); verifyContext(); - assertNotNull(this.context.getBean(ServletContextAwareConfiguration.class) - .getServletContext()); + assertThat(this.context.getBean(ServletContextAwareConfiguration.class) + .getServletContext()).isNotNull(); } private void verifyContext() { @@ -140,7 +139,7 @@ public class AnnotationConfigEmbeddedWebApplicationContextTests { @Override public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException { - assertNotNull(this.component); + assertThat(this.component).isNotNull(); } } diff --git a/spring-boot/src/test/java/org/springframework/boot/context/embedded/DelegatingFilterProxyRegistrationBeanTests.java b/spring-boot/src/test/java/org/springframework/boot/context/embedded/DelegatingFilterProxyRegistrationBeanTests.java index 54989c4d01..8e0ac12934 100644 --- a/spring-boot/src/test/java/org/springframework/boot/context/embedded/DelegatingFilterProxyRegistrationBeanTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/context/embedded/DelegatingFilterProxyRegistrationBeanTests.java @@ -26,9 +26,7 @@ import org.springframework.web.context.WebApplicationContext; import org.springframework.web.context.support.GenericWebApplicationContext; import org.springframework.web.filter.DelegatingFilterProxy; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.instanceOf; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Matchers.isA; /** @@ -59,18 +57,18 @@ public class DelegatingFilterProxyRegistrationBeanTests @Test public void nameDefaultsToTargetBeanName() throws Exception { assertThat(new DelegatingFilterProxyRegistrationBean("myFilter") - .getOrDeduceName(null), equalTo("myFilter")); + .getOrDeduceName(null)).isEqualTo("myFilter"); } @Test public void getFilterUsesDelegatingFilterProxy() throws Exception { AbstractFilterRegistrationBean registrationBean = createFilterRegistrationBean(); Filter filter = registrationBean.getFilter(); - assertThat(filter, instanceOf(DelegatingFilterProxy.class)); - assertThat(ReflectionTestUtils.getField(filter, "webApplicationContext"), - equalTo((Object) this.applicationContext)); - assertThat(ReflectionTestUtils.getField(filter, "targetBeanName"), - equalTo((Object) "mockFilter")); + assertThat(filter).isInstanceOf(DelegatingFilterProxy.class); + assertThat(ReflectionTestUtils.getField(filter, "webApplicationContext")) + .isEqualTo(this.applicationContext); + assertThat(ReflectionTestUtils.getField(filter, "targetBeanName")) + .isEqualTo("mockFilter"); } @Test diff --git a/spring-boot/src/test/java/org/springframework/boot/context/embedded/EmbeddedServletContainerMvcIntegrationTests.java b/spring-boot/src/test/java/org/springframework/boot/context/embedded/EmbeddedServletContainerMvcIntegrationTests.java index ff6e3b62df..76a95804f5 100644 --- a/spring-boot/src/test/java/org/springframework/boot/context/embedded/EmbeddedServletContainerMvcIntegrationTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/context/embedded/EmbeddedServletContainerMvcIntegrationTests.java @@ -42,8 +42,7 @@ import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.servlet.DispatcherServlet; import org.springframework.web.servlet.config.annotation.EnableWebMvc; -import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; /** * Integration tests for {@link EmbeddedWebApplicationContext} and @@ -105,7 +104,7 @@ public class EmbeddedServletContainerMvcIntegrationTests { try { String actual = StreamUtils.copyToString(response.getBody(), Charset.forName("UTF-8")); - assertThat(actual, equalTo("Hello World")); + assertThat(actual).isEqualTo("Hello World"); } finally { response.close(); diff --git a/spring-boot/src/test/java/org/springframework/boot/context/embedded/EmbeddedWebApplicationContextTests.java b/spring-boot/src/test/java/org/springframework/boot/context/embedded/EmbeddedWebApplicationContextTests.java index 51b8f31053..29560ee648 100644 --- a/spring-boot/src/test/java/org/springframework/boot/context/embedded/EmbeddedWebApplicationContextTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/context/embedded/EmbeddedWebApplicationContextTests.java @@ -63,14 +63,7 @@ import org.springframework.web.context.WebApplicationContext; import org.springframework.web.context.request.SessionScope; import org.springframework.web.filter.GenericFilterBean; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.instanceOf; -import static org.hamcrest.Matchers.nullValue; -import static org.hamcrest.Matchers.sameInstance; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.BDDMockito.given; import static org.mockito.Matchers.anyObject; import static org.mockito.Matchers.anyString; @@ -115,20 +108,19 @@ public class EmbeddedWebApplicationContextTests { MockEmbeddedServletContainerFactory escf = getEmbeddedServletContainerFactory(); // Ensure that the context has been setup - assertThat(this.context.getServletContext(), equalTo(escf.getServletContext())); + assertThat(this.context.getServletContext()).isEqualTo(escf.getServletContext()); verify(escf.getServletContext()).setAttribute( WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, this.context); // Ensure WebApplicationContextUtils.registerWebApplicationScopes was called - assertThat( - this.context.getBeanFactory() - .getRegisteredScope(WebApplicationContext.SCOPE_SESSION), - instanceOf(SessionScope.class)); + assertThat(this.context.getBeanFactory() + .getRegisteredScope(WebApplicationContext.SCOPE_SESSION)) + .isInstanceOf(SessionScope.class); // Ensure WebApplicationContextUtils.registerEnvironmentBeans was called - assertThat(this.context.containsBean( - WebApplicationContext.SERVLET_CONTEXT_BEAN_NAME), equalTo(true)); + assertThat(this.context + .containsBean(WebApplicationContext.SERVLET_CONTEXT_BEAN_NAME)).isTrue(); } @Test @@ -142,7 +134,7 @@ public class EmbeddedWebApplicationContextTests { .getDeclaredField("shutdownHook"); shutdownHookField.setAccessible(true); Object shutdownHook = shutdownHookField.get(this.context); - assertThat(shutdownHook, nullValue()); + assertThat(shutdownHook).isNull(); } @Test @@ -153,9 +145,9 @@ public class EmbeddedWebApplicationContextTests { this.context.refresh(); EmbeddedServletContainerInitializedEvent event = this.context .getBean(MockListener.class).getEvent(); - assertNotNull(event); - assertTrue(event.getSource().getPort() >= 0); - assertEquals(this.context, event.getApplicationContext()); + assertThat(event).isNotNull(); + assertThat(event.getSource().getPort() >= 0).isTrue(); + assertThat(event.getApplicationContext()).isEqualTo(this.context); } @Test @@ -164,8 +156,8 @@ public class EmbeddedWebApplicationContextTests { new ServerPortInfoApplicationContextInitializer().initialize(this.context); this.context.refresh(); ConfigurableEnvironment environment = this.context.getEnvironment(); - assertTrue(environment.containsProperty("local.server.port")); - assertEquals("8080", environment.getProperty("local.server.port")); + assertThat(environment.containsProperty("local.server.port")).isTrue(); + assertThat(environment.getProperty("local.server.port")).isEqualTo("8080"); } @Test @@ -240,7 +232,7 @@ public class EmbeddedWebApplicationContextTests { MockEmbeddedServletContainerFactory escf = getEmbeddedServletContainerFactory(); verify(escf.getServletContext()).addFilter("filterBean", filter); verify(escf.getServletContext()).addFilter("object", registration.getFilter()); - assertEquals(filter, escf.getRegisteredFilter(0).getFilter()); + assertThat(escf.getRegisteredFilter(0).getFilter()).isEqualTo(filter); } @Test @@ -460,8 +452,8 @@ public class EmbeddedWebApplicationContextTests { beanDefinition(propertySupport)); this.context.refresh(); - assertThat(getEmbeddedServletContainerFactory().getContainer().getPort(), - equalTo(8080)); + assertThat(getEmbeddedServletContainerFactory().getContainer().getPort()) + .isEqualTo(8080); } @Test @@ -473,12 +465,12 @@ public class EmbeddedWebApplicationContextTests { factory.registerScope(WebApplicationContext.SCOPE_GLOBAL_SESSION, scope); addEmbeddedServletContainerFactoryBean(); this.context.refresh(); - assertThat(factory.getRegisteredScope(WebApplicationContext.SCOPE_REQUEST), - sameInstance(scope)); - assertThat(factory.getRegisteredScope(WebApplicationContext.SCOPE_SESSION), - sameInstance(scope)); - assertThat(factory.getRegisteredScope(WebApplicationContext.SCOPE_GLOBAL_SESSION), - sameInstance(scope)); + assertThat(factory.getRegisteredScope(WebApplicationContext.SCOPE_REQUEST)) + .isSameAs(scope); + assertThat(factory.getRegisteredScope(WebApplicationContext.SCOPE_SESSION)) + .isSameAs(scope); + assertThat(factory.getRegisteredScope(WebApplicationContext.SCOPE_GLOBAL_SESSION)) + .isSameAs(scope); } private void addEmbeddedServletContainerFactoryBean() { diff --git a/spring-boot/src/test/java/org/springframework/boot/context/embedded/MimeMappingsTests.java b/spring-boot/src/test/java/org/springframework/boot/context/embedded/MimeMappingsTests.java index 129fcef59f..9ebe352040 100644 --- a/spring-boot/src/test/java/org/springframework/boot/context/embedded/MimeMappingsTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/context/embedded/MimeMappingsTests.java @@ -25,9 +25,7 @@ import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.nullValue; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link MimeMappings}. @@ -50,8 +48,8 @@ public class MimeMappingsTests { mappings.add("foo", "bar"); MimeMappings clone = new MimeMappings(mappings); mappings.add("baz", "bar"); - assertThat(clone.get("foo"), equalTo("bar")); - assertThat(clone.get("baz"), nullValue()); + assertThat(clone.get("foo")).isEqualTo("bar"); + assertThat(clone.get("baz")).isNull(); } @Test @@ -60,8 +58,8 @@ public class MimeMappingsTests { mappings.put("foo", "bar"); MimeMappings clone = new MimeMappings(mappings); mappings.put("baz", "bar"); - assertThat(clone.get("foo"), equalTo("bar")); - assertThat(clone.get("baz"), nullValue()); + assertThat(clone.get("foo")).isEqualTo("bar"); + assertThat(clone.get("baz")).isNull(); } @Test @@ -73,10 +71,10 @@ public class MimeMappingsTests { for (MimeMappings.Mapping mapping : mappings) { mappingList.add(mapping); } - assertThat(mappingList.get(0).getExtension(), equalTo("foo")); - assertThat(mappingList.get(0).getMimeType(), equalTo("bar")); - assertThat(mappingList.get(1).getExtension(), equalTo("baz")); - assertThat(mappingList.get(1).getMimeType(), equalTo("boo")); + assertThat(mappingList.get(0).getExtension()).isEqualTo("foo"); + assertThat(mappingList.get(0).getMimeType()).isEqualTo("bar"); + assertThat(mappingList.get(1).getExtension()).isEqualTo("baz"); + assertThat(mappingList.get(1).getMimeType()).isEqualTo("boo"); } @Test @@ -86,44 +84,44 @@ public class MimeMappingsTests { mappings.add("baz", "boo"); List mappingList = new ArrayList(); mappingList.addAll(mappings.getAll()); - assertThat(mappingList.get(0).getExtension(), equalTo("foo")); - assertThat(mappingList.get(0).getMimeType(), equalTo("bar")); - assertThat(mappingList.get(1).getExtension(), equalTo("baz")); - assertThat(mappingList.get(1).getMimeType(), equalTo("boo")); + assertThat(mappingList.get(0).getExtension()).isEqualTo("foo"); + assertThat(mappingList.get(0).getMimeType()).isEqualTo("bar"); + assertThat(mappingList.get(1).getExtension()).isEqualTo("baz"); + assertThat(mappingList.get(1).getMimeType()).isEqualTo("boo"); } @Test public void addNew() throws Exception { MimeMappings mappings = new MimeMappings(); - assertThat(mappings.add("foo", "bar"), nullValue()); + assertThat(mappings.add("foo", "bar")).isNull(); } @Test public void addReplacesExisting() throws Exception { MimeMappings mappings = new MimeMappings(); mappings.add("foo", "bar"); - assertThat(mappings.add("foo", "baz"), equalTo("bar")); + assertThat(mappings.add("foo", "baz")).isEqualTo("bar"); } @Test public void remove() throws Exception { MimeMappings mappings = new MimeMappings(); mappings.add("foo", "bar"); - assertThat(mappings.remove("foo"), equalTo("bar")); - assertThat(mappings.remove("foo"), nullValue()); + assertThat(mappings.remove("foo")).isEqualTo("bar"); + assertThat(mappings.remove("foo")).isNull(); } @Test public void get() throws Exception { MimeMappings mappings = new MimeMappings(); mappings.add("foo", "bar"); - assertThat(mappings.get("foo"), equalTo("bar")); + assertThat(mappings.get("foo")).isEqualTo("bar"); } @Test public void getMissing() throws Exception { MimeMappings mappings = new MimeMappings(); - assertThat(mappings.get("foo"), nullValue()); + assertThat(mappings.get("foo")).isNull(); } @Test @@ -138,7 +136,7 @@ public class MimeMappingsTests { // Expected } mappings.remove("foo"); - assertThat(unmodifiable.get("foo"), nullValue()); + assertThat(unmodifiable.get("foo")).isNull(); } } diff --git a/spring-boot/src/test/java/org/springframework/boot/context/embedded/MultipartConfigFactoryTests.java b/spring-boot/src/test/java/org/springframework/boot/context/embedded/MultipartConfigFactoryTests.java index 76daef15e0..03f9c87cee 100644 --- a/spring-boot/src/test/java/org/springframework/boot/context/embedded/MultipartConfigFactoryTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/context/embedded/MultipartConfigFactoryTests.java @@ -20,8 +20,7 @@ import javax.servlet.MultipartConfigElement; import org.junit.Test; -import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link MultipartConfigFactory}. @@ -34,10 +33,10 @@ public class MultipartConfigFactoryTests { public void sensibleDefaults() { MultipartConfigFactory factory = new MultipartConfigFactory(); MultipartConfigElement config = factory.createMultipartConfig(); - assertThat(config.getLocation(), equalTo("")); - assertThat(config.getMaxFileSize(), equalTo(-1L)); - assertThat(config.getMaxRequestSize(), equalTo(-1L)); - assertThat(config.getFileSizeThreshold(), equalTo(0)); + assertThat(config.getLocation()).isEqualTo(""); + assertThat(config.getMaxFileSize()).isEqualTo(-1L); + assertThat(config.getMaxRequestSize()).isEqualTo(-1L); + assertThat(config.getFileSizeThreshold()).isEqualTo(0); } @Test @@ -48,10 +47,10 @@ public class MultipartConfigFactoryTests { factory.setMaxRequestSize(2); factory.setFileSizeThreshold(3); MultipartConfigElement config = factory.createMultipartConfig(); - assertThat(config.getLocation(), equalTo("loc")); - assertThat(config.getMaxFileSize(), equalTo(1L)); - assertThat(config.getMaxRequestSize(), equalTo(2L)); - assertThat(config.getFileSizeThreshold(), equalTo(3)); + assertThat(config.getLocation()).isEqualTo("loc"); + assertThat(config.getMaxFileSize()).isEqualTo(1L); + assertThat(config.getMaxRequestSize()).isEqualTo(2L); + assertThat(config.getFileSizeThreshold()).isEqualTo(3); } @Test @@ -61,9 +60,9 @@ public class MultipartConfigFactoryTests { factory.setMaxRequestSize("2kB"); factory.setFileSizeThreshold("3Mb"); MultipartConfigElement config = factory.createMultipartConfig(); - assertThat(config.getMaxFileSize(), equalTo(1L)); - assertThat(config.getMaxRequestSize(), equalTo(2 * 1024L)); - assertThat(config.getFileSizeThreshold(), equalTo(3 * 1024 * 1024)); + assertThat(config.getMaxFileSize()).isEqualTo(1L); + assertThat(config.getMaxRequestSize()).isEqualTo(2 * 1024L); + assertThat(config.getFileSizeThreshold()).isEqualTo(3 * 1024 * 1024); } } diff --git a/spring-boot/src/test/java/org/springframework/boot/context/embedded/config/AnsiOutputApplicationListenerTests.java b/spring-boot/src/test/java/org/springframework/boot/context/embedded/config/AnsiOutputApplicationListenerTests.java index a9b195a2e9..31a92890af 100644 --- a/spring-boot/src/test/java/org/springframework/boot/context/embedded/config/AnsiOutputApplicationListenerTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/context/embedded/config/AnsiOutputApplicationListenerTests.java @@ -34,8 +34,7 @@ import org.springframework.context.annotation.Configuration; import org.springframework.core.env.ConfigurableEnvironment; import org.springframework.core.env.StandardEnvironment; -import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link AnsiOutputApplicationListener}. @@ -67,7 +66,7 @@ public class AnsiOutputApplicationListenerTests { props.put("spring.output.ansi.enabled", "ALWAYS"); application.setDefaultProperties(props); this.context = application.run(); - assertThat(AnsiOutputEnabledValue.get(), equalTo(Enabled.ALWAYS)); + assertThat(AnsiOutputEnabledValue.get()).isEqualTo(Enabled.ALWAYS); } @Test @@ -78,7 +77,7 @@ public class AnsiOutputApplicationListenerTests { props.put("spring.output.ansi.enabled", "never"); application.setDefaultProperties(props); this.context = application.run(); - assertThat(AnsiOutputEnabledValue.get(), equalTo(Enabled.NEVER)); + assertThat(AnsiOutputEnabledValue.get()).isEqualTo(Enabled.NEVER); } @Test @@ -89,7 +88,7 @@ public class AnsiOutputApplicationListenerTests { application.setWebEnvironment(false); application.setEnvironment(environment); this.context = application.run(); - assertThat(AnsiOutputEnabledValue.get(), equalTo(Enabled.NEVER)); + assertThat(AnsiOutputEnabledValue.get()).isEqualTo(Enabled.NEVER); } @Configuration diff --git a/spring-boot/src/test/java/org/springframework/boot/context/embedded/jetty/JettyEmbeddedServletContainerFactoryTests.java b/spring-boot/src/test/java/org/springframework/boot/context/embedded/jetty/JettyEmbeddedServletContainerFactoryTests.java index f80fb62f7e..a2daa9433f 100644 --- a/spring-boot/src/test/java/org/springframework/boot/context/embedded/jetty/JettyEmbeddedServletContainerFactoryTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/context/embedded/jetty/JettyEmbeddedServletContainerFactoryTests.java @@ -46,9 +46,7 @@ import org.springframework.boot.context.embedded.ServletRegistrationBean; import org.springframework.boot.context.embedded.Ssl; import org.springframework.http.HttpHeaders; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.is; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Matchers.anyObject; import static org.mockito.Mockito.inOrder; import static org.mockito.Mockito.mock; @@ -134,8 +132,8 @@ public class JettyEmbeddedServletContainerFactoryTests .getConnectors()[0]; SslConnectionFactory connectionFactory = connector .getConnectionFactory(SslConnectionFactory.class); - assertThat(connectionFactory.getSslContextFactory().getIncludeCipherSuites(), - equalTo(new String[] { "ALPHA", "BRAVO", "CHARLIE" })); + assertThat(connectionFactory.getSslContextFactory().getIncludeCipherSuites()) + .containsExactly("ALPHA", "BRAVO", "CHARLIE"); } private void assertTimeout(JettyEmbeddedServletContainerFactory factory, @@ -147,7 +145,7 @@ public class JettyEmbeddedServletContainerFactoryTests WebAppContext webAppContext = (WebAppContext) handlers[0]; int actual = webAppContext.getSessionHandler().getSessionManager() .getMaxInactiveInterval(); - assertThat(actual, equalTo(expected)); + assertThat(actual).isEqualTo(expected); } @Test @@ -167,7 +165,7 @@ public class JettyEmbeddedServletContainerFactoryTests this.container = factory .getEmbeddedServletContainer(exampleServletRegistration()); this.container.start(); - assertThat(getResponse(getLocalUrl("/hello")), equalTo("Hello World")); + assertThat(getResponse(getLocalUrl("/hello"))).isEqualTo("Hello World"); } @Test @@ -182,7 +180,7 @@ public class JettyEmbeddedServletContainerFactoryTests initParameters.put("a", "alpha"); factory.getJspServlet().setInitParameters(initParameters); this.container = factory.getEmbeddedServletContainer(); - assertThat(getJspServlet().getInitParameters(), is(equalTo(initParameters))); + assertThat(getJspServlet().getInitParameters()).isEqualTo(initParameters); } @Test diff --git a/spring-boot/src/test/java/org/springframework/boot/context/embedded/tomcat/TomcatEmbeddedServletContainerFactoryTests.java b/spring-boot/src/test/java/org/springframework/boot/context/embedded/tomcat/TomcatEmbeddedServletContainerFactoryTests.java index e593db937e..cad1a1be23 100644 --- a/spring-boot/src/test/java/org/springframework/boot/context/embedded/tomcat/TomcatEmbeddedServletContainerFactoryTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/context/embedded/tomcat/TomcatEmbeddedServletContainerFactoryTests.java @@ -47,12 +47,7 @@ import org.springframework.boot.context.embedded.Ssl; import org.springframework.test.util.ReflectionTestUtils; import org.springframework.util.SocketUtils; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.not; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.fail; import static org.mockito.BDDMockito.given; import static org.mockito.Matchers.any; @@ -90,8 +85,8 @@ public class TomcatEmbeddedServletContainerFactoryTests String firstContainerName = ((TomcatEmbeddedServletContainer) this.container) .getTomcat().getEngine().getName(); String secondContainerName = container2.getTomcat().getEngine().getName(); - assertFalse("Tomcat engines must have different names", - firstContainerName.equals(secondContainerName)); + assertThat(firstContainerName).as("Tomcat engines must have different names") + .isNotEqualTo(secondContainerName); container2.stop(); } @@ -156,8 +151,8 @@ public class TomcatEmbeddedServletContainerFactoryTests this.container = factory.getEmbeddedServletContainer(); Map connectors = ((TomcatEmbeddedServletContainer) this.container) .getServiceConnectors(); - assertThat(connectors.values().iterator().next().length, - equalTo(listeners.length + 1)); + assertThat(connectors.values().iterator().next().length) + .isEqualTo(listeners.length + 1); } @Test @@ -235,14 +230,14 @@ public class TomcatEmbeddedServletContainerFactoryTests TomcatEmbeddedServletContainerFactory factory = getFactory(); factory.setUriEncoding(Charset.forName("US-ASCII")); Tomcat tomcat = getTomcat(factory); - assertEquals("US-ASCII", tomcat.getConnector().getURIEncoding()); + assertThat(tomcat.getConnector().getURIEncoding()).isEqualTo("US-ASCII"); } @Test public void defaultUriEncoding() throws Exception { TomcatEmbeddedServletContainerFactory factory = getFactory(); Tomcat tomcat = getTomcat(factory); - assertEquals("UTF-8", tomcat.getConnector().getURIEncoding()); + assertThat(tomcat.getConnector().getURIEncoding()).isEqualTo("UTF-8"); } @Test @@ -260,7 +255,7 @@ public class TomcatEmbeddedServletContainerFactoryTests AbstractHttp11JsseProtocol jsseProtocol = (AbstractHttp11JsseProtocol) connector .getProtocolHandler(); - assertThat(jsseProtocol.getCiphers(), equalTo("ALPHA,BRAVO,CHARLIE")); + assertThat(jsseProtocol.getCiphers()).isEqualTo("ALPHA,BRAVO,CHARLIE"); } @Test @@ -328,7 +323,7 @@ public class TomcatEmbeddedServletContainerFactoryTests factory.getJspServlet().setInitParameters(initParameters); this.container = factory.getEmbeddedServletContainer(); Wrapper jspServlet = getJspServlet(); - assertThat(jspServlet.findInitParameter("a"), is(equalTo("alpha"))); + assertThat(jspServlet.findInitParameter("a")).isEqualTo("alpha"); } @Test @@ -359,8 +354,8 @@ public class TomcatEmbeddedServletContainerFactoryTests System.out.println(s2); System.out.println(s3); String message = "Session error s1=" + s1 + " s2=" + s2 + " s3=" + s3; - assertThat(message, s2.split(":")[0], equalTo(s1.split(":")[1])); - assertThat(message, s3.split(":")[0], not(equalTo(s2.split(":")[1]))); + assertThat(s2.split(":")[0]).as(message).isEqualTo(s1.split(":")[1]); + assertThat(s3.split(":")[0]).as(message).isNotEqualTo(s2.split(":")[1]); } @Override @@ -383,7 +378,7 @@ public class TomcatEmbeddedServletContainerFactoryTests int expected) { Tomcat tomcat = getTomcat(factory); Context context = (Context) tomcat.getHost().findChildren()[0]; - assertThat(context.getSessionTimeout(), equalTo(expected)); + assertThat(context.getSessionTimeout()).isEqualTo(expected); } private Tomcat getTomcat(TomcatEmbeddedServletContainerFactory factory) { diff --git a/spring-boot/src/test/java/org/springframework/boot/context/embedded/undertow/FileSessionPersistenceTests.java b/spring-boot/src/test/java/org/springframework/boot/context/embedded/undertow/FileSessionPersistenceTests.java index a8b4a3cc15..06ade9a844 100644 --- a/spring-boot/src/test/java/org/springframework/boot/context/embedded/undertow/FileSessionPersistenceTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/context/embedded/undertow/FileSessionPersistenceTests.java @@ -28,10 +28,7 @@ import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.notNullValue; -import static org.hamcrest.Matchers.nullValue; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link FileSessionPersistence}. @@ -61,7 +58,7 @@ public class FileSessionPersistenceTests { public void loadsNullForMissingFile() throws Exception { Map attributes = this.persistence .loadSessionAttributes("test", this.classLoader); - assertThat(attributes, nullValue()); + assertThat(attributes).isNull(); } @Test @@ -74,10 +71,9 @@ public class FileSessionPersistenceTests { this.persistence.persistSessions("test", sessionData); Map restored = this.persistence .loadSessionAttributes("test", this.classLoader); - assertThat(restored, notNullValue()); - assertThat(restored.get("abc").getExpiration(), equalTo(this.expiration)); - assertThat(restored.get("abc").getSessionData().get("spring"), - equalTo((Object) "boot")); + assertThat(restored).isNotNull(); + assertThat(restored.get("abc").getExpiration()).isEqualTo(this.expiration); + assertThat(restored.get("abc").getSessionData().get("spring")).isEqualTo("boot"); } @Test @@ -91,8 +87,8 @@ public class FileSessionPersistenceTests { this.persistence.persistSessions("test", sessionData); Map restored = this.persistence .loadSessionAttributes("test", this.classLoader); - assertThat(restored, notNullValue()); - assertThat(restored.containsKey("abc"), equalTo(false)); + assertThat(restored).isNotNull(); + assertThat(restored.containsKey("abc")).isFalse(); } @Test @@ -100,9 +96,9 @@ public class FileSessionPersistenceTests { File sessionFile = new File(this.dir, "test.session"); Map sessionData = new LinkedHashMap(); this.persistence.persistSessions("test", sessionData); - assertThat(sessionFile.exists(), equalTo(true)); + assertThat(sessionFile.exists()).isTrue(); this.persistence.clear("test"); - assertThat(sessionFile.exists(), equalTo(false)); + assertThat(sessionFile.exists()).isFalse(); } } diff --git a/spring-boot/src/test/java/org/springframework/boot/context/embedded/undertow/UndertowEmbeddedServletContainerFactoryTests.java b/spring-boot/src/test/java/org/springframework/boot/context/embedded/undertow/UndertowEmbeddedServletContainerFactoryTests.java index 477592259d..a8ffc224b3 100644 --- a/spring-boot/src/test/java/org/springframework/boot/context/embedded/undertow/UndertowEmbeddedServletContainerFactoryTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/context/embedded/undertow/UndertowEmbeddedServletContainerFactoryTests.java @@ -42,13 +42,7 @@ import org.springframework.boot.context.embedded.ServletRegistrationBean; import org.springframework.http.HttpStatus; import org.springframework.test.util.ReflectionTestUtils; -import static org.hamcrest.Matchers.arrayContaining; -import static org.hamcrest.Matchers.arrayWithSize; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.not; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Matchers.anyObject; import static org.mockito.Mockito.inOrder; import static org.mockito.Mockito.mock; @@ -75,8 +69,8 @@ public class UndertowEmbeddedServletContainerFactoryTests this.container = factory.getEmbeddedServletContainer( new ServletRegistrationBean(new ExampleServlet(), "/hello")); this.container.start(); - assertThat(getResponse(getLocalUrl("/hello")), equalTo("Hello World")); - assertThat(getResponse(getLocalUrl("/not-found")), equalTo("Hello World")); + assertThat(getResponse(getLocalUrl("/hello"))).isEqualTo("Hello World"); + assertThat(getResponse(getLocalUrl("/not-found"))).isEqualTo("Hello World"); } @Test @@ -161,7 +155,7 @@ public class UndertowEmbeddedServletContainerFactoryTests } }); this.container = factory.getEmbeddedServletContainer(); - assertEquals("/", contextPath.get()); + assertThat(contextPath.get()).isEqualTo("/"); } @Test @@ -173,8 +167,8 @@ public class UndertowEmbeddedServletContainerFactoryTests @Test public void eachFactoryUsesADiscreteServletContainer() { - assertThat(getServletContainerFromNewFactory(), - is(not(equalTo(getServletContainerFromNewFactory())))); + assertThat(getServletContainerFromNewFactory()) + .isNotEqualTo(getServletContainerFromNewFactory()); } @Test @@ -184,14 +178,14 @@ public class UndertowEmbeddedServletContainerFactoryTests factory.setAccessLogEnabled(true); File accessLogDirectory = this.temporaryFolder.getRoot(); factory.setAccessLogDirectory(accessLogDirectory); - assertThat(accessLogDirectory.listFiles(), is(arrayWithSize(0))); + assertThat(accessLogDirectory.listFiles()).isEmpty(); this.container = factory.getEmbeddedServletContainer( new ServletRegistrationBean(new ExampleServlet(), "/hello")); this.container.start(); - assertThat(getResponse(getLocalUrl("/hello")), equalTo("Hello World")); + assertThat(getResponse(getLocalUrl("/hello"))).isEqualTo("Hello World"); File accessLog = new File(accessLogDirectory, "access_log.log"); awaitFile(accessLog); - assertThat(accessLogDirectory.listFiles(), is(arrayContaining(accessLog))); + assertThat(accessLogDirectory.listFiles()).contains(accessLog); } @Override diff --git a/spring-boot/src/test/java/org/springframework/boot/context/properties/ConfigurationPropertiesBindingPostProcessorTests.java b/spring-boot/src/test/java/org/springframework/boot/context/properties/ConfigurationPropertiesBindingPostProcessorTests.java index 49d1cfa7df..cc6e73ca36 100644 --- a/spring-boot/src/test/java/org/springframework/boot/context/properties/ConfigurationPropertiesBindingPostProcessorTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/context/properties/ConfigurationPropertiesBindingPostProcessorTests.java @@ -46,15 +46,7 @@ import org.springframework.validation.Errors; import org.springframework.validation.ValidationUtils; import org.springframework.validation.Validator; -import static org.hamcrest.Matchers.contains; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.startsWith; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.fail; /** @@ -98,9 +90,9 @@ public class ConfigurationPropertiesBindingPostProcessorTests { catch (BeanCreationException ex) { RelaxedBindingNotWritablePropertyException bex = (RelaxedBindingNotWritablePropertyException) ex .getRootCause(); - assertThat(bex.getMessage(), - startsWith("Failed to bind 'com.example.baz' from 'test' to 'baz' " - + "property on '" + TestConfiguration.class.getName())); + assertThat(bex.getMessage()) + .startsWith("Failed to bind 'com.example.baz' from 'test' to 'baz' " + + "property on '" + TestConfiguration.class.getName()); } } @@ -125,7 +117,7 @@ public class ConfigurationPropertiesBindingPostProcessorTests { this.context.refresh(); ConfigurationPropertiesBindingPostProcessor bean = this.context .getBean(ConfigurationPropertiesBindingPostProcessor.class); - assertNull(ReflectionTestUtils.getField(bean, "validator")); + assertThat(ReflectionTestUtils.getField(bean, "validator")).isNull(); } @Test @@ -185,8 +177,8 @@ public class ConfigurationPropertiesBindingPostProcessorTests { EnvironmentTestUtils.addEnvironment(this.context, property); this.context.register(PropertyWithEnum.class); this.context.refresh(); - assertThat(this.context.getBean(PropertyWithEnum.class).getTheValue(), - equalTo(FooEnum.FOO)); + assertThat(this.context.getBean(PropertyWithEnum.class).getTheValue()) + .isEqualTo(FooEnum.FOO); this.context.close(); } @@ -203,8 +195,8 @@ public class ConfigurationPropertiesBindingPostProcessorTests { EnvironmentTestUtils.addEnvironment(this.context, property); this.context.register(PropertyWithEnum.class); this.context.refresh(); - assertThat(this.context.getBean(PropertyWithEnum.class).getTheValues(), - contains(expected)); + assertThat(this.context.getBean(PropertyWithEnum.class).getTheValues()) + .contains(expected); this.context.close(); } @@ -214,8 +206,8 @@ public class ConfigurationPropertiesBindingPostProcessorTests { EnvironmentTestUtils.addEnvironment(this.context, "default.value:foo"); this.context.register(PropertyWithValue.class); this.context.refresh(); - assertThat(this.context.getBean(PropertyWithValue.class).getValue(), - equalTo("foo")); + assertThat(this.context.getBean(PropertyWithValue.class).getValue()) + .isEqualTo("foo"); } @Test @@ -224,8 +216,8 @@ public class ConfigurationPropertiesBindingPostProcessorTests { EnvironmentTestUtils.addEnvironment(this.context, "fooValue:bar"); this.context.register(CustomConfigurationLocation.class); this.context.refresh(); - assertThat(this.context.getBean(CustomConfigurationLocation.class).getFoo(), - equalTo("bar")); + assertThat(this.context.getBean(CustomConfigurationLocation.class).getFoo()) + .isEqualTo("bar"); } @Test @@ -235,8 +227,8 @@ public class ConfigurationPropertiesBindingPostProcessorTests { this.context.register(UnmergedCustomConfigurationLocation.class); this.context.refresh(); assertThat( - this.context.getBean(UnmergedCustomConfigurationLocation.class).getFoo(), - equalTo("${fooValue}")); + this.context.getBean(UnmergedCustomConfigurationLocation.class).getFoo()) + .isEqualTo("${fooValue}"); } @Test @@ -245,8 +237,8 @@ public class ConfigurationPropertiesBindingPostProcessorTests { this.context = new AnnotationConfigApplicationContext() { @Override protected void onRefresh() throws BeansException { - assertFalse("Init too early", - ConfigurationPropertiesWithFactoryBean.factoryBeanInit); + assertThat(ConfigurationPropertiesWithFactoryBean.factoryBeanInit) + .as("Init too early").isFalse(); super.onRefresh(); } }; @@ -256,7 +248,8 @@ public class ConfigurationPropertiesBindingPostProcessorTests { beanDefinition.setAutowireMode(AbstractBeanDefinition.AUTOWIRE_BY_TYPE); this.context.registerBeanDefinition("test", beanDefinition); this.context.refresh(); - assertTrue("No init", ConfigurationPropertiesWithFactoryBean.factoryBeanInit); + assertThat(ConfigurationPropertiesWithFactoryBean.factoryBeanInit).as("No init") + .isTrue(); } @Test @@ -265,8 +258,8 @@ public class ConfigurationPropertiesBindingPostProcessorTests { EnvironmentTestUtils.addEnvironment(this.context, "test.chars:word"); this.context.register(PropertyWithCharArray.class); this.context.refresh(); - assertThat(this.context.getBean(PropertyWithCharArray.class).getChars(), - equalTo("word".toCharArray())); + assertThat(this.context.getBean(PropertyWithCharArray.class).getChars()) + .isEqualTo("word".toCharArray()); } @Test @@ -275,8 +268,8 @@ public class ConfigurationPropertiesBindingPostProcessorTests { EnvironmentTestUtils.addEnvironment(this.context, "test.chars[4]:s"); this.context.register(PropertyWithCharArrayExpansion.class); this.context.refresh(); - assertThat(this.context.getBean(PropertyWithCharArrayExpansion.class).getChars(), - equalTo("words".toCharArray())); + assertThat(this.context.getBean(PropertyWithCharArrayExpansion.class).getChars()) + .isEqualTo("words".toCharArray()); } @Test @@ -304,8 +297,8 @@ public class ConfigurationPropertiesBindingPostProcessorTests { EnvironmentTestUtils.addEnvironment(this.context, environment); this.context.register(RelaxedPropertyNames.class); this.context.refresh(); - assertThat(this.context.getBean(RelaxedPropertyNames.class).getFooBar(), - equalTo("test2")); + assertThat(this.context.getBean(RelaxedPropertyNames.class).getFooBar()) + .isEqualTo("test2"); } @Test @@ -316,7 +309,7 @@ public class ConfigurationPropertiesBindingPostProcessorTests { this.context.register(PropertyWithNestedValue.class); this.context.refresh(); assertThat(this.context.getBean(PropertyWithNestedValue.class).getNested() - .getValue(), equalTo("test1")); + .getValue()).isEqualTo("test1"); } @Test @@ -337,7 +330,7 @@ public class ConfigurationPropertiesBindingPostProcessorTests { } catch (BeanCreationException ex) { BindException bex = (BindException) ex.getRootCause(); - assertEquals(errorCount, bex.getErrorCount()); + assertThat(bex.getErrorCount()).isEqualTo(errorCount); } } @@ -434,7 +427,7 @@ public class ConfigurationPropertiesBindingPostProcessorTests { @PostConstruct public void init() { - assertNotNull(this.bar); + assertThat(this.bar).isNotNull(); } } diff --git a/spring-boot/src/test/java/org/springframework/boot/context/properties/EnableConfigurationPropertiesTests.java b/spring-boot/src/test/java/org/springframework/boot/context/properties/EnableConfigurationPropertiesTests.java index 839ec10fb7..ec16251125 100644 --- a/spring-boot/src/test/java/org/springframework/boot/context/properties/EnableConfigurationPropertiesTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/context/properties/EnableConfigurationPropertiesTests.java @@ -17,7 +17,6 @@ package org.springframework.boot.context.properties; import java.util.ArrayList; -import java.util.Arrays; import java.util.List; import java.util.Map; @@ -40,8 +39,7 @@ import org.springframework.core.env.MutablePropertySources; import org.springframework.stereotype.Component; import org.springframework.validation.BindException; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link EnableConfigurationProperties}. @@ -68,8 +66,8 @@ public class EnableConfigurationPropertiesTests { this.context.register(TestConfiguration.class); EnvironmentTestUtils.addEnvironment(this.context, "name:foo"); this.context.refresh(); - assertEquals(1, this.context.getBeanNamesForType(TestProperties.class).length); - assertEquals("foo", this.context.getBean(TestProperties.class).name); + assertThat(this.context.getBeanNamesForType(TestProperties.class)).hasSize(1); + assertThat(this.context.getBean(TestProperties.class).name).isEqualTo("foo"); } @Test @@ -77,8 +75,8 @@ public class EnableConfigurationPropertiesTests { this.context.register(TestConfiguration.class); System.setProperty("name", "foo"); this.context.refresh(); - assertEquals(1, this.context.getBeanNamesForType(TestProperties.class).length); - assertEquals("foo", this.context.getBean(TestProperties.class).name); + assertThat(this.context.getBeanNamesForType(TestProperties.class)).hasSize(1); + assertThat(this.context.getBean(TestProperties.class).name).isEqualTo("foo"); } @Test @@ -87,9 +85,10 @@ public class EnableConfigurationPropertiesTests { System.setProperty("name", "foo"); System.setProperty("nested.name", "bar"); this.context.refresh(); - assertEquals(1, this.context.getBeanNamesForType(NestedProperties.class).length); - assertEquals("foo", this.context.getBean(NestedProperties.class).name); - assertEquals("bar", this.context.getBean(NestedProperties.class).nested.name); + assertThat(this.context.getBeanNamesForType(NestedProperties.class)).hasSize(1); + assertThat(this.context.getBean(NestedProperties.class).name).isEqualTo("foo"); + assertThat(this.context.getBean(NestedProperties.class).nested.name) + .isEqualTo("bar"); } @Test @@ -98,9 +97,10 @@ public class EnableConfigurationPropertiesTests { System.setProperty("name", "foo"); System.setProperty("nested_name", "bar"); this.context.refresh(); - assertEquals(1, this.context.getBeanNamesForType(NestedProperties.class).length); - assertEquals("foo", this.context.getBean(NestedProperties.class).name); - assertEquals("bar", this.context.getBean(NestedProperties.class).nested.name); + assertThat(this.context.getBeanNamesForType(NestedProperties.class)).hasSize(1); + assertThat(this.context.getBean(NestedProperties.class).name).isEqualTo("foo"); + assertThat(this.context.getBean(NestedProperties.class).nested.name) + .isEqualTo("bar"); } @Test @@ -108,9 +108,10 @@ public class EnableConfigurationPropertiesTests { EnvironmentTestUtils.addEnvironment(this.context, "NAME:foo", "NESTED_NAME:bar"); this.context.register(NestedConfiguration.class); this.context.refresh(); - assertEquals(1, this.context.getBeanNamesForType(NestedProperties.class).length); - assertEquals("foo", this.context.getBean(NestedProperties.class).name); - assertEquals("bar", this.context.getBean(NestedProperties.class).nested.name); + assertThat(this.context.getBeanNamesForType(NestedProperties.class)).hasSize(1); + assertThat(this.context.getBean(NestedProperties.class).name).isEqualTo("foo"); + assertThat(this.context.getBean(NestedProperties.class).nested.name) + .isEqualTo("bar"); } @Test @@ -119,9 +120,9 @@ public class EnableConfigurationPropertiesTests { this.context.register(StrictTestConfiguration.class); EnvironmentTestUtils.addEnvironment(this.context, "name:foo"); this.context.refresh(); - assertEquals(1, - this.context.getBeanNamesForType(StrictTestProperties.class).length); - assertEquals("foo", this.context.getBean(TestProperties.class).name); + assertThat(this.context.getBeanNamesForType(StrictTestProperties.class)) + .hasSize(1); + assertThat(this.context.getBean(TestProperties.class).name).isEqualTo("foo"); } @Test @@ -129,9 +130,9 @@ public class EnableConfigurationPropertiesTests { this.context.register(EmbeddedTestConfiguration.class); EnvironmentTestUtils.addEnvironment(this.context, "spring_foo_name:foo"); this.context.refresh(); - assertEquals(1, - this.context.getBeanNamesForType(EmbeddedTestProperties.class).length); - assertEquals("foo", this.context.getBean(TestProperties.class).name); + assertThat(this.context.getBeanNamesForType(EmbeddedTestProperties.class)) + .hasSize(1); + assertThat(this.context.getBean(TestProperties.class).name).isEqualTo("foo"); } @Test @@ -139,9 +140,9 @@ public class EnableConfigurationPropertiesTests { EnvironmentTestUtils.addEnvironment(this.context, "SPRING_FOO_NAME:foo"); this.context.register(EmbeddedTestConfiguration.class); this.context.refresh(); - assertEquals(1, - this.context.getBeanNamesForType(EmbeddedTestProperties.class).length); - assertEquals("foo", this.context.getBean(TestProperties.class).name); + assertThat(this.context.getBeanNamesForType(EmbeddedTestProperties.class)) + .hasSize(1); + assertThat(this.context.getBean(TestProperties.class).name).isEqualTo("foo"); } @Test @@ -150,9 +151,9 @@ public class EnableConfigurationPropertiesTests { this.context.register(IgnoreNestedTestConfiguration.class); EnvironmentTestUtils.addEnvironment(this.context, "name:foo", "nested.name:bar"); this.context.refresh(); - assertEquals(1, this.context - .getBeanNamesForType(IgnoreNestedTestProperties.class).length); - assertEquals("foo", this.context.getBean(TestProperties.class).name); + assertThat(this.context.getBeanNamesForType(IgnoreNestedTestProperties.class)) + .hasSize(1); + assertThat(this.context.getBean(TestProperties.class).name).isEqualTo("foo"); } @Test @@ -168,9 +169,10 @@ public class EnableConfigurationPropertiesTests { this.context.register(NoExceptionIfInvalidTestConfiguration.class); EnvironmentTestUtils.addEnvironment(this.context, "name:foo"); this.context.refresh(); - assertEquals(1, this.context - .getBeanNamesForType(NoExceptionIfInvalidTestProperties.class).length); - assertEquals("foo", this.context.getBean(TestProperties.class).name); + assertThat(this.context + .getBeanNamesForType(NoExceptionIfInvalidTestProperties.class)) + .hasSize(1); + assertThat(this.context.getBean(TestProperties.class).name).isEqualTo("foo"); } @Test @@ -178,9 +180,10 @@ public class EnableConfigurationPropertiesTests { this.context.register(NestedConfiguration.class); EnvironmentTestUtils.addEnvironment(this.context, "name:foo", "nested.name:bar"); this.context.refresh(); - assertEquals(1, this.context.getBeanNamesForType(NestedProperties.class).length); - assertEquals("foo", this.context.getBean(NestedProperties.class).name); - assertEquals("bar", this.context.getBean(NestedProperties.class).nested.name); + assertThat(this.context.getBeanNamesForType(NestedProperties.class)).hasSize(1); + assertThat(this.context.getBean(NestedProperties.class).name).isEqualTo("foo"); + assertThat(this.context.getBean(NestedProperties.class).nested.name) + .isEqualTo("bar"); } @Test @@ -188,8 +191,8 @@ public class EnableConfigurationPropertiesTests { this.context.register(DerivedConfiguration.class); EnvironmentTestUtils.addEnvironment(this.context, "name:foo"); this.context.refresh(); - assertEquals(1, this.context.getBeanNamesForType(DerivedProperties.class).length); - assertEquals("foo", this.context.getBean(BaseProperties.class).name); + assertThat(this.context.getBeanNamesForType(DerivedProperties.class)).hasSize(1); + assertThat(this.context.getBean(BaseProperties.class).name).isEqualTo("foo"); } @Test @@ -197,8 +200,8 @@ public class EnableConfigurationPropertiesTests { this.context.register(TestConfiguration.class); EnvironmentTestUtils.addEnvironment(this.context, "name:foo", "array:1,2,3"); this.context.refresh(); - assertEquals(1, this.context.getBeanNamesForType(TestProperties.class).length); - assertEquals(3, this.context.getBean(TestProperties.class).getArray().length); + assertThat(this.context.getBeanNamesForType(TestProperties.class)).hasSize(1); + assertThat(this.context.getBean(TestProperties.class).getArray()).hasSize(3); } @Test @@ -207,7 +210,7 @@ public class EnableConfigurationPropertiesTests { EnvironmentTestUtils.addEnvironment(this.context, "name:foo", "list[0]:1", "list[1]:2"); this.context.refresh(); - assertEquals(2, this.context.getBean(TestProperties.class).getList().size()); + assertThat(this.context.getBean(TestProperties.class).getList()).hasSize(2); } @Test @@ -225,8 +228,8 @@ public class EnableConfigurationPropertiesTests { this.context.register(MoreConfiguration.class); EnvironmentTestUtils.addEnvironment(this.context, "name:foo"); this.context.refresh(); - assertEquals(1, this.context.getBeanNamesForType(MoreProperties.class).length); - assertEquals("foo", this.context.getBean(MoreProperties.class).name); + assertThat(this.context.getBeanNamesForType(MoreProperties.class)).hasSize(1); + assertThat(this.context.getBean(MoreProperties.class).name).isEqualTo("foo"); } @Test @@ -234,8 +237,8 @@ public class EnableConfigurationPropertiesTests { this.context.register(TestConfiguration.class, DefaultXmlConfiguration.class); this.context.refresh(); String[] beanNames = this.context.getBeanNamesForType(TestProperties.class); - assertEquals("Wrong beans: " + Arrays.asList(beanNames), 1, beanNames.length); - assertEquals("bar", this.context.getBean(TestProperties.class).name); + assertThat(beanNames).as("Wrong beans").containsExactly(beanNames); + assertThat(this.context.getBean(TestProperties.class).name).isEqualTo("bar"); } @Test @@ -243,17 +246,18 @@ public class EnableConfigurationPropertiesTests { this.context.register(DefaultConfiguration.class); this.context.refresh(); String[] beanNames = this.context.getBeanNamesForType(TestProperties.class); - assertEquals("Wrong beans: " + Arrays.asList(beanNames), 1, beanNames.length); - assertEquals("bar", this.context.getBean(TestProperties.class).name); + assertThat(beanNames).as("Wrong beans").containsExactly(beanNames); + assertThat(this.context.getBean(TestProperties.class).name).isEqualTo("bar"); } @Test public void testBindingDirectlyToFile() { this.context.register(ResourceBindingProperties.class, TestConfiguration.class); this.context.refresh(); - assertEquals(1, - this.context.getBeanNamesForType(ResourceBindingProperties.class).length); - assertEquals("foo", this.context.getBean(ResourceBindingProperties.class).name); + assertThat(this.context.getBeanNamesForType(ResourceBindingProperties.class)) + .hasSize(1); + assertThat(this.context.getBean(ResourceBindingProperties.class).name) + .isEqualTo("foo"); } @Test @@ -262,9 +266,10 @@ public class EnableConfigurationPropertiesTests { "binding.location:classpath:other.yml"); this.context.register(ResourceBindingProperties.class, TestConfiguration.class); this.context.refresh(); - assertEquals(1, - this.context.getBeanNamesForType(ResourceBindingProperties.class).length); - assertEquals("other", this.context.getBean(ResourceBindingProperties.class).name); + assertThat(this.context.getBeanNamesForType(ResourceBindingProperties.class)) + .hasSize(1); + assertThat(this.context.getBean(ResourceBindingProperties.class).name) + .isEqualTo("other"); } @Test @@ -272,9 +277,10 @@ public class EnableConfigurationPropertiesTests { this.context.register(ResourceBindingProperties.class, TestConfiguration.class); this.context.getEnvironment().addActiveProfile("nonexistent"); this.context.refresh(); - assertEquals(1, - this.context.getBeanNamesForType(ResourceBindingProperties.class).length); - assertEquals("foo", this.context.getBean(ResourceBindingProperties.class).name); + assertThat(this.context.getBeanNamesForType(ResourceBindingProperties.class)) + .hasSize(1); + assertThat(this.context.getBean(ResourceBindingProperties.class).name) + .isEqualTo("foo"); } @Test @@ -282,9 +288,10 @@ public class EnableConfigurationPropertiesTests { this.context.register(ResourceBindingProperties.class, TestConfiguration.class); this.context.getEnvironment().addActiveProfile("super"); this.context.refresh(); - assertEquals(1, - this.context.getBeanNamesForType(ResourceBindingProperties.class).length); - assertEquals("bar", this.context.getBean(ResourceBindingProperties.class).name); + assertThat(this.context.getBeanNamesForType(ResourceBindingProperties.class)) + .hasSize(1); + assertThat(this.context.getBean(ResourceBindingProperties.class).name) + .isEqualTo("bar"); } @Test @@ -292,17 +299,20 @@ public class EnableConfigurationPropertiesTests { this.context.register(ResourceBindingProperties.class, TestConfiguration.class); this.context.getEnvironment().setActiveProfiles("super", "other"); this.context.refresh(); - assertEquals(1, - this.context.getBeanNamesForType(ResourceBindingProperties.class).length); - assertEquals("spam", this.context.getBean(ResourceBindingProperties.class).name); + assertThat(this.context.getBeanNamesForType(ResourceBindingProperties.class)) + .hasSize(1); + assertThat(this.context.getBean(ResourceBindingProperties.class).name) + .isEqualTo("spam"); } @Test public void testBindingWithTwoBeans() { this.context.register(MoreConfiguration.class, TestConfiguration.class); this.context.refresh(); - assertEquals(1, this.context.getBeanNamesForType(TestProperties.class).length); - assertEquals(1, this.context.getBeanNamesForType(MoreProperties.class).length); + assertThat(this.context.getBeanNamesForType(TestProperties.class).length) + .isEqualTo(1); + assertThat(this.context.getBeanNamesForType(MoreProperties.class).length) + .isEqualTo(1); } @Test @@ -314,9 +324,10 @@ public class EnableConfigurationPropertiesTests { this.context.setParent(parent); this.context.register(TestConfiguration.class, TestConsumer.class); this.context.refresh(); - assertEquals(1, this.context.getBeanNamesForType(TestProperties.class).length); - assertEquals(1, parent.getBeanNamesForType(TestProperties.class).length); - assertEquals("foo", this.context.getBean(TestConsumer.class).getName()); + assertThat(this.context.getBeanNamesForType(TestProperties.class).length) + .isEqualTo(1); + assertThat(parent.getBeanNamesForType(TestProperties.class).length).isEqualTo(1); + assertThat(this.context.getBean(TestConsumer.class).getName()).isEqualTo("foo"); } @Test @@ -328,9 +339,10 @@ public class EnableConfigurationPropertiesTests { this.context.setParent(parent); this.context.register(TestConsumer.class); this.context.refresh(); - assertEquals(0, this.context.getBeanNamesForType(TestProperties.class).length); - assertEquals(1, parent.getBeanNamesForType(TestProperties.class).length); - assertEquals("foo", this.context.getBean(TestConsumer.class).getName()); + assertThat(this.context.getBeanNamesForType(TestProperties.class).length) + .isEqualTo(0); + assertThat(parent.getBeanNamesForType(TestProperties.class).length).isEqualTo(1); + assertThat(this.context.getBean(TestConsumer.class).getName()).isEqualTo("foo"); } @Test @@ -338,7 +350,7 @@ public class EnableConfigurationPropertiesTests { EnvironmentTestUtils.addEnvironment(this.context, "spring_test_external_val:baz"); this.context.register(SystemExampleConfig.class); this.context.refresh(); - assertEquals("baz", this.context.getBean(SystemEnvVar.class).getVal()); + assertThat(this.context.getBean(SystemEnvVar.class).getVal()).isEqualTo("baz"); } @Test @@ -346,7 +358,7 @@ public class EnableConfigurationPropertiesTests { EnvironmentTestUtils.addEnvironment(this.context, "external.name:foo"); this.context.register(ExampleConfig.class); this.context.refresh(); - assertEquals("foo", this.context.getBean(External.class).getName()); + assertThat(this.context.getBean(External.class).getName()).isEqualTo("foo"); } @Test @@ -354,7 +366,7 @@ public class EnableConfigurationPropertiesTests { EnvironmentTestUtils.addEnvironment(this.context, "external.name:foo"); this.context.register(AnotherExampleConfig.class); this.context.refresh(); - assertEquals("foo", this.context.getBean(External.class).getName()); + assertThat(this.context.getBean(External.class).getName()).isEqualTo("foo"); } @Test @@ -363,8 +375,8 @@ public class EnableConfigurationPropertiesTests { "another.name:bar"); this.context.register(FurtherExampleConfig.class); this.context.refresh(); - assertEquals("foo", this.context.getBean(External.class).getName()); - assertEquals("bar", this.context.getBean(Another.class).getName()); + assertThat(this.context.getBean(External.class).getName()).isEqualTo("foo"); + assertThat(this.context.getBean(Another.class).getName()).isEqualTo("bar"); } @Test @@ -374,10 +386,10 @@ public class EnableConfigurationPropertiesTests { ResourceBindingPropertiesWithMap bean = this.context .getBean(ResourceBindingPropertiesWithMap.class); - assertEquals("value3", bean.mymap.get("key3")); + assertThat(bean.mymap.get("key3")).isEqualTo("value3"); // this should not fail!!! // mymap looks to contain - {key1=, key3=value3} - assertEquals("value12", bean.mymap.get("key1.key2")); + assertThat(bean.mymap.get("key1.key2")).isEqualTo("value12"); } @Test @@ -386,7 +398,7 @@ public class EnableConfigurationPropertiesTests { "spam.name:foo"); this.context.register(TestConfigurationWithAnnotatedBean.class); this.context.refresh(); - assertEquals("foo", this.context.getBean(External.class).getName()); + assertThat(this.context.getBean(External.class).getName()).isEqualTo("foo"); } /** @@ -560,7 +572,7 @@ public class EnableConfigurationPropertiesTests { @PostConstruct public void init() { - assertNotNull(this.properties); + assertThat(this.properties).isNotNull(); } public String getName() { diff --git a/spring-boot/src/test/java/org/springframework/boot/context/web/ErrorPageFilterIntegrationTests.java b/spring-boot/src/test/java/org/springframework/boot/context/web/ErrorPageFilterIntegrationTests.java index 07bd1e028c..c206456c19 100644 --- a/spring-boot/src/test/java/org/springframework/boot/context/web/ErrorPageFilterIntegrationTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/context/web/ErrorPageFilterIntegrationTests.java @@ -52,8 +52,7 @@ import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; -import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; /** * Integration tests for {@link ErrorPageFilter}. @@ -80,13 +79,13 @@ public class ErrorPageFilterIntegrationTests { @Test public void created() throws Exception { doTest(this.context, "/create", HttpStatus.CREATED); - assertThat(this.controller.getStatus(), equalTo(201)); + assertThat(this.controller.getStatus()).isEqualTo(201); } @Test public void ok() throws Exception { doTest(this.context, "/hello", HttpStatus.OK); - assertThat(this.controller.getStatus(), equalTo(200)); + assertThat(this.controller.getStatus()).isEqualTo(200); } private void doTest(AnnotationConfigEmbeddedWebApplicationContext context, @@ -95,8 +94,8 @@ public class ErrorPageFilterIntegrationTests { TestRestTemplate template = new TestRestTemplate(); ResponseEntity entity = template.getForEntity( new URI("http://localhost:" + port + resourcePath), String.class); - assertThat(entity.getBody(), equalTo("Hello World")); - assertThat(entity.getStatusCode(), equalTo(status)); + assertThat(entity.getBody()).isEqualTo("Hello World"); + assertThat(entity.getStatusCode()).isEqualTo(status); } @Configuration @@ -133,8 +132,8 @@ public class ErrorPageFilterIntegrationTests { private CountDownLatch latch = new CountDownLatch(1); public int getStatus() throws InterruptedException { - assertThat("Timed out waiting for latch", - this.latch.await(1, TimeUnit.SECONDS), equalTo(true)); + assertThat(this.latch.await(1, TimeUnit.SECONDS)) + .as("Timed out waiting for latch").isTrue(); return this.status; } diff --git a/spring-boot/src/test/java/org/springframework/boot/context/web/ErrorPageFilterTests.java b/spring-boot/src/test/java/org/springframework/boot/context/web/ErrorPageFilterTests.java index dcfa15d9c6..c2b358e93c 100644 --- a/spring-boot/src/test/java/org/springframework/boot/context/web/ErrorPageFilterTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/context/web/ErrorPageFilterTests.java @@ -41,14 +41,7 @@ import org.springframework.web.context.request.async.WebAsyncManager; import org.springframework.web.context.request.async.WebAsyncUtils; import org.springframework.web.util.NestedServletException; -import static org.hamcrest.Matchers.containsString; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.nullValue; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; @@ -77,11 +70,11 @@ public class ErrorPageFilterTests { @Test public void notAnError() throws Exception { this.filter.doFilter(this.request, this.response, this.chain); - assertThat(this.chain.getRequest(), equalTo((ServletRequest) this.request)); - assertThat(((HttpServletResponseWrapper) this.chain.getResponse()).getResponse(), - equalTo((ServletResponse) this.response)); - assertTrue(this.response.isCommitted()); - assertThat(this.response.getForwardedUrl(), is(nullValue())); + assertThat(this.chain.getRequest()).isEqualTo(this.request); + assertThat(((HttpServletResponseWrapper) this.chain.getResponse()).getResponse()) + .isEqualTo(this.response); + assertThat(this.response.isCommitted()).isTrue(); + assertThat(this.response.getForwardedUrl()).isNull(); } @Test @@ -96,11 +89,11 @@ public class ErrorPageFilterTests { } }; this.filter.doFilter(this.request, this.response, this.chain); - assertThat(((HttpServletResponse) this.chain.getResponse()).getStatus(), - equalTo(201)); + assertThat(((HttpServletResponse) this.chain.getResponse()).getStatus()) + .isEqualTo(201); assertThat(((HttpServletResponse) ((HttpServletResponseWrapper) this.chain - .getResponse()).getResponse()).getStatus(), equalTo(201)); - assertTrue(this.response.isCommitted()); + .getResponse()).getResponse()).getStatus()).isEqualTo(201); + assertThat(this.response.isCommitted()).isTrue(); } @Test @@ -115,15 +108,15 @@ public class ErrorPageFilterTests { } }; this.filter.doFilter(this.request, this.response, this.chain); - assertThat(this.chain.getRequest(), equalTo((ServletRequest) this.request)); + assertThat(this.chain.getRequest()).isEqualTo(this.request); HttpServletResponseWrapper wrapper = (HttpServletResponseWrapper) this.chain .getResponse(); - assertThat(wrapper.getResponse(), equalTo((ServletResponse) this.response)); - assertTrue(this.response.isCommitted()); - assertThat(wrapper.getStatus(), equalTo(401)); + assertThat(wrapper.getResponse()).isEqualTo(this.response); + assertThat(this.response.isCommitted()).isTrue(); + assertThat(wrapper.getStatus()).isEqualTo(401); // The real response has to be 401 as well... - assertThat(this.response.getStatus(), equalTo(401)); - assertThat(this.response.getForwardedUrl(), equalTo("/error")); + assertThat(this.response.getStatus()).isEqualTo(401); + assertThat(this.response.getForwardedUrl()).isEqualTo("/error"); } @Test @@ -139,13 +132,13 @@ public class ErrorPageFilterTests { } }; this.filter.doFilter(this.request, this.response, this.chain); - assertThat(this.chain.getRequest(), equalTo((ServletRequest) this.request)); - assertThat(((HttpServletResponseWrapper) this.chain.getResponse()).getResponse(), - equalTo((ServletResponse) this.response)); - assertThat(((HttpServletResponseWrapper) this.chain.getResponse()).getStatus(), - equalTo(400)); - assertThat(this.response.getForwardedUrl(), is(nullValue())); - assertTrue(this.response.isCommitted()); + assertThat(this.chain.getRequest()).isEqualTo(this.request); + assertThat(((HttpServletResponseWrapper) this.chain.getResponse()).getResponse()) + .isEqualTo(this.response); + assertThat(((HttpServletResponseWrapper) this.chain.getResponse()).getStatus()) + .isEqualTo(400); + assertThat(this.response.getForwardedUrl()).isNull(); + assertThat(this.response.isCommitted()).isTrue(); } @Test @@ -159,13 +152,13 @@ public class ErrorPageFilterTests { } }; this.filter.doFilter(this.request, this.response, this.chain); - assertThat(this.chain.getRequest(), equalTo((ServletRequest) this.request)); - assertThat(((HttpServletResponseWrapper) this.chain.getResponse()).getResponse(), - equalTo((ServletResponse) this.response)); - assertThat(((HttpServletResponseWrapper) this.chain.getResponse()).getStatus(), - equalTo(400)); - assertThat(this.response.getForwardedUrl(), is(nullValue())); - assertTrue(this.response.isCommitted()); + assertThat(this.chain.getRequest()).isEqualTo(this.request); + assertThat(((HttpServletResponseWrapper) this.chain.getResponse()).getResponse()) + .isEqualTo(this.response); + assertThat(((HttpServletResponseWrapper) this.chain.getResponse()).getStatus()) + .isEqualTo(400); + assertThat(this.response.getForwardedUrl()).isNull(); + assertThat(this.response.isCommitted()).isTrue(); } @Test @@ -175,7 +168,7 @@ public class ErrorPageFilterTests { public void doFilter(ServletRequest request, ServletResponse response) throws IOException, ServletException { ((HttpServletResponse) response).sendError(400, "BAD"); - assertNotNull(request.getAttribute("FILTER.FILTERED")); + assertThat(request.getAttribute("FILTER.FILTERED")).isNotNull(); super.doFilter(request, response); } }; @@ -195,17 +188,16 @@ public class ErrorPageFilterTests { } }; this.filter.doFilter(this.request, this.response, this.chain); - assertThat(((HttpServletResponseWrapper) this.chain.getResponse()).getStatus(), - equalTo(400)); - assertThat(this.request.getAttribute(RequestDispatcher.ERROR_STATUS_CODE), - equalTo((Object) 400)); - assertThat(this.request.getAttribute(RequestDispatcher.ERROR_MESSAGE), - equalTo((Object) "BAD")); - assertThat(this.request.getAttribute(RequestDispatcher.ERROR_REQUEST_URI), - equalTo((Object) "/test/path")); - - assertTrue(this.response.isCommitted()); - assertThat(this.response.getForwardedUrl(), equalTo("/error")); + assertThat(((HttpServletResponseWrapper) this.chain.getResponse()).getStatus()) + .isEqualTo(400); + assertThat(this.request.getAttribute(RequestDispatcher.ERROR_STATUS_CODE)) + .isEqualTo(400); + assertThat(this.request.getAttribute(RequestDispatcher.ERROR_MESSAGE)) + .isEqualTo("BAD"); + assertThat(this.request.getAttribute(RequestDispatcher.ERROR_REQUEST_URI)) + .isEqualTo("/test/path"); + assertThat(this.response.isCommitted()).isTrue(); + assertThat(this.response.getForwardedUrl()).isEqualTo("/error"); } @Test @@ -220,16 +212,16 @@ public class ErrorPageFilterTests { } }; this.filter.doFilter(this.request, this.response, this.chain); - assertThat(((HttpServletResponseWrapper) this.chain.getResponse()).getStatus(), - equalTo(400)); - assertThat(this.request.getAttribute(RequestDispatcher.ERROR_STATUS_CODE), - equalTo((Object) 400)); - assertThat(this.request.getAttribute(RequestDispatcher.ERROR_MESSAGE), - equalTo((Object) "BAD")); - assertThat(this.request.getAttribute(RequestDispatcher.ERROR_REQUEST_URI), - equalTo((Object) "/test/path")); - assertTrue(this.response.isCommitted()); - assertThat(this.response.getForwardedUrl(), equalTo("/400")); + assertThat(((HttpServletResponseWrapper) this.chain.getResponse()).getStatus()) + .isEqualTo(400); + assertThat(this.request.getAttribute(RequestDispatcher.ERROR_STATUS_CODE)) + .isEqualTo(400); + assertThat(this.request.getAttribute(RequestDispatcher.ERROR_MESSAGE)) + .isEqualTo("BAD"); + assertThat(this.request.getAttribute(RequestDispatcher.ERROR_REQUEST_URI)) + .isEqualTo("/test/path"); + assertThat(this.response.isCommitted()).isTrue(); + assertThat(this.response.getForwardedUrl()).isEqualTo("/400"); } @Test @@ -245,10 +237,10 @@ public class ErrorPageFilterTests { } }; this.filter.doFilter(this.request, this.response, this.chain); - assertThat(((HttpServletResponseWrapper) this.chain.getResponse()).getStatus(), - equalTo(400)); - assertTrue(this.response.isCommitted()); - assertThat(this.response.getForwardedUrl(), is(nullValue())); + assertThat(((HttpServletResponseWrapper) this.chain.getResponse()).getStatus()) + .isEqualTo(400); + assertThat(this.response.isCommitted()).isTrue(); + assertThat(this.response.getForwardedUrl()).isNull(); } @Test @@ -263,18 +255,18 @@ public class ErrorPageFilterTests { } }; this.filter.doFilter(this.request, this.response, this.chain); - assertThat(((HttpServletResponseWrapper) this.chain.getResponse()).getStatus(), - equalTo(500)); - assertThat(this.request.getAttribute(RequestDispatcher.ERROR_STATUS_CODE), - equalTo((Object) 500)); - assertThat(this.request.getAttribute(RequestDispatcher.ERROR_MESSAGE), - equalTo((Object) "BAD")); - assertThat(this.request.getAttribute(RequestDispatcher.ERROR_EXCEPTION_TYPE), - equalTo((Object) RuntimeException.class.getName())); - assertThat(this.request.getAttribute(RequestDispatcher.ERROR_REQUEST_URI), - equalTo((Object) "/test/path")); - assertTrue(this.response.isCommitted()); - assertThat(this.response.getForwardedUrl(), equalTo("/500")); + assertThat(((HttpServletResponseWrapper) this.chain.getResponse()).getStatus()) + .isEqualTo(500); + assertThat(this.request.getAttribute(RequestDispatcher.ERROR_STATUS_CODE)) + .isEqualTo(500); + assertThat(this.request.getAttribute(RequestDispatcher.ERROR_MESSAGE)) + .isEqualTo("BAD"); + assertThat(this.request.getAttribute(RequestDispatcher.ERROR_EXCEPTION_TYPE)) + .isEqualTo(RuntimeException.class.getName()); + assertThat(this.request.getAttribute(RequestDispatcher.ERROR_REQUEST_URI)) + .isEqualTo("/test/path"); + assertThat(this.response.isCommitted()).isTrue(); + assertThat(this.response.getForwardedUrl()).isEqualTo("/500"); } @Test @@ -290,7 +282,7 @@ public class ErrorPageFilterTests { } }; this.filter.doFilter(this.request, this.response, this.chain); - assertThat(this.response.getForwardedUrl(), is(nullValue())); + assertThat(this.response.getForwardedUrl()).isNull(); } @Test @@ -299,13 +291,13 @@ public class ErrorPageFilterTests { @Override public void doFilter(ServletRequest request, ServletResponse response) throws IOException, ServletException { - assertThat(((HttpServletResponse) response).getStatus(), equalTo(200)); + assertThat(((HttpServletResponse) response).getStatus()).isEqualTo(200); super.doFilter(request, response); } }; this.filter.doFilter(this.request, this.response, this.chain); - assertThat(((HttpServletResponseWrapper) this.chain.getResponse()).getStatus(), - equalTo(200)); + assertThat(((HttpServletResponseWrapper) this.chain.getResponse()).getStatus()) + .isEqualTo(200); } @Test @@ -320,27 +312,27 @@ public class ErrorPageFilterTests { } }; this.filter.doFilter(this.request, this.response, this.chain); - assertThat(((HttpServletResponseWrapper) this.chain.getResponse()).getStatus(), - equalTo(500)); - assertThat(this.request.getAttribute(RequestDispatcher.ERROR_STATUS_CODE), - equalTo((Object) 500)); - assertThat(this.request.getAttribute(RequestDispatcher.ERROR_MESSAGE), - equalTo((Object) "BAD")); - assertThat(this.request.getAttribute(RequestDispatcher.ERROR_EXCEPTION_TYPE), - equalTo((Object) IllegalStateException.class.getName())); - assertThat(this.request.getAttribute(RequestDispatcher.ERROR_REQUEST_URI), - equalTo((Object) "/test/path")); - assertTrue(this.response.isCommitted()); + assertThat(((HttpServletResponseWrapper) this.chain.getResponse()).getStatus()) + .isEqualTo(500); + assertThat(this.request.getAttribute(RequestDispatcher.ERROR_STATUS_CODE)) + .isEqualTo(500); + assertThat(this.request.getAttribute(RequestDispatcher.ERROR_MESSAGE)) + .isEqualTo("BAD"); + assertThat(this.request.getAttribute(RequestDispatcher.ERROR_EXCEPTION_TYPE)) + .isEqualTo(IllegalStateException.class.getName()); + assertThat(this.request.getAttribute(RequestDispatcher.ERROR_REQUEST_URI)) + .isEqualTo("/test/path"); + assertThat(this.response.isCommitted()).isTrue(); } @Test public void responseIsNotCommittedWhenRequestIsAsync() throws Exception { this.request.setAsyncStarted(true); this.filter.doFilter(this.request, this.response, this.chain); - assertThat(this.chain.getRequest(), equalTo((ServletRequest) this.request)); - assertThat(((HttpServletResponseWrapper) this.chain.getResponse()).getResponse(), - equalTo((ServletResponse) this.response)); - assertFalse(this.response.isCommitted()); + assertThat(this.chain.getRequest()).isEqualTo(this.request); + assertThat(((HttpServletResponseWrapper) this.chain.getResponse()).getResponse()) + .isEqualTo(this.response); + assertThat(this.response.isCommitted()).isFalse(); } @Test @@ -357,10 +349,10 @@ public class ErrorPageFilterTests { } }; this.filter.doFilter(this.request, this.response, this.chain); - assertThat(this.chain.getRequest(), equalTo((ServletRequest) this.request)); - assertThat(((HttpServletResponseWrapper) this.chain.getResponse()).getResponse(), - equalTo((ServletResponse) this.response)); - assertTrue(this.response.isCommitted()); + assertThat(this.chain.getRequest()).isEqualTo(this.request); + assertThat(((HttpServletResponseWrapper) this.chain.getResponse()).getResponse()) + .isEqualTo(this.response); + assertThat(this.response.isCommitted()).isTrue(); } @Test @@ -377,20 +369,20 @@ public class ErrorPageFilterTests { } }; this.filter.doFilter(this.request, this.response, this.chain); - assertThat(this.chain.getRequest(), equalTo((ServletRequest) this.request)); - assertThat(((HttpServletResponseWrapper) this.chain.getResponse()).getResponse(), - equalTo((ServletResponse) this.response)); - assertTrue(this.response.isCommitted()); + assertThat(this.chain.getRequest()).isEqualTo(this.request); + assertThat(((HttpServletResponseWrapper) this.chain.getResponse()).getResponse()) + .isEqualTo(this.response); + assertThat(this.response.isCommitted()).isTrue(); } @Test public void responseIsNotCommittedDuringAsyncDispatch() throws Exception { setUpAsyncDispatch(); this.filter.doFilter(this.request, this.response, this.chain); - assertThat(this.chain.getRequest(), equalTo((ServletRequest) this.request)); - assertThat(((HttpServletResponseWrapper) this.chain.getResponse()).getResponse(), - equalTo((ServletResponse) this.response)); - assertFalse(this.response.isCommitted()); + assertThat(this.chain.getRequest()).isEqualTo(this.request); + assertThat(((HttpServletResponseWrapper) this.chain.getResponse()).getResponse()) + .isEqualTo(this.response); + assertThat(this.response.isCommitted()).isFalse(); } @Test @@ -407,10 +399,10 @@ public class ErrorPageFilterTests { } }; this.filter.doFilter(this.request, this.response, this.chain); - assertThat(this.chain.getRequest(), equalTo((ServletRequest) this.request)); - assertThat(((HttpServletResponseWrapper) this.chain.getResponse()).getResponse(), - equalTo((ServletResponse) this.response)); - assertTrue(this.response.isCommitted()); + assertThat(this.chain.getRequest()).isEqualTo(this.request); + assertThat(((HttpServletResponseWrapper) this.chain.getResponse()).getResponse()) + .isEqualTo(this.response); + assertThat(this.response.isCommitted()).isTrue(); } @Test @@ -427,10 +419,10 @@ public class ErrorPageFilterTests { } }; this.filter.doFilter(this.request, this.response, this.chain); - assertThat(this.chain.getRequest(), equalTo((ServletRequest) this.request)); - assertThat(((HttpServletResponseWrapper) this.chain.getResponse()).getResponse(), - equalTo((ServletResponse) this.response)); - assertTrue(this.response.isCommitted()); + assertThat(this.chain.getRequest()).isEqualTo(this.request); + assertThat(((HttpServletResponseWrapper) this.chain.getResponse()).getResponse()) + .isEqualTo(this.response); + assertThat(this.response.isCommitted()).isTrue(); } @Test @@ -449,15 +441,17 @@ public class ErrorPageFilterTests { this.request.setServletPath("/test"); this.filter.addErrorPages(new ErrorPage("/error")); this.chain = new MockFilterChain() { + @Override public void doFilter(ServletRequest request, ServletResponse response) throws IOException, ServletException { super.doFilter(request, response); throw new RuntimeException(); } + }; this.filter.doFilter(this.request, this.response, this.chain); - assertThat(this.output.toString(), containsString("request [/test]")); + assertThat(this.output.toString()).contains("request [/test]"); } @Test @@ -467,15 +461,17 @@ public class ErrorPageFilterTests { this.request.setPathInfo("/alpha"); this.filter.addErrorPages(new ErrorPage("/error")); this.chain = new MockFilterChain() { + @Override public void doFilter(ServletRequest request, ServletResponse response) throws IOException, ServletException { super.doFilter(request, response); throw new RuntimeException(); } + }; this.filter.doFilter(this.request, this.response, this.chain); - assertThat(this.output.toString(), containsString("request [/test/alpha]")); + assertThat(this.output.toString()).contains("request [/test/alpha]"); } @Test @@ -490,18 +486,18 @@ public class ErrorPageFilterTests { } }; this.filter.doFilter(this.request, this.response, this.chain); - assertThat(((HttpServletResponseWrapper) this.chain.getResponse()).getStatus(), - equalTo(500)); - assertThat(this.request.getAttribute(RequestDispatcher.ERROR_STATUS_CODE), - equalTo((Object) 500)); - assertThat(this.request.getAttribute(RequestDispatcher.ERROR_MESSAGE), - equalTo((Object) "BAD")); - assertThat(this.request.getAttribute(RequestDispatcher.ERROR_EXCEPTION_TYPE), - equalTo((Object) RuntimeException.class.getName())); - assertThat(this.request.getAttribute(RequestDispatcher.ERROR_REQUEST_URI), - equalTo((Object) "/test/path")); - assertTrue(this.response.isCommitted()); - assertThat(this.response.getForwardedUrl(), equalTo("/500")); + assertThat(((HttpServletResponseWrapper) this.chain.getResponse()).getStatus()) + .isEqualTo(500); + assertThat(this.request.getAttribute(RequestDispatcher.ERROR_STATUS_CODE)) + .isEqualTo(500); + assertThat(this.request.getAttribute(RequestDispatcher.ERROR_MESSAGE)) + .isEqualTo("BAD"); + assertThat(this.request.getAttribute(RequestDispatcher.ERROR_EXCEPTION_TYPE)) + .isEqualTo(RuntimeException.class.getName()); + assertThat(this.request.getAttribute(RequestDispatcher.ERROR_REQUEST_URI)) + .isEqualTo("/test/path"); + assertThat(this.response.isCommitted()).isTrue(); + assertThat(this.response.getForwardedUrl()).isEqualTo("/500"); } private void setUpAsyncDispatch() throws Exception { diff --git a/spring-boot/src/test/java/org/springframework/boot/context/web/SpringBootServletInitializerTests.java b/spring-boot/src/test/java/org/springframework/boot/context/web/SpringBootServletInitializerTests.java index 7cb85aacad..8f98ae0f80 100644 --- a/spring-boot/src/test/java/org/springframework/boot/context/web/SpringBootServletInitializerTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/context/web/SpringBootServletInitializerTests.java @@ -16,13 +16,8 @@ package org.springframework.boot.context.web; -import java.util.Collections; -import java.util.LinkedHashSet; -import java.util.Set; - import javax.servlet.ServletContext; -import org.hamcrest.Matcher; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; @@ -34,9 +29,7 @@ import org.springframework.context.annotation.Configuration; import org.springframework.mock.web.MockServletContext; import org.springframework.web.context.WebApplicationContext; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.is; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link SpringBootServletInitializer}. @@ -65,22 +58,22 @@ public class SpringBootServletInitializerTests { public void withConfigurationAnnotation() throws Exception { new WithConfigurationAnnotation() .createRootApplicationContext(this.servletContext); - assertThat(this.application.getSources(), - equalToSet(WithConfigurationAnnotation.class, ErrorPageFilter.class)); + assertThat(this.application.getSources()) + .containsOnly(WithConfigurationAnnotation.class, ErrorPageFilter.class); } @Test public void withConfiguredSource() throws Exception { new WithConfiguredSource().createRootApplicationContext(this.servletContext); - assertThat(this.application.getSources(), - equalToSet(Config.class, ErrorPageFilter.class)); + assertThat(this.application.getSources()).containsOnly(Config.class, + ErrorPageFilter.class); } @Test public void applicationBuilderCanBeCustomized() throws Exception { CustomSpringBootServletInitializer servletInitializer = new CustomSpringBootServletInitializer(); servletInitializer.createRootApplicationContext(this.servletContext); - assertThat(servletInitializer.applicationBuilder.built, equalTo(true)); + assertThat(servletInitializer.applicationBuilder.built).isTrue(); } @Test @@ -90,22 +83,15 @@ public class SpringBootServletInitializerTests { .createRootApplicationContext(this.servletContext); Class mainApplicationClass = (Class) new DirectFieldAccessor(this.application) .getPropertyValue("mainApplicationClass"); - assertThat(mainApplicationClass, - is(equalTo((Class) WithConfigurationAnnotation.class))); + assertThat(mainApplicationClass).isEqualTo(WithConfigurationAnnotation.class); } @Test public void withErrorPageFilterNotRegistered() throws Exception { new WithErrorPageFilterNotRegistered() .createRootApplicationContext(this.servletContext); - assertThat(this.application.getSources(), - equalToSet(WithErrorPageFilterNotRegistered.class)); - } - - private Matcher> equalToSet(Object... items) { - Set set = new LinkedHashSet(); - Collections.addAll(set, items); - return equalTo(set); + assertThat(this.application.getSources()) + .containsOnly(WithErrorPageFilterNotRegistered.class); } private class MockSpringBootServletInitializer extends SpringBootServletInitializer { diff --git a/spring-boot/src/test/java/org/springframework/boot/env/PropertiesPropertySourceLoaderTests.java b/spring-boot/src/test/java/org/springframework/boot/env/PropertiesPropertySourceLoaderTests.java index 6f719dfd51..440ba4ebf1 100644 --- a/spring-boot/src/test/java/org/springframework/boot/env/PropertiesPropertySourceLoaderTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/env/PropertiesPropertySourceLoaderTests.java @@ -21,8 +21,7 @@ import org.junit.Test; import org.springframework.core.env.PropertySource; import org.springframework.core.io.ClassPathResource; -import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link PropertiesPropertySourceLoader}. @@ -35,29 +34,28 @@ public class PropertiesPropertySourceLoaderTests { @Test public void getFileExtensions() throws Exception { - assertThat(this.loader.getFileExtensions(), - equalTo(new String[] { "properties", "xml" })); + assertThat(this.loader.getFileExtensions()).containsExactly("properties", "xml"); } @Test public void loadProperties() throws Exception { PropertySource source = this.loader.load("test.properties", new ClassPathResource("test-properties.properties", getClass()), null); - assertThat(source.getProperty("test"), equalTo((Object) "properties")); + assertThat(source.getProperty("test")).isEqualTo("properties"); } @Test public void loadPropertiesEncoded() throws Exception { PropertySource source = this.loader.load("encoded.properties", new ClassPathResource("test-encoded.properties", getClass()), null); - assertThat(source.getProperty("test"), equalTo((Object) "prकperties")); + assertThat(source.getProperty("test")).isEqualTo("prकperties"); } @Test public void loadXml() throws Exception { PropertySource source = this.loader.load("test.xml", new ClassPathResource("test-xml.xml", getClass()), null); - assertThat(source.getProperty("test"), equalTo((Object) "xml")); + assertThat(source.getProperty("test")).isEqualTo("xml"); } } diff --git a/spring-boot/src/test/java/org/springframework/boot/env/PropertySourcesLoaderTests.java b/spring-boot/src/test/java/org/springframework/boot/env/PropertySourcesLoaderTests.java index 0baa7ee0b6..de6e732b66 100644 --- a/spring-boot/src/test/java/org/springframework/boot/env/PropertySourcesLoaderTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/env/PropertySourcesLoaderTests.java @@ -18,7 +18,7 @@ package org.springframework.boot.env; import org.junit.Test; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link PropertySourcesLoader}. @@ -31,10 +31,8 @@ public class PropertySourcesLoaderTests { @Test public void fileExtensions() { - assertTrue(this.loader.getAllFileExtensions().contains("yml")); - assertTrue(this.loader.getAllFileExtensions().contains("yaml")); - assertTrue(this.loader.getAllFileExtensions().contains("properties")); - assertTrue(this.loader.getAllFileExtensions().contains("xml")); + assertThat(this.loader.getAllFileExtensions()).containsOnly("yml", "yaml", + "properties", "xml"); } } diff --git a/spring-boot/src/test/java/org/springframework/boot/env/SpringApplicationJsonEnvironmentPostProcessorTests.java b/spring-boot/src/test/java/org/springframework/boot/env/SpringApplicationJsonEnvironmentPostProcessorTests.java index f58da06126..281b740777 100644 --- a/spring-boot/src/test/java/org/springframework/boot/env/SpringApplicationJsonEnvironmentPostProcessorTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/env/SpringApplicationJsonEnvironmentPostProcessorTests.java @@ -22,7 +22,7 @@ import org.springframework.boot.test.EnvironmentTestUtils; import org.springframework.core.env.ConfigurableEnvironment; import org.springframework.core.env.StandardEnvironment; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link SpringApplicationJsonEnvironmentPostProcessor}. @@ -37,82 +37,83 @@ public class SpringApplicationJsonEnvironmentPostProcessorTests { @Test public void error() { - assertEquals("", this.environment.resolvePlaceholders("${foo:}")); + assertThat(this.environment.resolvePlaceholders("${foo:}")).isEmpty(); EnvironmentTestUtils.addEnvironment(this.environment, "spring.application.json=foo:bar"); this.processor.postProcessEnvironment(this.environment, null); - assertEquals("", this.environment.resolvePlaceholders("${foo:}")); + assertThat(this.environment.resolvePlaceholders("${foo:}")).isEmpty(); } @Test public void missing() { - assertEquals("", this.environment.resolvePlaceholders("${foo:}")); + assertThat(this.environment.resolvePlaceholders("${foo:}")).isEmpty(); this.processor.postProcessEnvironment(this.environment, null); - assertEquals("", this.environment.resolvePlaceholders("${foo:}")); + assertThat(this.environment.resolvePlaceholders("${foo:}")).isEmpty(); } @Test public void empty() { - assertEquals("", this.environment.resolvePlaceholders("${foo:}")); + assertThat(this.environment.resolvePlaceholders("${foo:}")).isEmpty(); EnvironmentTestUtils.addEnvironment(this.environment, "spring.application.json={}"); this.processor.postProcessEnvironment(this.environment, null); - assertEquals("", this.environment.resolvePlaceholders("${foo:}")); + assertThat(this.environment.resolvePlaceholders("${foo:}")).isEmpty(); } @Test public void periodSeparated() { - assertEquals("", this.environment.resolvePlaceholders("${foo:}")); + assertThat(this.environment.resolvePlaceholders("${foo:}")).isEmpty(); EnvironmentTestUtils.addEnvironment(this.environment, "spring.application.json={\"foo\":\"bar\"}"); this.processor.postProcessEnvironment(this.environment, null); - assertEquals("bar", this.environment.resolvePlaceholders("${foo:}")); + assertThat(this.environment.resolvePlaceholders("${foo:}")).isEqualTo("bar"); } @Test public void envVar() { - assertEquals("", this.environment.resolvePlaceholders("${foo:}")); + assertThat(this.environment.resolvePlaceholders("${foo:}")).isEmpty(); EnvironmentTestUtils.addEnvironment(this.environment, "SPRING_APPLICATION_JSON={\"foo\":\"bar\"}"); this.processor.postProcessEnvironment(this.environment, null); - assertEquals("bar", this.environment.resolvePlaceholders("${foo:}")); + assertThat(this.environment.resolvePlaceholders("${foo:}")).isEqualTo("bar"); } @Test public void nested() { - assertEquals("", this.environment.resolvePlaceholders("${foo:}")); + assertThat(this.environment.resolvePlaceholders("${foo:}")).isEmpty(); EnvironmentTestUtils.addEnvironment(this.environment, "SPRING_APPLICATION_JSON={\"foo\":{\"bar\":\"spam\",\"rab\":\"maps\"}}"); this.processor.postProcessEnvironment(this.environment, null); - assertEquals("spam", this.environment.resolvePlaceholders("${foo.bar:}")); - assertEquals("maps", this.environment.resolvePlaceholders("${foo.rab:}")); + assertThat(this.environment.resolvePlaceholders("${foo.bar:}")).isEqualTo("spam"); + assertThat(this.environment.resolvePlaceholders("${foo.rab:}")).isEqualTo("maps"); } @Test public void prefixed() { - assertEquals("", this.environment.resolvePlaceholders("${foo:}")); + assertThat(this.environment.resolvePlaceholders("${foo:}")).isEmpty(); EnvironmentTestUtils.addEnvironment(this.environment, "SPRING_APPLICATION_JSON={\"foo.bar\":\"spam\"}"); this.processor.postProcessEnvironment(this.environment, null); - assertEquals("spam", this.environment.resolvePlaceholders("${foo.bar:}")); + assertThat(this.environment.resolvePlaceholders("${foo.bar:}")).isEqualTo("spam"); } @Test public void list() { - assertEquals("", this.environment.resolvePlaceholders("${foo[1]:}")); + assertThat(this.environment.resolvePlaceholders("${foo[1]:}")).isEmpty(); EnvironmentTestUtils.addEnvironment(this.environment, "SPRING_APPLICATION_JSON={\"foo\":[\"bar\",\"spam\"]}"); this.processor.postProcessEnvironment(this.environment, null); - assertEquals("spam", this.environment.resolvePlaceholders("${foo[1]:}")); + assertThat(this.environment.resolvePlaceholders("${foo[1]:}")).isEqualTo("spam"); } @Test public void listOfObject() { - assertEquals("", this.environment.resolvePlaceholders("${foo[0].bar:}")); + assertThat(this.environment.resolvePlaceholders("${foo[0].bar:}")).isEmpty(); EnvironmentTestUtils.addEnvironment(this.environment, "SPRING_APPLICATION_JSON={\"foo\":[{\"bar\":\"spam\"}]}"); this.processor.postProcessEnvironment(this.environment, null); - assertEquals("spam", this.environment.resolvePlaceholders("${foo[0].bar:}")); + assertThat(this.environment.resolvePlaceholders("${foo[0].bar:}")) + .isEqualTo("spam"); } } diff --git a/spring-boot/src/test/java/org/springframework/boot/env/YamlPropertySourceLoaderTests.java b/spring-boot/src/test/java/org/springframework/boot/env/YamlPropertySourceLoaderTests.java index ea62164439..930c83d742 100644 --- a/spring-boot/src/test/java/org/springframework/boot/env/YamlPropertySourceLoaderTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/env/YamlPropertySourceLoaderTests.java @@ -25,10 +25,7 @@ import org.springframework.core.env.EnumerablePropertySource; import org.springframework.core.env.PropertySource; import org.springframework.core.io.ByteArrayResource; -import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link YamlPropertySourceLoader}. @@ -46,8 +43,8 @@ public class YamlPropertySourceLoaderTests { ByteArrayResource resource = new ByteArrayResource( "foo:\n bar: spam".getBytes()); PropertySource source = this.loader.load("resource", resource, null); - assertNotNull(source); - assertEquals("spam", source.getProperty("foo.bar")); + assertThat(source).isNotNull(); + assertThat(source.getProperty("foo.bar")).isEqualTo("spam"); } @Test @@ -61,8 +58,9 @@ public class YamlPropertySourceLoaderTests { ByteArrayResource resource = new ByteArrayResource(yaml.toString().getBytes()); EnumerablePropertySource source = (EnumerablePropertySource) this.loader .load("resource", resource, null); - assertNotNull(source); - assertThat(source.getPropertyNames(), equalTo(expected.toArray(new String[] {}))); + assertThat(source).isNotNull(); + assertThat(source.getPropertyNames()) + .isEqualTo(expected.toArray(new String[] {})); } @Test @@ -73,17 +71,17 @@ public class YamlPropertySourceLoaderTests { yaml.append("foo:\n baz: wham\n"); ByteArrayResource resource = new ByteArrayResource(yaml.toString().getBytes()); PropertySource source = this.loader.load("resource", resource, null); - assertNotNull(source); - assertEquals("spam", source.getProperty("foo.bar")); - assertEquals("wham", source.getProperty("foo.baz")); + assertThat(source).isNotNull(); + assertThat(source.getProperty("foo.bar")).isEqualTo("spam"); + assertThat(source.getProperty("foo.baz")).isEqualTo("wham"); } @Test public void timestampLikeItemsDoNotBecomeDates() throws Exception { ByteArrayResource resource = new ByteArrayResource("foo: 2015-01-28".getBytes()); PropertySource source = this.loader.load("resource", resource, null); - assertNotNull(source); - assertEquals("2015-01-28", source.getProperty("foo")); + assertThat(source).isNotNull(); + assertThat(source.getProperty("foo")).isEqualTo("2015-01-28"); } } diff --git a/spring-boot/src/test/java/org/springframework/boot/json/AbstractJsonParserTests.java b/spring-boot/src/test/java/org/springframework/boot/json/AbstractJsonParserTests.java index d9d3494b05..fe7852f308 100644 --- a/spring-boot/src/test/java/org/springframework/boot/json/AbstractJsonParserTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/json/AbstractJsonParserTests.java @@ -23,7 +23,7 @@ import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * Base for {@link JsonParser} tests. @@ -43,36 +43,36 @@ public abstract class AbstractJsonParserTests { @Test public void simpleMap() { Map map = this.parser.parseMap("{\"foo\":\"bar\",\"spam\":1}"); - assertEquals(2, map.size()); - assertEquals("bar", map.get("foo")); - assertEquals(1L, ((Number) map.get("spam")).longValue()); + assertThat(map).hasSize(2); + assertThat(map.get("foo")).isEqualTo("bar"); + assertThat(((Number) map.get("spam")).longValue()).isEqualTo(1L); } @Test public void doubleValue() { Map map = this.parser.parseMap("{\"foo\":\"bar\",\"spam\":1.23}"); - assertEquals(2, map.size()); - assertEquals("bar", map.get("foo")); - assertEquals(1.23d, map.get("spam")); + assertThat(map).hasSize(2); + assertThat(map.get("foo")).isEqualTo("bar"); + assertThat(map.get("spam")).isEqualTo(1.23d); } @Test public void emptyMap() { Map map = this.parser.parseMap("{}"); - assertEquals(0, map.size()); + assertThat(map).isEmpty(); } @Test public void simpleList() { List list = this.parser.parseList("[\"foo\",\"bar\",1]"); - assertEquals(3, list.size()); - assertEquals("bar", list.get(1)); + assertThat(list).hasSize(3); + assertThat(list.get(1)).isEqualTo("bar"); } @Test public void emptyList() { List list = this.parser.parseList("[]"); - assertEquals(0, list.size()); + assertThat(list).isEmpty(); } @SuppressWarnings("unchecked") @@ -80,8 +80,8 @@ public abstract class AbstractJsonParserTests { public void listOfMaps() { List list = this.parser .parseList("[{\"foo\":\"bar\",\"spam\":1},{\"foo\":\"baz\",\"spam\":2}]"); - assertEquals(2, list.size()); - assertEquals(2, ((Map) list.get(1)).size()); + assertThat(list).hasSize(2); + assertThat(((Map) list.get(1))).hasSize(2); } @SuppressWarnings("unchecked") @@ -89,8 +89,8 @@ public abstract class AbstractJsonParserTests { public void mapOfLists() { Map map = this.parser.parseMap( "{\"foo\":[{\"foo\":\"bar\",\"spam\":1},{\"foo\":\"baz\",\"spam\":2}]}"); - assertEquals(1, map.size()); - assertEquals(2, ((List) map.get("foo")).size()); + assertThat(map).hasSize(1); + assertThat(((List) map.get("foo"))).hasSize(2); } @Test @@ -132,15 +132,15 @@ public abstract class AbstractJsonParserTests { @Test public void listWithLeadingWhitespace() { List list = this.parser.parseList("\n\t[\"foo\"]"); - assertEquals(1, list.size()); - assertEquals("foo", list.get(0)); + assertThat(list).hasSize(1); + assertThat(list.get(0)).isEqualTo("foo"); } @Test public void mapWithLeadingWhitespace() { Map map = this.parser.parseMap("\n\t{\"foo\":\"bar\"}"); - assertEquals(1, map.size()); - assertEquals("bar", map.get("foo")); + assertThat(map).hasSize(1); + assertThat(map.get("foo")).isEqualTo("bar"); } @Test diff --git a/spring-boot/src/test/java/org/springframework/boot/jta/atomikos/AtomikosConnectionFactoryBeanTests.java b/spring-boot/src/test/java/org/springframework/boot/jta/atomikos/AtomikosConnectionFactoryBeanTests.java index a6325b2d0c..3a917a7b68 100644 --- a/spring-boot/src/test/java/org/springframework/boot/jta/atomikos/AtomikosConnectionFactoryBeanTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/jta/atomikos/AtomikosConnectionFactoryBeanTests.java @@ -20,8 +20,7 @@ import javax.jms.JMSException; import org.junit.Test; -import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.never; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.verify; @@ -39,7 +38,7 @@ public class AtomikosConnectionFactoryBeanTests { new MockAtomikosConnectionFactoryBean()); bean.setBeanName("bean"); bean.afterPropertiesSet(); - assertThat(bean.getUniqueResourceName(), equalTo("bean")); + assertThat(bean.getUniqueResourceName()).isEqualTo("bean"); verify(bean).init(); verify(bean, never()).close(); bean.destroy(); diff --git a/spring-boot/src/test/java/org/springframework/boot/jta/atomikos/AtomikosDataSourceBeanTests.java b/spring-boot/src/test/java/org/springframework/boot/jta/atomikos/AtomikosDataSourceBeanTests.java index 228f0a0cc1..47e057f2d3 100644 --- a/spring-boot/src/test/java/org/springframework/boot/jta/atomikos/AtomikosDataSourceBeanTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/jta/atomikos/AtomikosDataSourceBeanTests.java @@ -19,8 +19,7 @@ package org.springframework.boot.jta.atomikos; import com.atomikos.jdbc.AtomikosSQLException; import org.junit.Test; -import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.never; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.verify; @@ -37,7 +36,7 @@ public class AtomikosDataSourceBeanTests { MockAtomikosDataSourceBean bean = spy(new MockAtomikosDataSourceBean()); bean.setBeanName("bean"); bean.afterPropertiesSet(); - assertThat(bean.getUniqueResourceName(), equalTo("bean")); + assertThat(bean.getUniqueResourceName()).isEqualTo("bean"); verify(bean).init(); verify(bean, never()).close(); bean.destroy(); diff --git a/spring-boot/src/test/java/org/springframework/boot/jta/atomikos/AtomikosDependsOnBeanFactoryPostProcessorTests.java b/spring-boot/src/test/java/org/springframework/boot/jta/atomikos/AtomikosDependsOnBeanFactoryPostProcessorTests.java index 1578de19f5..f24cb61c4e 100644 --- a/spring-boot/src/test/java/org/springframework/boot/jta/atomikos/AtomikosDependsOnBeanFactoryPostProcessorTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/jta/atomikos/AtomikosDependsOnBeanFactoryPostProcessorTests.java @@ -31,9 +31,7 @@ import org.springframework.context.annotation.AnnotationConfigApplicationContext import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; -import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; /** @@ -58,12 +56,12 @@ public class AtomikosDependsOnBeanFactoryPostProcessorTests { private void assertDependsOn(String bean, String... expected) { BeanDefinition definition = this.context.getBeanDefinition(bean); if (definition.getDependsOn() == null) { - assertTrue("No dependsOn expected for " + bean, expected.length == 0); + assertThat(expected).as("No dependsOn expected for " + bean).isEmpty(); return; } HashSet dependsOn = new HashSet( Arrays.asList(definition.getDependsOn())); - assertThat(dependsOn, equalTo(new HashSet(Arrays.asList(expected)))); + assertThat(dependsOn).isEqualTo(new HashSet(Arrays.asList(expected))); } @Configuration diff --git a/spring-boot/src/test/java/org/springframework/boot/jta/atomikos/AtomikosPropertiesTests.java b/spring-boot/src/test/java/org/springframework/boot/jta/atomikos/AtomikosPropertiesTests.java index c1d4fef224..3500d798df 100644 --- a/spring-boot/src/test/java/org/springframework/boot/jta/atomikos/AtomikosPropertiesTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/jta/atomikos/AtomikosPropertiesTests.java @@ -18,8 +18,7 @@ package org.springframework.boot.jta.atomikos; import org.junit.Test; -import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for ;@link AtomikosProperties}. @@ -50,7 +49,7 @@ public class AtomikosPropertiesTests { this.properties.setConsoleFileLimit(6); this.properties.setThreadedTwoPhaseCommit(true); - assertThat(this.properties.asProperties().size(), equalTo(17)); + assertThat(this.properties.asProperties().size()).isEqualTo(17); assertProperty("com.atomikos.icatch.service", "service"); assertProperty("com.atomikos.icatch.max_timeout", "1"); assertProperty("com.atomikos.icatch.default_jta_timeout", "2"); @@ -71,7 +70,7 @@ public class AtomikosPropertiesTests { } private void assertProperty(String key, String value) { - assertThat(this.properties.asProperties().getProperty(key), equalTo(value)); + assertThat(this.properties.asProperties().getProperty(key)).isEqualTo(value); } } diff --git a/spring-boot/src/test/java/org/springframework/boot/jta/atomikos/AtomikosXAConnectionFactoryWrapperTests.java b/spring-boot/src/test/java/org/springframework/boot/jta/atomikos/AtomikosXAConnectionFactoryWrapperTests.java index 3745522fd6..896532e2f5 100644 --- a/spring-boot/src/test/java/org/springframework/boot/jta/atomikos/AtomikosXAConnectionFactoryWrapperTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/jta/atomikos/AtomikosXAConnectionFactoryWrapperTests.java @@ -21,9 +21,7 @@ import javax.jms.XAConnectionFactory; import org.junit.Test; -import static org.hamcrest.Matchers.instanceOf; -import static org.hamcrest.Matchers.sameInstance; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; /** @@ -38,9 +36,9 @@ public class AtomikosXAConnectionFactoryWrapperTests { XAConnectionFactory connectionFactory = mock(XAConnectionFactory.class); AtomikosXAConnectionFactoryWrapper wrapper = new AtomikosXAConnectionFactoryWrapper(); ConnectionFactory wrapped = wrapper.wrapConnectionFactory(connectionFactory); - assertThat(wrapped, instanceOf(AtomikosConnectionFactoryBean.class)); - assertThat(((AtomikosConnectionFactoryBean) wrapped).getXaConnectionFactory(), - sameInstance(connectionFactory)); + assertThat(wrapped).isInstanceOf(AtomikosConnectionFactoryBean.class); + assertThat(((AtomikosConnectionFactoryBean) wrapped).getXaConnectionFactory()) + .isSameAs(connectionFactory); } } diff --git a/spring-boot/src/test/java/org/springframework/boot/jta/atomikos/AtomikosXADataSourceWrapperTests.java b/spring-boot/src/test/java/org/springframework/boot/jta/atomikos/AtomikosXADataSourceWrapperTests.java index c2d6e56a5f..20ec3391f2 100644 --- a/spring-boot/src/test/java/org/springframework/boot/jta/atomikos/AtomikosXADataSourceWrapperTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/jta/atomikos/AtomikosXADataSourceWrapperTests.java @@ -21,9 +21,7 @@ import javax.sql.XADataSource; import org.junit.Test; -import static org.hamcrest.Matchers.instanceOf; -import static org.hamcrest.Matchers.sameInstance; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; /** @@ -38,9 +36,9 @@ public class AtomikosXADataSourceWrapperTests { XADataSource dataSource = mock(XADataSource.class); AtomikosXADataSourceWrapper wrapper = new AtomikosXADataSourceWrapper(); DataSource wrapped = wrapper.wrapDataSource(dataSource); - assertThat(wrapped, instanceOf(AtomikosDataSourceBean.class)); - assertThat(((AtomikosDataSourceBean) wrapped).getXaDataSource(), - sameInstance(dataSource)); + assertThat(wrapped).isInstanceOf(AtomikosDataSourceBean.class); + assertThat(((AtomikosDataSourceBean) wrapped).getXaDataSource()) + .isSameAs(dataSource); } } diff --git a/spring-boot/src/test/java/org/springframework/boot/jta/bitronix/BitronixXAConnectionFactoryWrapperTests.java b/spring-boot/src/test/java/org/springframework/boot/jta/bitronix/BitronixXAConnectionFactoryWrapperTests.java index fca543971b..a0ab8c20aa 100644 --- a/spring-boot/src/test/java/org/springframework/boot/jta/bitronix/BitronixXAConnectionFactoryWrapperTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/jta/bitronix/BitronixXAConnectionFactoryWrapperTests.java @@ -21,9 +21,7 @@ import javax.jms.XAConnectionFactory; import org.junit.Test; -import static org.hamcrest.Matchers.instanceOf; -import static org.hamcrest.Matchers.sameInstance; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; /** @@ -38,9 +36,9 @@ public class BitronixXAConnectionFactoryWrapperTests { XAConnectionFactory connectionFactory = mock(XAConnectionFactory.class); BitronixXAConnectionFactoryWrapper wrapper = new BitronixXAConnectionFactoryWrapper(); ConnectionFactory wrapped = wrapper.wrapConnectionFactory(connectionFactory); - assertThat(wrapped, instanceOf(PoolingConnectionFactoryBean.class)); - assertThat(((PoolingConnectionFactoryBean) wrapped).getConnectionFactory(), - sameInstance(connectionFactory)); + assertThat(wrapped).isInstanceOf(PoolingConnectionFactoryBean.class); + assertThat(((PoolingConnectionFactoryBean) wrapped).getConnectionFactory()) + .isSameAs(connectionFactory); } } diff --git a/spring-boot/src/test/java/org/springframework/boot/jta/bitronix/BitronixXADataSourceWrapperTests.java b/spring-boot/src/test/java/org/springframework/boot/jta/bitronix/BitronixXADataSourceWrapperTests.java index abea432440..bae96ab367 100644 --- a/spring-boot/src/test/java/org/springframework/boot/jta/bitronix/BitronixXADataSourceWrapperTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/jta/bitronix/BitronixXADataSourceWrapperTests.java @@ -21,9 +21,7 @@ import javax.sql.XADataSource; import org.junit.Test; -import static org.hamcrest.Matchers.instanceOf; -import static org.hamcrest.Matchers.sameInstance; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; /** @@ -38,9 +36,9 @@ public class BitronixXADataSourceWrapperTests { XADataSource dataSource = mock(XADataSource.class); BitronixXADataSourceWrapper wrapper = new BitronixXADataSourceWrapper(); DataSource wrapped = wrapper.wrapDataSource(dataSource); - assertThat(wrapped, instanceOf(PoolingDataSourceBean.class)); - assertThat(((PoolingDataSourceBean) wrapped).getDataSource(), - sameInstance(dataSource)); + assertThat(wrapped).isInstanceOf(PoolingDataSourceBean.class); + assertThat(((PoolingDataSourceBean) wrapped).getDataSource()) + .isSameAs(dataSource); } } diff --git a/spring-boot/src/test/java/org/springframework/boot/jta/bitronix/PoolingConnectionFactoryBeanTests.java b/spring-boot/src/test/java/org/springframework/boot/jta/bitronix/PoolingConnectionFactoryBeanTests.java index 595efbb3d1..4897d954fd 100644 --- a/spring-boot/src/test/java/org/springframework/boot/jta/bitronix/PoolingConnectionFactoryBeanTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/jta/bitronix/PoolingConnectionFactoryBeanTests.java @@ -20,8 +20,7 @@ import javax.jms.XAConnectionFactory; import org.junit.Test; -import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; @@ -42,17 +41,17 @@ public class PoolingConnectionFactoryBeanTests { @Test public void sensibleDefaults() throws Exception { - assertThat(this.bean.getMaxPoolSize(), equalTo(10)); - assertThat(this.bean.getTestConnections(), equalTo(true)); - assertThat(this.bean.getAutomaticEnlistingEnabled(), equalTo(true)); - assertThat(this.bean.getAllowLocalTransactions(), equalTo(true)); + assertThat(this.bean.getMaxPoolSize()).isEqualTo(10); + assertThat(this.bean.getTestConnections()).isTrue(); + assertThat(this.bean.getAutomaticEnlistingEnabled()).isTrue(); + assertThat(this.bean.getAllowLocalTransactions()).isTrue(); } @Test public void setsUniqueNameIfNull() throws Exception { this.bean.setBeanName("beanName"); this.bean.afterPropertiesSet(); - assertThat(this.bean.getUniqueName(), equalTo("beanName")); + assertThat(this.bean.getUniqueName()).isEqualTo("beanName"); } @Test @@ -60,7 +59,7 @@ public class PoolingConnectionFactoryBeanTests { this.bean.setBeanName("beanName"); this.bean.setUniqueName("un"); this.bean.afterPropertiesSet(); - assertThat(this.bean.getUniqueName(), equalTo("un")); + assertThat(this.bean.getUniqueName()).isEqualTo("un"); } @Test diff --git a/spring-boot/src/test/java/org/springframework/boot/jta/bitronix/PoolingDataSourceBeanTests.java b/spring-boot/src/test/java/org/springframework/boot/jta/bitronix/PoolingDataSourceBeanTests.java index 20f02b83c9..7e880f109d 100644 --- a/spring-boot/src/test/java/org/springframework/boot/jta/bitronix/PoolingDataSourceBeanTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/jta/bitronix/PoolingDataSourceBeanTests.java @@ -23,8 +23,7 @@ import javax.sql.XADataSource; import org.junit.Test; -import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; @@ -40,16 +39,16 @@ public class PoolingDataSourceBeanTests { @Test public void sensibleDefaults() throws Exception { - assertThat(this.bean.getMaxPoolSize(), equalTo(10)); - assertThat(this.bean.getAutomaticEnlistingEnabled(), equalTo(true)); - assertThat(this.bean.isEnableJdbc4ConnectionTest(), equalTo(true)); + assertThat(this.bean.getMaxPoolSize()).isEqualTo(10); + assertThat(this.bean.getAutomaticEnlistingEnabled()).isTrue(); + assertThat(this.bean.isEnableJdbc4ConnectionTest()).isTrue(); } @Test public void setsUniqueNameIfNull() throws Exception { this.bean.setBeanName("beanName"); this.bean.afterPropertiesSet(); - assertThat(this.bean.getUniqueName(), equalTo("beanName")); + assertThat(this.bean.getUniqueName()).isEqualTo("beanName"); } @Test @@ -57,7 +56,7 @@ public class PoolingDataSourceBeanTests { this.bean.setBeanName("beanName"); this.bean.setUniqueName("un"); this.bean.afterPropertiesSet(); - assertThat(this.bean.getUniqueName(), equalTo("un")); + assertThat(this.bean.getUniqueName()).isEqualTo("un"); } @Test diff --git a/spring-boot/src/test/java/org/springframework/boot/liquibase/LiquibaseServiceLocatorApplicationListenerTests.java b/spring-boot/src/test/java/org/springframework/boot/liquibase/LiquibaseServiceLocatorApplicationListenerTests.java index deb1a550e0..8f411257bf 100644 --- a/spring-boot/src/test/java/org/springframework/boot/liquibase/LiquibaseServiceLocatorApplicationListenerTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/liquibase/LiquibaseServiceLocatorApplicationListenerTests.java @@ -27,8 +27,7 @@ import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.annotation.Configuration; import org.springframework.util.ReflectionUtils; -import static org.hamcrest.Matchers.instanceOf; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link LiquibaseServiceLocatorApplicationListener}. @@ -55,7 +54,7 @@ public class LiquibaseServiceLocatorApplicationListenerTests { Field field = ReflectionUtils.findField(ServiceLocator.class, "classResolver"); field.setAccessible(true); Object resolver = field.get(instance); - assertThat(resolver, instanceOf(SpringPackageScanClassResolver.class)); + assertThat(resolver).isInstanceOf(SpringPackageScanClassResolver.class); } @Configuration diff --git a/spring-boot/src/test/java/org/springframework/boot/liquibase/SpringPackageScanClassResolverTests.java b/spring-boot/src/test/java/org/springframework/boot/liquibase/SpringPackageScanClassResolverTests.java index 47926394ac..6532683275 100644 --- a/spring-boot/src/test/java/org/springframework/boot/liquibase/SpringPackageScanClassResolverTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/liquibase/SpringPackageScanClassResolverTests.java @@ -22,8 +22,7 @@ import liquibase.logging.Logger; import org.apache.commons.logging.LogFactory; import org.junit.Test; -import static org.hamcrest.Matchers.greaterThan; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for SpringPackageScanClassResolver. @@ -39,7 +38,7 @@ public class SpringPackageScanClassResolverTests { resolver.addClassLoader(getClass().getClassLoader()); Set> implementations = resolver.findImplementations(Logger.class, "liquibase.logging.core"); - assertThat(implementations.size(), greaterThan(0)); + assertThat(implementations).isNotEmpty(); } } diff --git a/spring-boot/src/test/java/org/springframework/boot/logging/DeferredLogTests.java b/spring-boot/src/test/java/org/springframework/boot/logging/DeferredLogTests.java index cafabf7281..d14b1b0552 100644 --- a/spring-boot/src/test/java/org/springframework/boot/logging/DeferredLogTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/logging/DeferredLogTests.java @@ -19,8 +19,7 @@ package org.springframework.boot.logging; import org.apache.commons.logging.Log; import org.junit.Test; -import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; @@ -43,32 +42,32 @@ public class DeferredLogTests { @Test public void isTraceEnabled() throws Exception { - assertThat(this.deferredLog.isTraceEnabled(), equalTo(true)); + assertThat(this.deferredLog.isTraceEnabled()).isTrue(); } @Test public void isDebugEnabled() throws Exception { - assertThat(this.deferredLog.isDebugEnabled(), equalTo(true)); + assertThat(this.deferredLog.isDebugEnabled()).isTrue(); } @Test public void isInfoEnabled() throws Exception { - assertThat(this.deferredLog.isInfoEnabled(), equalTo(true)); + assertThat(this.deferredLog.isInfoEnabled()).isTrue(); } @Test public void isWarnEnabled() throws Exception { - assertThat(this.deferredLog.isWarnEnabled(), equalTo(true)); + assertThat(this.deferredLog.isWarnEnabled()).isTrue(); } @Test public void isErrorEnabled() throws Exception { - assertThat(this.deferredLog.isErrorEnabled(), equalTo(true)); + assertThat(this.deferredLog.isErrorEnabled()).isTrue(); } @Test public void isFatalEnabled() throws Exception { - assertThat(this.deferredLog.isFatalEnabled(), equalTo(true)); + assertThat(this.deferredLog.isFatalEnabled()).isTrue(); } @Test diff --git a/spring-boot/src/test/java/org/springframework/boot/logging/LogFileTests.java b/spring-boot/src/test/java/org/springframework/boot/logging/LogFileTests.java index 309dc5fba8..4a67528804 100644 --- a/spring-boot/src/test/java/org/springframework/boot/logging/LogFileTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/logging/LogFileTests.java @@ -28,9 +28,7 @@ import org.springframework.core.env.PropertyResolver; import org.springframework.core.env.PropertySource; import org.springframework.core.env.PropertySourcesPropertyResolver; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.nullValue; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link LogFile}. @@ -43,7 +41,7 @@ public class LogFileTests { public void noProperties() throws Exception { PropertyResolver resolver = getPropertyResolver(null, null); LogFile logFile = LogFile.get(resolver); - assertThat(logFile, nullValue()); + assertThat(logFile).isNull(); } @Test @@ -52,9 +50,9 @@ public class LogFileTests { LogFile logFile = LogFile.get(resolver); Properties properties = new Properties(); logFile.applyTo(properties); - assertThat(logFile.toString(), equalTo("log.file")); - assertThat(properties.getProperty("LOG_FILE"), equalTo("log.file")); - assertThat(properties.getProperty("LOG_PATH"), nullValue()); + assertThat(logFile.toString()).isEqualTo("log.file"); + assertThat(properties.getProperty("LOG_FILE")).isEqualTo("log.file"); + assertThat(properties.getProperty("LOG_PATH")).isNull(); } @Test @@ -63,9 +61,9 @@ public class LogFileTests { LogFile logFile = LogFile.get(resolver); Properties properties = new Properties(); logFile.applyTo(properties); - assertThat(logFile.toString(), equalTo("logpath/spring.log")); - assertThat(properties.getProperty("LOG_FILE"), equalTo("logpath/spring.log")); - assertThat(properties.getProperty("LOG_PATH"), equalTo("logpath")); + assertThat(logFile.toString()).isEqualTo("logpath/spring.log"); + assertThat(properties.getProperty("LOG_FILE")).isEqualTo("logpath/spring.log"); + assertThat(properties.getProperty("LOG_PATH")).isEqualTo("logpath"); } @Test @@ -74,9 +72,9 @@ public class LogFileTests { LogFile logFile = LogFile.get(resolver); Properties properties = new Properties(); logFile.applyTo(properties); - assertThat(logFile.toString(), equalTo("log.file")); - assertThat(properties.getProperty("LOG_FILE"), equalTo("log.file")); - assertThat(properties.getProperty("LOG_PATH"), equalTo("logpath")); + assertThat(logFile.toString()).isEqualTo("log.file"); + assertThat(properties.getProperty("LOG_FILE")).isEqualTo("log.file"); + assertThat(properties.getProperty("LOG_PATH")).isEqualTo("logpath"); } private PropertyResolver getPropertyResolver(String file, String path) { diff --git a/spring-boot/src/test/java/org/springframework/boot/logging/LoggingApplicationListenerIntegrationTests.java b/spring-boot/src/test/java/org/springframework/boot/logging/LoggingApplicationListenerIntegrationTests.java index 6bba334ffb..5830bd47ac 100644 --- a/spring-boot/src/test/java/org/springframework/boot/logging/LoggingApplicationListenerIntegrationTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/logging/LoggingApplicationListenerIntegrationTests.java @@ -23,7 +23,7 @@ import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.stereotype.Component; -import static org.junit.Assert.assertNotNull; +import static org.assertj.core.api.Assertions.assertThat; /** * Integration tests for {@link LoggingApplicationListener}. @@ -38,7 +38,7 @@ public class LoggingApplicationListenerIntegrationTests { SampleService.class).web(false).run(); try { SampleService service = context.getBean(SampleService.class); - assertNotNull(service.loggingSystem); + assertThat(service.loggingSystem).isNotNull(); } finally { context.close(); diff --git a/spring-boot/src/test/java/org/springframework/boot/logging/LoggingApplicationListenerTests.java b/spring-boot/src/test/java/org/springframework/boot/logging/LoggingApplicationListenerTests.java index 51ec9ceb85..ab58b7e9dc 100644 --- a/spring-boot/src/test/java/org/springframework/boot/logging/LoggingApplicationListenerTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/logging/LoggingApplicationListenerTests.java @@ -44,13 +44,9 @@ import org.springframework.context.event.ContextClosedEvent; import org.springframework.context.support.GenericApplicationContext; import org.springframework.test.util.ReflectionTestUtils; +import static org.assertj.core.api.Assertions.assertThat; import static org.hamcrest.Matchers.containsString; -import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.not; -import static org.hamcrest.Matchers.nullValue; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; /** * Tests for {@link LoggingApplicationListener}. @@ -122,7 +118,7 @@ public class LoggingApplicationListenerTests { this.outputCapture.expect(not(containsString("???"))); this.outputCapture.expect(containsString("[junit-")); this.logger.info("Hello world", new RuntimeException("Expected")); - assertFalse(new File(tmpDir() + "/spring.log").exists()); + assertThat(new File(tmpDir() + "/spring.log").exists()).isFalse(); } @Test @@ -133,11 +129,8 @@ public class LoggingApplicationListenerTests { this.context.getClassLoader()); this.logger.info("Hello world"); String output = this.outputCapture.toString().trim(); - assertTrue("Wrong output:\n" + output, output.contains("Hello world")); - assertFalse("Wrong output:\n" + output, output.contains("???")); - assertTrue("Wrong output:\n" + output, - output.startsWith("LOG_FILE_IS_UNDEFINED")); - assertTrue("Wrong output:\n" + output, output.endsWith("BOOTBOOT")); + assertThat(output).contains("Hello world").doesNotContain("???") + .startsWith("LOG_FILE_IS_UNDEFINED").endsWith("BOOTBOOT"); } @Test @@ -159,9 +152,8 @@ public class LoggingApplicationListenerTests { this.context.getClassLoader()); this.logger.info("Hello world"); String output = this.outputCapture.toString().trim(); - assertTrue("Wrong output:\n" + output, output.contains("Hello world")); - assertFalse("Wrong output:\n" + output, output.contains("???")); - assertFalse(new File(tmpDir() + "/spring.log").exists()); + assertThat(output).contains("Hello world").doesNotContain("???"); + assertThat(new File(tmpDir() + "/spring.log").exists()).isFalse(); } @Test @@ -186,18 +178,18 @@ public class LoggingApplicationListenerTests { Log logger = LogFactory.getLog(LoggingApplicationListenerTests.class); logger.info("Hello world"); String output = this.outputCapture.toString().trim(); - assertTrue("Wrong output:\n" + output, output.startsWith("target/foo.log")); + assertThat(output).startsWith("target/foo.log"); } @Test public void addLogFilePropertyWithDefault() { - assertFalse(new File("target/foo.log").exists()); + assertThat(new File("target/foo.log").exists()).isFalse(); EnvironmentTestUtils.addEnvironment(this.context, "logging.file: target/foo.log"); this.initializer.initialize(this.context.getEnvironment(), this.context.getClassLoader()); Log logger = LogFactory.getLog(LoggingApplicationListenerTests.class); logger.info("Hello world"); - assertTrue(new File("target/foo.log").exists()); + assertThat(new File("target/foo.log").exists()).isTrue(); } @Test @@ -210,8 +202,7 @@ public class LoggingApplicationListenerTests { Log logger = LogFactory.getLog(LoggingApplicationListenerTests.class); logger.info("Hello world"); String output = this.outputCapture.toString().trim(); - assertTrue("Wrong output:\n" + output, - output.startsWith("target/foo/spring.log")); + assertThat(output).startsWith("target/foo/spring.log"); } @Test @@ -221,8 +212,8 @@ public class LoggingApplicationListenerTests { this.context.getClassLoader()); this.logger.debug("testatdebug"); this.logger.trace("testattrace"); - assertThat(this.outputCapture.toString(), containsString("testatdebug")); - assertThat(this.outputCapture.toString(), not(containsString("testattrace"))); + assertThat(this.outputCapture.toString()).contains("testatdebug"); + assertThat(this.outputCapture.toString()).doesNotContain("testattrace"); } @Test @@ -232,8 +223,8 @@ public class LoggingApplicationListenerTests { this.context.getClassLoader()); this.logger.debug("testatdebug"); this.logger.trace("testattrace"); - assertThat(this.outputCapture.toString(), containsString("testatdebug")); - assertThat(this.outputCapture.toString(), containsString("testattrace")); + assertThat(this.outputCapture.toString()).contains("testatdebug"); + assertThat(this.outputCapture.toString()).contains("testattrace"); } @Test @@ -244,8 +235,8 @@ public class LoggingApplicationListenerTests { this.context.getClassLoader()); this.logger.debug("testatdebug"); this.logger.trace("testattrace"); - assertThat(this.outputCapture.toString(), containsString("testatdebug")); - assertThat(this.outputCapture.toString(), containsString("testattrace")); + assertThat(this.outputCapture.toString()).contains("testatdebug"); + assertThat(this.outputCapture.toString()).contains("testattrace"); } @Test @@ -256,8 +247,8 @@ public class LoggingApplicationListenerTests { this.context.getClassLoader()); this.logger.debug("testatdebug"); this.logger.trace("testattrace"); - assertThat(this.outputCapture.toString(), containsString("testatdebug")); - assertThat(this.outputCapture.toString(), containsString("testattrace")); + assertThat(this.outputCapture.toString()).contains("testatdebug"); + assertThat(this.outputCapture.toString()).contains("testattrace"); } @Test @@ -268,8 +259,8 @@ public class LoggingApplicationListenerTests { this.context.getClassLoader()); this.logger.debug("testatdebug"); this.logger.trace("testattrace"); - assertThat(this.outputCapture.toString(), containsString("testatdebug")); - assertThat(this.outputCapture.toString(), containsString("testattrace")); + assertThat(this.outputCapture.toString()).contains("testatdebug"); + assertThat(this.outputCapture.toString()).contains("testattrace"); } @Test @@ -279,9 +270,8 @@ public class LoggingApplicationListenerTests { this.initializer.initialize(this.context.getEnvironment(), this.context.getClassLoader()); this.logger.debug("testatdebug"); - assertThat(this.outputCapture.toString(), not(containsString("testatdebug"))); - assertThat(this.outputCapture.toString(), - containsString("Cannot set level: GARBAGE")); + assertThat(this.outputCapture.toString()).doesNotContain("testatdebug") + .contains("Cannot set level: GARBAGE"); } @Test @@ -292,8 +282,8 @@ public class LoggingApplicationListenerTests { this.context.getClassLoader()); this.logger.debug("testatdebug"); this.logger.fatal("testatfatal"); - assertThat(this.outputCapture.toString(), not(containsString("testatdebug"))); - assertThat(this.outputCapture.toString(), not(containsString("testatfatal"))); + assertThat(this.outputCapture.toString()).doesNotContain("testatdebug") + .doesNotContain("testatfatal"); } @Test @@ -304,8 +294,8 @@ public class LoggingApplicationListenerTests { this.context.getClassLoader()); this.logger.debug("testatdebug"); this.logger.fatal("testatfatal"); - assertThat(this.outputCapture.toString(), not(containsString("testatdebug"))); - assertThat(this.outputCapture.toString(), not(containsString("testatfatal"))); + assertThat(this.outputCapture.toString()).doesNotContain("testatdebug") + .doesNotContain("testatfatal"); } @Test @@ -315,7 +305,7 @@ public class LoggingApplicationListenerTests { this.initializer.initialize(this.context.getEnvironment(), this.context.getClassLoader()); this.logger.debug("testatdebug"); - assertThat(this.outputCapture.toString(), not(containsString("testatdebug"))); + assertThat(this.outputCapture.toString()).doesNotContain("testatdebug"); } @Test @@ -327,14 +317,14 @@ public class LoggingApplicationListenerTests { this.initializer.initialize(this.context.getEnvironment(), this.context.getClassLoader()); this.logger.debug("testatdebug"); - assertThat(this.outputCapture.toString(), not(containsString("testatdebug"))); + assertThat(this.outputCapture.toString()).doesNotContain("testatdebug"); } @Test public void bridgeHandlerLifecycle() throws Exception { - assertTrue(bridgeHandlerInstalled()); + assertThat(bridgeHandlerInstalled()).isTrue(); this.initializer.onApplicationEvent(new ContextClosedEvent(this.context)); - assertFalse(bridgeHandlerInstalled()); + assertThat(bridgeHandlerInstalled()).isFalse(); } @Test @@ -369,7 +359,7 @@ public class LoggingApplicationListenerTests { listener.onApplicationEvent( new ApplicationStartedEvent(new SpringApplication(), NO_ARGS)); listener.initialize(this.context.getEnvironment(), this.context.getClassLoader()); - assertThat(listener.shutdownHook, is(nullValue())); + assertThat(listener.shutdownHook).isNull(); } @Test @@ -382,10 +372,10 @@ public class LoggingApplicationListenerTests { listener.onApplicationEvent( new ApplicationStartedEvent(new SpringApplication(), NO_ARGS)); listener.initialize(this.context.getEnvironment(), this.context.getClassLoader()); - assertThat(listener.shutdownHook, is(not(nullValue()))); + assertThat(listener.shutdownHook).isNotNull(); listener.shutdownHook.start(); assertThat(TestShutdownHandlerLoggingSystem.shutdownLatch.await(30, - TimeUnit.SECONDS), is(true)); + TimeUnit.SECONDS)).isTrue(); } @Test @@ -396,9 +386,9 @@ public class LoggingApplicationListenerTests { new ApplicationStartedEvent(this.springApplication, new String[0])); TestCleanupLoggingSystem loggingSystem = (TestCleanupLoggingSystem) ReflectionTestUtils .getField(this.initializer, "loggingSystem"); - assertThat(loggingSystem.cleanedUp, is(false)); + assertThat(loggingSystem.cleanedUp).isFalse(); this.initializer.onApplicationEvent(new ContextClosedEvent(this.context)); - assertThat(loggingSystem.cleanedUp, is(true)); + assertThat(loggingSystem.cleanedUp).isTrue(); } @Test @@ -409,13 +399,13 @@ public class LoggingApplicationListenerTests { new ApplicationStartedEvent(this.springApplication, new String[0])); TestCleanupLoggingSystem loggingSystem = (TestCleanupLoggingSystem) ReflectionTestUtils .getField(this.initializer, "loggingSystem"); - assertThat(loggingSystem.cleanedUp, is(false)); + assertThat(loggingSystem.cleanedUp).isFalse(); GenericApplicationContext childContext = new GenericApplicationContext(); childContext.setParent(this.context); this.initializer.onApplicationEvent(new ContextClosedEvent(childContext)); - assertThat(loggingSystem.cleanedUp, is(false)); + assertThat(loggingSystem.cleanedUp).isFalse(); this.initializer.onApplicationEvent(new ContextClosedEvent(this.context)); - assertThat(loggingSystem.cleanedUp, is(true)); + assertThat(loggingSystem.cleanedUp).isTrue(); childContext.close(); } diff --git a/spring-boot/src/test/java/org/springframework/boot/logging/java/JavaLoggingSystemTests.java b/spring-boot/src/test/java/org/springframework/boot/logging/java/JavaLoggingSystemTests.java index d2599ad4b2..f9a1af5941 100644 --- a/spring-boot/src/test/java/org/springframework/boot/logging/java/JavaLoggingSystemTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/logging/java/JavaLoggingSystemTests.java @@ -33,11 +33,7 @@ import org.springframework.boot.test.OutputCapture; import org.springframework.util.ClassUtils; import org.springframework.util.StringUtils; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.greaterThan; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link JavaLoggingSystem}. @@ -85,9 +81,8 @@ public class JavaLoggingSystemTests extends AbstractLoggingSystemTests { this.loggingSystem.initialize(null, null, null); this.logger.info("Hello world"); String output = this.output.toString().trim(); - assertTrue("Wrong output:\n" + output, output.contains("Hello world")); - assertFalse("Output not hidden:\n" + output, output.contains("Hidden")); - assertFalse(new File(tmpDir() + "/spring.log").exists()); + assertThat(output).contains("Hello world").doesNotContain("Hidden"); + assertThat(new File(tmpDir() + "/spring.log").exists()).isFalse(); } @Test @@ -102,9 +97,8 @@ public class JavaLoggingSystemTests extends AbstractLoggingSystemTests { this.loggingSystem.initialize(null, null, getLogFile(null, tmpDir())); this.logger.info("Hello world"); String output = this.output.toString().trim(); - assertTrue("Wrong output:\n" + output, output.contains("Hello world")); - assertFalse("Output not hidden:\n" + output, output.contains("Hidden")); - assertThat(temp.listFiles(SPRING_LOG_FILTER).length, greaterThan(0)); + assertThat(output).contains("Hello world").doesNotContain("Hidden"); + assertThat(temp.listFiles(SPRING_LOG_FILTER).length).isGreaterThan(0); } @Test @@ -113,8 +107,7 @@ public class JavaLoggingSystemTests extends AbstractLoggingSystemTests { this.loggingSystem.initialize(null, null, null); this.logger.info("Hello world"); String output = this.output.toString().trim(); - assertTrue("Wrong output:\n" + output, output.contains("Hello world")); - assertTrue("Wrong output:\n" + output, output.contains("???? INFO [")); + assertThat(output).contains("Hello world").contains("???? INFO ["); } @Test @@ -126,8 +119,7 @@ public class JavaLoggingSystemTests extends AbstractLoggingSystemTests { this.logger.info("Hello world"); this.logger.info("Hello world"); String output = this.output.toString().trim(); - assertTrue("Wrong output:\n" + output, output.contains("Hello world")); - assertTrue("Wrong output:\n" + output, output.contains("1234 INFO [")); + assertThat(output).contains("Hello world").contains("1234 INFO ["); } @Test @@ -137,7 +129,7 @@ public class JavaLoggingSystemTests extends AbstractLoggingSystemTests { null); this.logger.info("Hello world"); String output = this.output.toString().trim(); - assertTrue("Wrong output:\n" + output, output.contains("INFO: Hello")); + assertThat(output).contains("INFO: Hello"); } @Test(expected = IllegalStateException.class) @@ -154,8 +146,8 @@ public class JavaLoggingSystemTests extends AbstractLoggingSystemTests { this.logger.debug("Hello"); this.loggingSystem.setLogLevel("org.springframework.boot", LogLevel.DEBUG); this.logger.debug("Hello"); - assertThat(StringUtils.countOccurrencesOf(this.output.toString(), "Hello"), - equalTo(1)); + assertThat(StringUtils.countOccurrencesOf(this.output.toString(), "Hello")) + .isEqualTo(1); } } diff --git a/spring-boot/src/test/java/org/springframework/boot/logging/log4j2/ColorConverterTests.java b/spring-boot/src/test/java/org/springframework/boot/logging/log4j2/ColorConverterTests.java index ffe2be17ae..796ddd6e72 100644 --- a/spring-boot/src/test/java/org/springframework/boot/logging/log4j2/ColorConverterTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/logging/log4j2/ColorConverterTests.java @@ -25,8 +25,7 @@ import org.junit.Test; import org.springframework.boot.ansi.AnsiOutput; -import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link ColorConverter}. @@ -62,49 +61,49 @@ public class ColorConverterTests { public void faint() { StringBuilder output = new StringBuilder(); newConverter("faint").format(this.event, output); - assertThat(output.toString(), equalTo("\033[2min\033[0;39m")); + assertThat(output.toString()).isEqualTo("\033[2min\033[0;39m"); } @Test public void red() { StringBuilder output = new StringBuilder(); newConverter("red").format(this.event, output); - assertThat(output.toString(), equalTo("\033[31min\033[0;39m")); + assertThat(output.toString()).isEqualTo("\033[31min\033[0;39m"); } @Test public void green() throws Exception { StringBuilder output = new StringBuilder(); newConverter("green").format(this.event, output); - assertThat(output.toString(), equalTo("\033[32min\033[0;39m")); + assertThat(output.toString()).isEqualTo("\033[32min\033[0;39m"); } @Test public void yellow() throws Exception { StringBuilder output = new StringBuilder(); newConverter("yellow").format(this.event, output); - assertThat(output.toString(), equalTo("\033[33min\033[0;39m")); + assertThat(output.toString()).isEqualTo("\033[33min\033[0;39m"); } @Test public void blue() throws Exception { StringBuilder output = new StringBuilder(); newConverter("blue").format(this.event, output); - assertThat(output.toString(), equalTo("\033[34min\033[0;39m")); + assertThat(output.toString()).isEqualTo("\033[34min\033[0;39m"); } @Test public void magenta() throws Exception { StringBuilder output = new StringBuilder(); newConverter("magenta").format(this.event, output); - assertThat(output.toString(), equalTo("\033[35min\033[0;39m")); + assertThat(output.toString()).isEqualTo("\033[35min\033[0;39m"); } @Test public void cyan() throws Exception { StringBuilder output = new StringBuilder(); newConverter("cyan").format(this.event, output); - assertThat(output.toString(), equalTo("\033[36min\033[0;39m")); + assertThat(output.toString()).isEqualTo("\033[36min\033[0;39m"); } @Test @@ -112,7 +111,7 @@ public class ColorConverterTests { this.event.setLevel(Level.FATAL); StringBuilder output = new StringBuilder(); newConverter(null).format(this.event, output); - assertThat(output.toString(), equalTo("\033[31min\033[0;39m")); + assertThat(output.toString()).isEqualTo("\033[31min\033[0;39m"); } @Test @@ -120,7 +119,7 @@ public class ColorConverterTests { this.event.setLevel(Level.ERROR); StringBuilder output = new StringBuilder(); newConverter(null).format(this.event, output); - assertThat(output.toString(), equalTo("\033[31min\033[0;39m")); + assertThat(output.toString()).isEqualTo("\033[31min\033[0;39m"); } @Test @@ -128,7 +127,7 @@ public class ColorConverterTests { this.event.setLevel(Level.WARN); StringBuilder output = new StringBuilder(); newConverter(null).format(this.event, output); - assertThat(output.toString(), equalTo("\033[33min\033[0;39m")); + assertThat(output.toString()).isEqualTo("\033[33min\033[0;39m"); } @Test @@ -136,7 +135,7 @@ public class ColorConverterTests { this.event.setLevel(Level.DEBUG); StringBuilder output = new StringBuilder(); newConverter(null).format(this.event, output); - assertThat(output.toString(), equalTo("\033[32min\033[0;39m")); + assertThat(output.toString()).isEqualTo("\033[32min\033[0;39m"); } @Test @@ -144,7 +143,7 @@ public class ColorConverterTests { this.event.setLevel(Level.TRACE); StringBuilder output = new StringBuilder(); newConverter(null).format(this.event, output); - assertThat(output.toString(), equalTo("\033[32min\033[0;39m")); + assertThat(output.toString()).isEqualTo("\033[32min\033[0;39m"); } private static class TestLogEvent extends AbstractLogEvent { diff --git a/spring-boot/src/test/java/org/springframework/boot/logging/log4j2/ExtendedWhitespaceThrowablePatternConverterTests.java b/spring-boot/src/test/java/org/springframework/boot/logging/log4j2/ExtendedWhitespaceThrowablePatternConverterTests.java index 7d2e0db1e0..ca8d8be842 100644 --- a/spring-boot/src/test/java/org/springframework/boot/logging/log4j2/ExtendedWhitespaceThrowablePatternConverterTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/logging/log4j2/ExtendedWhitespaceThrowablePatternConverterTests.java @@ -21,10 +21,7 @@ import org.apache.logging.log4j.core.impl.Log4jLogEvent; import org.apache.logging.log4j.core.pattern.ThrowablePatternConverter; import org.junit.Test; -import static org.hamcrest.Matchers.endsWith; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.startsWith; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link ExtendedWhitespaceThrowablePatternConverter}. @@ -44,7 +41,7 @@ public class ExtendedWhitespaceThrowablePatternConverterTests { LogEvent event = Log4jLogEvent.newBuilder().build(); StringBuilder builder = new StringBuilder(); this.converter.format(event, builder); - assertThat(builder.toString(), equalTo("")); + assertThat(builder.toString()).isEqualTo(""); } @Test @@ -52,8 +49,7 @@ public class ExtendedWhitespaceThrowablePatternConverterTests { LogEvent event = Log4jLogEvent.newBuilder().setThrown(new Exception()).build(); StringBuilder builder = new StringBuilder(); this.converter.format(event, builder); - assertThat(builder.toString(), startsWith(LINE_SEPARATOR)); - assertThat(builder.toString(), endsWith(LINE_SEPARATOR)); + assertThat(builder).startsWith(LINE_SEPARATOR).endsWith(LINE_SEPARATOR); } } diff --git a/spring-boot/src/test/java/org/springframework/boot/logging/log4j2/Log4J2LoggingSystemTests.java b/spring-boot/src/test/java/org/springframework/boot/logging/log4j2/Log4J2LoggingSystemTests.java index ed6ca0366d..969769461a 100644 --- a/spring-boot/src/test/java/org/springframework/boot/logging/log4j2/Log4J2LoggingSystemTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/logging/log4j2/Log4J2LoggingSystemTests.java @@ -37,19 +37,13 @@ import org.junit.Test; import org.springframework.boot.logging.AbstractLoggingSystemTests; import org.springframework.boot.logging.LogLevel; import org.springframework.boot.test.OutputCapture; +import org.springframework.boot.test.assertj.Matched; import org.springframework.util.FileCopyUtils; import org.springframework.util.StringUtils; -import static org.hamcrest.Matchers.arrayContaining; +import static org.assertj.core.api.Assertions.assertThat; import static org.hamcrest.Matchers.containsString; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.instanceOf; -import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.not; -import static org.hamcrest.Matchers.notNullValue; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; /** * Tests for {@link Log4J2LoggingSystem}. @@ -79,12 +73,10 @@ public class Log4J2LoggingSystemTests extends AbstractLoggingSystemTests { this.loggingSystem.initialize(null, null, null); this.logger.info("Hello world"); String output = this.output.toString().trim(); - assertTrue("Wrong output:\n" + output, output.contains("Hello world")); - assertFalse("Output not hidden:\n" + output, output.contains("Hidden")); - assertFalse(new File(tmpDir() + "/spring.log").exists()); - assertThat( - this.loggingSystem.getConfiguration().getConfigurationSource().getFile(), - is(notNullValue())); + Configuration configuration = this.loggingSystem.getConfiguration(); + assertThat(output).contains("Hello world").doesNotContain("Hidden"); + assertThat(new File(tmpDir() + "/spring.log").exists()).isFalse(); + assertThat(configuration.getConfigurationSource().getFile()).isNotNull(); } @Test @@ -94,12 +86,10 @@ public class Log4J2LoggingSystemTests extends AbstractLoggingSystemTests { this.loggingSystem.initialize(null, null, getLogFile(null, tmpDir())); this.logger.info("Hello world"); String output = this.output.toString().trim(); - assertTrue("Wrong output:\n" + output, output.contains("Hello world")); - assertFalse("Output not hidden:\n" + output, output.contains("Hidden")); - assertTrue(new File(tmpDir() + "/spring.log").exists()); - assertThat( - this.loggingSystem.getConfiguration().getConfigurationSource().getFile(), - is(notNullValue())); + Configuration configuration = this.loggingSystem.getConfiguration(); + assertThat(output).contains("Hello world").doesNotContain("Hidden"); + assertThat(new File(tmpDir() + "/spring.log").exists()).isTrue(); + assertThat(configuration.getConfigurationSource().getFile()).isNotNull(); } @Test @@ -109,15 +99,15 @@ public class Log4J2LoggingSystemTests extends AbstractLoggingSystemTests { getLogFile(tmpDir() + "/tmp.log", null)); this.logger.info("Hello world"); String output = this.output.toString().trim(); - assertTrue("Wrong output:\n" + output, output.contains("Hello world")); - assertTrue("Wrong output:\n" + output, output.contains(tmpDir() + "/tmp.log")); - assertFalse(new File(tmpDir() + "/tmp.log").exists()); - assertThat(this.loggingSystem.getConfiguration().getConfigurationSource() - .getFile().getAbsolutePath(), containsString("log4j2-nondefault.xml")); + Configuration configuration = this.loggingSystem.getConfiguration(); + assertThat(output).contains("Hello world").contains(tmpDir() + "/tmp.log"); + assertThat(new File(tmpDir() + "/tmp.log").exists()).isFalse(); + assertThat(configuration.getConfigurationSource().getFile().getAbsolutePath()) + .contains("log4j2-nondefault.xml"); // we assume that "log4j2-nondefault.xml" contains the 'monitorInterval' // attribute, so we check that a monitor is created - assertThat(this.loggingSystem.getConfiguration().getConfigurationMonitor(), - is(instanceOf(FileConfigurationMonitor.class))); + assertThat(configuration.getConfigurationMonitor()) + .isInstanceOf(FileConfigurationMonitor.class); } @Test(expected = IllegalStateException.class) @@ -133,8 +123,8 @@ public class Log4J2LoggingSystemTests extends AbstractLoggingSystemTests { this.logger.debug("Hello"); this.loggingSystem.setLogLevel("org.springframework.boot", LogLevel.DEBUG); this.logger.debug("Hello"); - assertThat(StringUtils.countOccurrencesOf(this.output.toString(), "Hello"), - equalTo(1)); + assertThat(StringUtils.countOccurrencesOf(this.output.toString(), "Hello")) + .isEqualTo(1); } @Test @@ -145,7 +135,7 @@ public class Log4J2LoggingSystemTests extends AbstractLoggingSystemTests { LogManager.getRootLogger().debug("Hello"); this.loggingSystem.setLogLevel("foo.bar.baz", LogLevel.DEBUG); LogManager.getRootLogger().debug("Hello"); - assertThat(this.output.toString(), not(containsString("Hello"))); + assertThat(this.output.toString()).doesNotContain("Hello"); } @Test @@ -157,28 +147,28 @@ public class Log4J2LoggingSystemTests extends AbstractLoggingSystemTests { .getLogger(getClass().getName()); julLogger.severe("Hello world"); String output = this.output.toString().trim(); - assertTrue("Wrong output:\n" + output, output.contains("Hello world")); + assertThat(output).contains("Hello world"); } @Test public void configLocationsWithNoExtraDependencies() { - assertThat(this.loggingSystem.getStandardConfigLocations(), - is(arrayContaining("log4j2.xml"))); + assertThat(this.loggingSystem.getStandardConfigLocations()) + .contains("log4j2.xml"); } @Test public void configLocationsWithJacksonDatabind() { this.loggingSystem.availableClasses(ObjectMapper.class.getName()); - assertThat(this.loggingSystem.getStandardConfigLocations(), - is(arrayContaining("log4j2.json", "log4j2.jsn", "log4j2.xml"))); + assertThat(this.loggingSystem.getStandardConfigLocations()) + .contains("log4j2.json", "log4j2.jsn", "log4j2.xml"); } @Test public void configLocationsWithJacksonDataformatYaml() { this.loggingSystem .availableClasses("com.fasterxml.jackson.dataformat.yaml.YAMLParser"); - assertThat(this.loggingSystem.getStandardConfigLocations(), - is(arrayContaining("log4j2.yaml", "log4j2.yml", "log4j2.xml"))); + assertThat(this.loggingSystem.getStandardConfigLocations()) + .contains("log4j2.yaml", "log4j2.yml", "log4j2.xml"); } @Test @@ -186,15 +176,14 @@ public class Log4J2LoggingSystemTests extends AbstractLoggingSystemTests { this.loggingSystem.availableClasses( "com.fasterxml.jackson.dataformat.yaml.YAMLParser", ObjectMapper.class.getName()); - assertThat(this.loggingSystem.getStandardConfigLocations(), - is(arrayContaining("log4j2.yaml", "log4j2.yml", "log4j2.json", - "log4j2.jsn", "log4j2.xml"))); + assertThat(this.loggingSystem.getStandardConfigLocations()).contains( + "log4j2.yaml", "log4j2.yml", "log4j2.json", "log4j2.jsn", "log4j2.xml"); } @Test public void springConfigLocations() throws Exception { String[] locations = getSpringConfigLocations(this.loggingSystem); - assertThat(locations, equalTo(new String[] { "log4j2-spring.xml" })); + assertThat(locations).isEqualTo(new String[] { "log4j2-spring.xml" }); } @Test @@ -206,7 +195,7 @@ public class Log4J2LoggingSystemTests extends AbstractLoggingSystemTests { this.logger.warn("Expected exception", new RuntimeException("Expected")); String fileContents = FileCopyUtils .copyToString(new FileReader(new File(tmpDir() + "/spring.log"))); - assertThat(fileContents, is(expectedOutput)); + assertThat(fileContents).is(Matched.by(expectedOutput)); } @Test @@ -224,7 +213,7 @@ public class Log4J2LoggingSystemTests extends AbstractLoggingSystemTests { new RuntimeException("Expected", new RuntimeException("Cause"))); String fileContents = FileCopyUtils .copyToString(new FileReader(new File(tmpDir() + "/spring.log"))); - assertThat(fileContents, is(expectedOutput)); + assertThat(fileContents).is(Matched.by(expectedOutput)); } finally { System.clearProperty("LOG_EXCEPTION_CONVERSION_WORD"); diff --git a/spring-boot/src/test/java/org/springframework/boot/logging/log4j2/WhitespaceThrowablePatternConverterTests.java b/spring-boot/src/test/java/org/springframework/boot/logging/log4j2/WhitespaceThrowablePatternConverterTests.java index c3bf041f32..7aefaab032 100644 --- a/spring-boot/src/test/java/org/springframework/boot/logging/log4j2/WhitespaceThrowablePatternConverterTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/logging/log4j2/WhitespaceThrowablePatternConverterTests.java @@ -21,10 +21,7 @@ import org.apache.logging.log4j.core.impl.Log4jLogEvent; import org.apache.logging.log4j.core.pattern.ThrowablePatternConverter; import org.junit.Test; -import static org.hamcrest.Matchers.endsWith; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.startsWith; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link WhitespaceThrowablePatternConverter}. @@ -43,7 +40,7 @@ public class WhitespaceThrowablePatternConverterTests { LogEvent event = Log4jLogEvent.newBuilder().build(); StringBuilder builder = new StringBuilder(); this.converter.format(event, builder); - assertThat(builder.toString(), equalTo("")); + assertThat(builder.toString()).isEqualTo(""); } @Test @@ -51,8 +48,8 @@ public class WhitespaceThrowablePatternConverterTests { LogEvent event = Log4jLogEvent.newBuilder().setThrown(new Exception()).build(); StringBuilder builder = new StringBuilder(); this.converter.format(event, builder); - assertThat(builder.toString(), startsWith(LINE_SEPARATOR)); - assertThat(builder.toString(), endsWith(LINE_SEPARATOR)); + assertThat(builder.toString()).startsWith(LINE_SEPARATOR) + .endsWith(LINE_SEPARATOR); } } diff --git a/spring-boot/src/test/java/org/springframework/boot/logging/logback/ColorConverterTests.java b/spring-boot/src/test/java/org/springframework/boot/logging/logback/ColorConverterTests.java index 47893a403f..865e3c560d 100644 --- a/spring-boot/src/test/java/org/springframework/boot/logging/logback/ColorConverterTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/logging/logback/ColorConverterTests.java @@ -27,8 +27,7 @@ import org.junit.Test; import org.springframework.boot.ansi.AnsiOutput; -import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link ColorConverter}. @@ -61,76 +60,76 @@ public class ColorConverterTests { public void faint() throws Exception { this.converter.setOptionList(Collections.singletonList("faint")); String out = this.converter.transform(this.event, this.in); - assertThat(out, equalTo("\033[2min\033[0;39m")); + assertThat(out).isEqualTo("\033[2min\033[0;39m"); } @Test public void red() throws Exception { this.converter.setOptionList(Collections.singletonList("red")); String out = this.converter.transform(this.event, this.in); - assertThat(out, equalTo("\033[31min\033[0;39m")); + assertThat(out).isEqualTo("\033[31min\033[0;39m"); } @Test public void green() throws Exception { this.converter.setOptionList(Collections.singletonList("green")); String out = this.converter.transform(this.event, this.in); - assertThat(out, equalTo("\033[32min\033[0;39m")); + assertThat(out).isEqualTo("\033[32min\033[0;39m"); } @Test public void yellow() throws Exception { this.converter.setOptionList(Collections.singletonList("yellow")); String out = this.converter.transform(this.event, this.in); - assertThat(out, equalTo("\033[33min\033[0;39m")); + assertThat(out).isEqualTo("\033[33min\033[0;39m"); } @Test public void blue() throws Exception { this.converter.setOptionList(Collections.singletonList("blue")); String out = this.converter.transform(this.event, this.in); - assertThat(out, equalTo("\033[34min\033[0;39m")); + assertThat(out).isEqualTo("\033[34min\033[0;39m"); } @Test public void magenta() throws Exception { this.converter.setOptionList(Collections.singletonList("magenta")); String out = this.converter.transform(this.event, this.in); - assertThat(out, equalTo("\033[35min\033[0;39m")); + assertThat(out).isEqualTo("\033[35min\033[0;39m"); } @Test public void cyan() throws Exception { this.converter.setOptionList(Collections.singletonList("cyan")); String out = this.converter.transform(this.event, this.in); - assertThat(out, equalTo("\033[36min\033[0;39m")); + assertThat(out).isEqualTo("\033[36min\033[0;39m"); } @Test public void highlightError() throws Exception { this.event.setLevel(Level.ERROR); String out = this.converter.transform(this.event, this.in); - assertThat(out, equalTo("\033[31min\033[0;39m")); + assertThat(out).isEqualTo("\033[31min\033[0;39m"); } @Test public void highlightWarn() throws Exception { this.event.setLevel(Level.WARN); String out = this.converter.transform(this.event, this.in); - assertThat(out, equalTo("\033[33min\033[0;39m")); + assertThat(out).isEqualTo("\033[33min\033[0;39m"); } @Test public void highlightDebug() throws Exception { this.event.setLevel(Level.DEBUG); String out = this.converter.transform(this.event, this.in); - assertThat(out, equalTo("\033[32min\033[0;39m")); + assertThat(out).isEqualTo("\033[32min\033[0;39m"); } @Test public void highlightTrace() throws Exception { this.event.setLevel(Level.TRACE); String out = this.converter.transform(this.event, this.in); - assertThat(out, equalTo("\033[32min\033[0;39m")); + assertThat(out).isEqualTo("\033[32min\033[0;39m"); } } diff --git a/spring-boot/src/test/java/org/springframework/boot/logging/logback/ExtendedWhitespaceThrowableProxyConverterTests.java b/spring-boot/src/test/java/org/springframework/boot/logging/logback/ExtendedWhitespaceThrowableProxyConverterTests.java index c8d36110fc..6aabd72a07 100644 --- a/spring-boot/src/test/java/org/springframework/boot/logging/logback/ExtendedWhitespaceThrowableProxyConverterTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/logging/logback/ExtendedWhitespaceThrowableProxyConverterTests.java @@ -20,10 +20,7 @@ import ch.qos.logback.classic.spi.LoggingEvent; import ch.qos.logback.classic.spi.ThrowableProxy; import org.junit.Test; -import static org.hamcrest.Matchers.endsWith; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.startsWith; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link ExtendedWhitespaceThrowableProxyConverter}. @@ -42,15 +39,14 @@ public class ExtendedWhitespaceThrowableProxyConverterTests { @Test public void noStackTrace() throws Exception { String s = this.converter.convert(this.event); - assertThat(s, equalTo("")); + assertThat(s).isEmpty(); } @Test public void withStackTrace() throws Exception { this.event.setThrowableProxy(new ThrowableProxy(new RuntimeException())); String s = this.converter.convert(this.event); - assertThat(s, startsWith(LINE_SEPARATOR)); - assertThat(s, endsWith(LINE_SEPARATOR)); + assertThat(s).startsWith(LINE_SEPARATOR).endsWith(LINE_SEPARATOR); } } diff --git a/spring-boot/src/test/java/org/springframework/boot/logging/logback/LevelRemappingAppenderTests.java b/spring-boot/src/test/java/org/springframework/boot/logging/logback/LevelRemappingAppenderTests.java index aeb25992a8..dcf10096ce 100644 --- a/spring-boot/src/test/java/org/springframework/boot/logging/logback/LevelRemappingAppenderTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/logging/logback/LevelRemappingAppenderTests.java @@ -27,8 +27,7 @@ import org.mockito.MockitoAnnotations; import org.springframework.boot.logging.logback.LevelRemappingAppender.AppendableLogger; -import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.spy; @@ -73,7 +72,7 @@ public class LevelRemappingAppenderTests { public void defaultRemapsInfo() throws Exception { this.appender.append(mockLogEvent(Level.INFO)); verify(this.logger).callAppenders(this.logCaptor.capture()); - assertThat(this.logCaptor.getValue().getLevel(), equalTo(Level.DEBUG)); + assertThat(this.logCaptor.getValue().getLevel()).isEqualTo(Level.DEBUG); } @Test @@ -82,15 +81,17 @@ public class LevelRemappingAppenderTests { this.appender.append(mockLogEvent(Level.DEBUG)); this.appender.append(mockLogEvent(Level.ERROR)); verify(this.logger, times(2)).callAppenders(this.logCaptor.capture()); - assertThat(this.logCaptor.getAllValues().get(0).getLevel(), equalTo(Level.TRACE)); - assertThat(this.logCaptor.getAllValues().get(1).getLevel(), equalTo(Level.WARN)); + assertThat(this.logCaptor.getAllValues().get(0).getLevel()) + .isEqualTo(Level.TRACE); + assertThat(this.logCaptor.getAllValues().get(1).getLevel()).isEqualTo(Level.WARN); } @Test public void notRemapped() throws Exception { this.appender.append(mockLogEvent(Level.TRACE)); verify(this.logger).callAppenders(this.logCaptor.capture()); - assertThat(this.logCaptor.getAllValues().get(0).getLevel(), equalTo(Level.TRACE)); + assertThat(this.logCaptor.getAllValues().get(0).getLevel()) + .isEqualTo(Level.TRACE); } private ILoggingEvent mockLogEvent(Level level) { diff --git a/spring-boot/src/test/java/org/springframework/boot/logging/logback/LogbackLoggingSystemTests.java b/spring-boot/src/test/java/org/springframework/boot/logging/logback/LogbackLoggingSystemTests.java index 57b10dfa10..34ed791f28 100644 --- a/spring-boot/src/test/java/org/springframework/boot/logging/logback/LogbackLoggingSystemTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/logging/logback/LogbackLoggingSystemTests.java @@ -40,19 +40,14 @@ import org.springframework.boot.logging.LogFile; import org.springframework.boot.logging.LogLevel; import org.springframework.boot.logging.LoggingInitializationContext; import org.springframework.boot.test.OutputCapture; +import org.springframework.boot.test.assertj.Matched; import org.springframework.mock.env.MockEnvironment; import org.springframework.util.FileCopyUtils; import org.springframework.util.StringUtils; +import static org.assertj.core.api.Assertions.assertThat; import static org.hamcrest.Matchers.containsString; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.not; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; /** * Tests for {@link LogbackLoggingSystem}. @@ -93,11 +88,9 @@ public class LogbackLoggingSystemTests extends AbstractLoggingSystemTests { this.loggingSystem.initialize(this.initializationContext, null, null); this.logger.info("Hello world"); String output = this.output.toString().trim(); - assertTrue("Wrong output:\n" + output, output.contains("Hello world")); - assertFalse("Output not hidden:\n" + output, output.contains("Hidden")); - assertTrue("Wrong output pattern:\n" + output, - getLineWithText(output, "Hello world").contains("INFO")); - assertFalse(new File(tmpDir() + "/spring.log").exists()); + assertThat(output).contains("Hello world").doesNotContain("Hidden"); + assertThat(getLineWithText(output, "Hello world")).contains("INFO"); + assertThat(new File(tmpDir() + "/spring.log").exists()).isFalse(); } @Test @@ -109,13 +102,10 @@ public class LogbackLoggingSystemTests extends AbstractLoggingSystemTests { this.logger.info("Hello world"); String output = this.output.toString().trim(); File file = new File(tmpDir() + "/spring.log"); - assertTrue("Wrong output:\n" + output, output.contains("Hello world")); - assertFalse("Output not hidden:\n" + output, output.contains("Hidden")); - assertTrue("Wrong console output pattern:\n" + output, - getLineWithText(output, "Hello world").contains("INFO")); - assertTrue(file.exists()); - assertTrue("Wrong file output pattern:\n" + output, - getLineWithText(file, "Hello world").contains("INFO")); + assertThat(output).contains("Hello world").doesNotContain("Hidden"); + assertThat(getLineWithText(output, "Hello world")).contains("INFO"); + assertThat(file.exists()).isTrue(); + assertThat(getLineWithText(file, "Hello world")).contains("INFO"); } @Test @@ -124,7 +114,7 @@ public class LogbackLoggingSystemTests extends AbstractLoggingSystemTests { ILoggerFactory factory = StaticLoggerBinder.getSingleton().getLoggerFactory(); LoggerContext context = (LoggerContext) factory; Logger root = context.getLogger(org.slf4j.Logger.ROOT_LOGGER_NAME); - assertNotNull(root.getAppender("CONSOLE")); + assertThat(root.getAppender("CONSOLE")).isNotNull(); } @Test @@ -135,10 +125,9 @@ public class LogbackLoggingSystemTests extends AbstractLoggingSystemTests { getLogFile(tmpDir() + "/tmp.log", null)); this.logger.info("Hello world"); String output = this.output.toString().trim(); - assertTrue("Wrong output:\n" + output, output.contains("Hello world")); - assertTrue("Wrong output:\n" + output, output.contains(tmpDir() + "/tmp.log")); - assertTrue("Wrong output:\n" + output, output.endsWith("BOOTBOOT")); - assertFalse(new File(tmpDir() + "/tmp.log").exists()); + assertThat(output).contains("Hello world").contains(tmpDir() + "/tmp.log"); + assertThat(output).endsWith("BOOTBOOT"); + assertThat(new File(tmpDir() + "/tmp.log").exists()).isFalse(); } @Test @@ -148,8 +137,8 @@ public class LogbackLoggingSystemTests extends AbstractLoggingSystemTests { this.loggingSystem.beforeInitialize(); this.loggingSystem.initialize(this.initializationContext, null, null); String output = this.output.toString().trim(); - assertTrue("Wrong output:\n" + output, output.contains("Ignoring " - + "'logback.configurationFile' system property. Please use 'logging.config' instead.")); + assertThat(output).contains("Ignoring 'logback.configurationFile' " + + "system property. Please use 'logging.config' instead."); } finally { System.clearProperty("logback.configurationFile"); @@ -170,8 +159,8 @@ public class LogbackLoggingSystemTests extends AbstractLoggingSystemTests { this.logger.debug("Hello"); this.loggingSystem.setLogLevel("org.springframework.boot", LogLevel.DEBUG); this.logger.debug("Hello"); - assertThat(StringUtils.countOccurrencesOf(this.output.toString(), "Hello"), - equalTo(1)); + assertThat(StringUtils.countOccurrencesOf(this.output.toString(), "Hello")) + .isEqualTo(1); } @Test @@ -182,7 +171,7 @@ public class LogbackLoggingSystemTests extends AbstractLoggingSystemTests { .getLogger(getClass().getName()); julLogger.info("Hello world"); String output = this.output.toString().trim(); - assertTrue("Wrong output:\n" + output, output.contains("Hello world")); + assertThat(output).contains("Hello world"); } @Test @@ -194,38 +183,36 @@ public class LogbackLoggingSystemTests extends AbstractLoggingSystemTests { .getLogger(getClass().getName()); julLogger.fine("Hello debug world"); String output = this.output.toString().trim(); - assertTrue("Wrong output:\n" + output, output.contains("Hello debug world")); + assertThat(output).contains("Hello debug world"); } @Test public void jbossLoggingIsConfiguredToUseSlf4j() { this.loggingSystem.beforeInitialize(); - assertEquals("slf4j", System.getProperty("org.jboss.logging.provider")); + assertThat(System.getProperty("org.jboss.logging.provider")).isEqualTo("slf4j"); } @Test public void bridgeHandlerLifecycle() { - assertFalse(bridgeHandlerInstalled()); + assertThat(bridgeHandlerInstalled()).isFalse(); this.loggingSystem.beforeInitialize(); - assertTrue(bridgeHandlerInstalled()); + assertThat(bridgeHandlerInstalled()).isTrue(); this.loggingSystem.cleanUp(); - assertFalse(bridgeHandlerInstalled()); + assertThat(bridgeHandlerInstalled()).isFalse(); } @Test public void standardConfigLocations() throws Exception { String[] locations = this.loggingSystem.getStandardConfigLocations(); - assertThat(locations, equalTo(new String[] { "logback-test.groovy", - "logback-test.xml", "logback.groovy", "logback.xml" })); + assertThat(locations).containsExactly("logback-test.groovy", "logback-test.xml", + "logback.groovy", "logback.xml"); } @Test public void springConfigLocations() throws Exception { String[] locations = getSpringConfigLocations(this.loggingSystem); - assertThat(locations, - equalTo(new String[] { "logback-test-spring.groovy", - "logback-test-spring.xml", "logback-spring.groovy", - "logback-spring.xml" })); + assertThat(locations).containsExactly("logback-test-spring.groovy", + "logback-test-spring.xml", "logback-spring.groovy", "logback-spring.xml"); } private boolean bridgeHandlerInstalled() { @@ -248,8 +235,7 @@ public class LogbackLoggingSystemTests extends AbstractLoggingSystemTests { this.loggingSystem.initialize(loggingInitializationContext, null, null); this.logger.info("Hello world"); String output = this.output.toString().trim(); - assertFalse("Wrong output pattern:\n" + output, - getLineWithText(output, "Hello world").contains("INFO")); + assertThat(getLineWithText(output, "Hello world")).doesNotContain("INFO"); } @Test @@ -261,8 +247,7 @@ public class LogbackLoggingSystemTests extends AbstractLoggingSystemTests { this.loggingSystem.initialize(loggingInitializationContext, null, null); this.logger.info("Hello world"); String output = this.output.toString().trim(); - assertTrue("Wrong output pattern:\n" + output, - getLineWithText(output, "Hello world").contains("XINFOX")); + assertThat(getLineWithText(output, "Hello world")).contains("XINFOX"); } @Test @@ -276,10 +261,8 @@ public class LogbackLoggingSystemTests extends AbstractLoggingSystemTests { this.loggingSystem.initialize(loggingInitializationContext, null, logFile); this.logger.info("Hello world"); String output = this.output.toString().trim(); - assertTrue("Wrong console output pattern:\n" + output, - getLineWithText(output, "Hello world").contains("INFO")); - assertFalse("Wrong file output pattern:\n" + output, - getLineWithText(file, "Hello world").contains("INFO")); + assertThat(getLineWithText(output, "Hello world")).contains("INFO"); + assertThat(getLineWithText(file, "Hello world")).doesNotContain("INFO"); } @Test @@ -292,7 +275,7 @@ public class LogbackLoggingSystemTests extends AbstractLoggingSystemTests { this.logger.warn("Expected exception", new RuntimeException("Expected")); String fileContents = FileCopyUtils .copyToString(new FileReader(new File(tmpDir() + "/spring.log"))); - assertThat(fileContents, is(expectedOutput)); + assertThat(fileContents).is(Matched.by(expectedOutput)); } @Test @@ -311,7 +294,7 @@ public class LogbackLoggingSystemTests extends AbstractLoggingSystemTests { new RuntimeException("Expected", new RuntimeException("Cause"))); String fileContents = FileCopyUtils .copyToString(new FileReader(new File(tmpDir() + "/spring.log"))); - assertThat(fileContents, is(expectedOutput)); + assertThat(fileContents).is(Matched.by(expectedOutput)); } finally { System.clearProperty("LOG_EXCEPTION_CONVERSION_WORD"); diff --git a/spring-boot/src/test/java/org/springframework/boot/logging/logback/SpringBootJoranConfiguratorTests.java b/spring-boot/src/test/java/org/springframework/boot/logging/logback/SpringBootJoranConfiguratorTests.java index a00c654835..fd390b7f7c 100644 --- a/spring-boot/src/test/java/org/springframework/boot/logging/logback/SpringBootJoranConfiguratorTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/logging/logback/SpringBootJoranConfiguratorTests.java @@ -32,10 +32,9 @@ import org.springframework.boot.test.EnvironmentTestUtils; import org.springframework.boot.test.OutputCapture; import org.springframework.mock.env.MockEnvironment; +import static org.assertj.core.api.Assertions.assertThat; import static org.hamcrest.Matchers.containsString; -import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.not; -import static org.junit.Assert.assertThat; /** * Tests for {@link SpringBootJoranConfigurator}. @@ -129,14 +128,14 @@ public class SpringBootJoranConfiguratorTests { public void springProperty() throws Exception { EnvironmentTestUtils.addEnvironment(this.environment, "my.example-property:test"); initialize("property.xml"); - assertThat(this.context.getProperty("MINE"), equalTo("test")); + assertThat(this.context.getProperty("MINE")).isEqualTo("test"); } @Test public void relaxedSpringProperty() throws Exception { EnvironmentTestUtils.addEnvironment(this.environment, "my.EXAMPLE_PROPERTY:test"); initialize("property.xml"); - assertThat(this.context.getProperty("MINE"), equalTo("test")); + assertThat(this.context.getProperty("MINE")).isEqualTo("test"); } private void doTestNestedProfile(boolean expected, String... profiles) diff --git a/spring-boot/src/test/java/org/springframework/boot/logging/logback/WhitespaceThrowableProxyConverterTests.java b/spring-boot/src/test/java/org/springframework/boot/logging/logback/WhitespaceThrowableProxyConverterTests.java index b0b2b9a0fe..9515388c16 100644 --- a/spring-boot/src/test/java/org/springframework/boot/logging/logback/WhitespaceThrowableProxyConverterTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/logging/logback/WhitespaceThrowableProxyConverterTests.java @@ -20,10 +20,7 @@ import ch.qos.logback.classic.spi.LoggingEvent; import ch.qos.logback.classic.spi.ThrowableProxy; import org.junit.Test; -import static org.hamcrest.Matchers.endsWith; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.startsWith; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link WhitespaceThrowableProxyConverter}. @@ -42,15 +39,14 @@ public class WhitespaceThrowableProxyConverterTests { @Test public void noStackTrace() throws Exception { String s = this.converter.convert(this.event); - assertThat(s, equalTo("")); + assertThat(s).isEqualTo(""); } @Test public void withStackTrace() throws Exception { this.event.setThrowableProxy(new ThrowableProxy(new RuntimeException())); String s = this.converter.convert(this.event); - assertThat(s, startsWith(LINE_SEPARATOR)); - assertThat(s, endsWith(LINE_SEPARATOR)); + assertThat(s).startsWith(LINE_SEPARATOR).endsWith(LINE_SEPARATOR); } } diff --git a/spring-boot/src/test/java/org/springframework/boot/orm/jpa/EntityManagerFactoryBuilderTests.java b/spring-boot/src/test/java/org/springframework/boot/orm/jpa/EntityManagerFactoryBuilderTests.java index f581645747..a860078fc3 100644 --- a/spring-boot/src/test/java/org/springframework/boot/orm/jpa/EntityManagerFactoryBuilderTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/orm/jpa/EntityManagerFactoryBuilderTests.java @@ -27,8 +27,7 @@ import org.junit.Test; import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; /** @@ -52,8 +51,8 @@ public class EntityManagerFactoryBuilderTests { LocalContainerEntityManagerFactoryBean result1 = factory .dataSource(this.dataSource1) .properties(Collections.singletonMap("foo", "spam")).build(); - assertFalse(result1.getJpaPropertyMap().isEmpty()); - assertTrue(this.properties.isEmpty()); + assertThat(result1.getJpaPropertyMap().isEmpty()).isFalse(); + assertThat(this.properties.isEmpty()).isTrue(); } @Test @@ -63,10 +62,10 @@ public class EntityManagerFactoryBuilderTests { LocalContainerEntityManagerFactoryBean result1 = factory .dataSource(this.dataSource1) .properties(Collections.singletonMap("foo", "spam")).build(); - assertFalse(result1.getJpaPropertyMap().isEmpty()); + assertThat(result1.getJpaPropertyMap().isEmpty()).isFalse(); LocalContainerEntityManagerFactoryBean result2 = factory .dataSource(this.dataSource2).build(); - assertTrue(result2.getJpaPropertyMap().isEmpty()); + assertThat(result2.getJpaPropertyMap().isEmpty()).isTrue(); } } diff --git a/spring-boot/src/test/java/org/springframework/boot/orm/jpa/EntityScanTests.java b/spring-boot/src/test/java/org/springframework/boot/orm/jpa/EntityScanTests.java index f81740fc79..4037d0e9b7 100644 --- a/spring-boot/src/test/java/org/springframework/boot/orm/jpa/EntityScanTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/orm/jpa/EntityScanTests.java @@ -31,8 +31,7 @@ import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; -import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; /** @@ -121,7 +120,7 @@ public class EntityScanTests { String[] actual = this.context .getBean(TestLocalContainerEntityManagerFactoryBean.class) .getPackagesToScan(); - assertThat(actual, equalTo(expected)); + assertThat(actual).isEqualTo(expected); } @Configuration diff --git a/spring-boot/src/test/java/org/springframework/boot/test/AbstractConfigurationClassTests.java b/spring-boot/src/test/java/org/springframework/boot/test/AbstractConfigurationClassTests.java index 0c32ad98c2..706df04b83 100644 --- a/spring-boot/src/test/java/org/springframework/boot/test/AbstractConfigurationClassTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/test/AbstractConfigurationClassTests.java @@ -35,7 +35,7 @@ import org.springframework.core.type.MethodMetadata; import org.springframework.core.type.classreading.MetadataReader; import org.springframework.core.type.classreading.SimpleMetadataReaderFactory; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * Abstract base class for {@code @Configuration} sanity checks. @@ -59,8 +59,7 @@ public abstract class AbstractConfigurationClassTests { } } } - assertEquals("Found non-public @Bean methods: " + nonPublicBeanMethods, 0, - nonPublicBeanMethods.size()); + assertThat(nonPublicBeanMethods).as("Found non-public @Bean methods").isEmpty(); } private Set findConfigurationClasses() throws IOException { diff --git a/spring-boot/src/test/java/org/springframework/boot/test/ConfigFileApplicationContextInitializerTests.java b/spring-boot/src/test/java/org/springframework/boot/test/ConfigFileApplicationContextInitializerTests.java index a1df2ce204..5f3d7f04bb 100644 --- a/spring-boot/src/test/java/org/springframework/boot/test/ConfigFileApplicationContextInitializerTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/test/ConfigFileApplicationContextInitializerTests.java @@ -25,8 +25,7 @@ import org.springframework.core.env.Environment; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link ConfigFileApplicationContextInitializer}. @@ -42,7 +41,7 @@ public class ConfigFileApplicationContextInitializerTests { @Test public void initializerPopulatesEnvironment() { - assertThat(this.environment.getProperty("foo"), equalTo("bucket")); + assertThat(this.environment.getProperty("foo")).isEqualTo("bucket"); } @Configuration diff --git a/spring-boot/src/test/java/org/springframework/boot/test/EnvironmentTestUtilsTests.java b/spring-boot/src/test/java/org/springframework/boot/test/EnvironmentTestUtilsTests.java index 382071592f..fe9f330444 100644 --- a/spring-boot/src/test/java/org/springframework/boot/test/EnvironmentTestUtilsTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/test/EnvironmentTestUtilsTests.java @@ -25,9 +25,7 @@ import org.springframework.core.env.ConfigurableEnvironment; import org.springframework.core.env.MapPropertySource; import org.springframework.core.env.StandardEnvironment; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link EnvironmentTestUtils}. @@ -71,18 +69,16 @@ public class EnvironmentTestUtilsTests { @Test public void addPairNoValue() { String propertyName = "my.foo+bar"; - assertFalse(this.environment.containsProperty(propertyName)); + assertThat(this.environment.containsProperty(propertyName)).isFalse(); EnvironmentTestUtils.addEnvironment(this.environment, propertyName); - assertTrue(this.environment.containsProperty(propertyName)); - assertEquals("", this.environment.getProperty(propertyName)); + assertThat(this.environment.containsProperty(propertyName)).isTrue(); + assertThat(this.environment.getProperty(propertyName)).isEqualTo(""); } private void testAddSimplePair(String key, String value, String delimiter) { - assertFalse("Property '" + key + "' should not exist", - this.environment.containsProperty(key)); + assertThat(this.environment.containsProperty(key)).isFalse(); EnvironmentTestUtils.addEnvironment(this.environment, key + delimiter + value); - assertEquals("Wrong value for property '" + key + "'", value, - this.environment.getProperty(key)); + assertThat(this.environment.getProperty(key)).isEqualTo(value); } @Test @@ -91,9 +87,9 @@ public class EnvironmentTestUtilsTests { map.put("my.foo", "bar"); MapPropertySource source = new MapPropertySource("sample", map); this.environment.getPropertySources().addFirst(source); - assertEquals("bar", this.environment.getProperty("my.foo")); + assertThat(this.environment.getProperty("my.foo")).isEqualTo("bar"); EnvironmentTestUtils.addEnvironment(this.environment, "my.foo=bar2"); - assertEquals("bar2", this.environment.getProperty("my.foo")); + assertThat(this.environment.getProperty("my.foo")).isEqualTo("bar2"); } } diff --git a/spring-boot/src/test/java/org/springframework/boot/test/SpringApplicationConfigurationActiveProfileTests.java b/spring-boot/src/test/java/org/springframework/boot/test/SpringApplicationConfigurationActiveProfileTests.java index 58b0875296..7c350d18ec 100644 --- a/spring-boot/src/test/java/org/springframework/boot/test/SpringApplicationConfigurationActiveProfileTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/test/SpringApplicationConfigurationActiveProfileTests.java @@ -25,8 +25,7 @@ import org.springframework.context.annotation.Configuration; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link SpringApplicationContextLoader} with active profiles. See gh-1469. @@ -44,8 +43,8 @@ public class SpringApplicationConfigurationActiveProfileTests { @Test public void profiles() throws Exception { - assertThat(this.context.getEnvironment().getActiveProfiles(), - equalTo(new String[] { "override" })); + assertThat(this.context.getEnvironment().getActiveProfiles()) + .containsExactly("override"); } @Configuration diff --git a/spring-boot/src/test/java/org/springframework/boot/test/SpringApplicationConfigurationDefaultConfigurationTests.java b/spring-boot/src/test/java/org/springframework/boot/test/SpringApplicationConfigurationDefaultConfigurationTests.java index 8f3a416f6c..af6a19a26c 100644 --- a/spring-boot/src/test/java/org/springframework/boot/test/SpringApplicationConfigurationDefaultConfigurationTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/test/SpringApplicationConfigurationDefaultConfigurationTests.java @@ -23,7 +23,7 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import static org.junit.Assert.assertNotNull; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link SpringApplicationContextLoader} (detectDefaultConfigurationClasses). @@ -39,7 +39,7 @@ public class SpringApplicationConfigurationDefaultConfigurationTests { @Test public void nestedConfigClasses() { - assertNotNull(this.config); + assertThat(this.config).isNotNull(); } @Configuration diff --git a/spring-boot/src/test/java/org/springframework/boot/test/SpringApplicationConfigurationGroovyConfigurationTests.java b/spring-boot/src/test/java/org/springframework/boot/test/SpringApplicationConfigurationGroovyConfigurationTests.java index 404704f756..6984375baa 100644 --- a/spring-boot/src/test/java/org/springframework/boot/test/SpringApplicationConfigurationGroovyConfigurationTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/test/SpringApplicationConfigurationGroovyConfigurationTests.java @@ -22,7 +22,7 @@ import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import static org.junit.Assert.assertNotNull; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link SpringApplicationContextLoader} (detectDefaultConfigurationClasses). @@ -38,7 +38,7 @@ public class SpringApplicationConfigurationGroovyConfigurationTests { @Test public void groovyConfigLoaded() { - assertNotNull(this.foo); + assertThat(this.foo).isNotNull(); } } diff --git a/spring-boot/src/test/java/org/springframework/boot/test/SpringApplicationConfigurationGroovyConventionConfigurationTests.java b/spring-boot/src/test/java/org/springframework/boot/test/SpringApplicationConfigurationGroovyConventionConfigurationTests.java index 9bedeaf799..3cfb7359d5 100644 --- a/spring-boot/src/test/java/org/springframework/boot/test/SpringApplicationConfigurationGroovyConventionConfigurationTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/test/SpringApplicationConfigurationGroovyConventionConfigurationTests.java @@ -22,8 +22,7 @@ import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link SpringApplicationContextLoader} finding groovy config. @@ -39,7 +38,7 @@ public class SpringApplicationConfigurationGroovyConventionConfigurationTests { @Test public void groovyConfigLoaded() { - assertThat(this.foo, equalTo("World")); + assertThat(this.foo).isEqualTo("World"); } } diff --git a/spring-boot/src/test/java/org/springframework/boot/test/SpringApplicationConfigurationJmxTests.java b/spring-boot/src/test/java/org/springframework/boot/test/SpringApplicationConfigurationJmxTests.java index 54e79beb3f..31be059578 100644 --- a/spring-boot/src/test/java/org/springframework/boot/test/SpringApplicationConfigurationJmxTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/test/SpringApplicationConfigurationJmxTests.java @@ -26,7 +26,7 @@ import org.springframework.context.annotation.Configuration; import org.springframework.context.support.PropertySourcesPlaceholderConfigurer; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import static org.junit.Assert.assertFalse; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for disabling JMX by default @@ -43,7 +43,7 @@ public class SpringApplicationConfigurationJmxTests { @Test public void disabledByDefault() { - assertFalse(this.jmx); + assertThat(this.jmx).isFalse(); } @Configuration diff --git a/spring-boot/src/test/java/org/springframework/boot/test/SpringApplicationConfigurationMixedConfigurationTests.java b/spring-boot/src/test/java/org/springframework/boot/test/SpringApplicationConfigurationMixedConfigurationTests.java index f56bf8fd2c..31436a11c3 100644 --- a/spring-boot/src/test/java/org/springframework/boot/test/SpringApplicationConfigurationMixedConfigurationTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/test/SpringApplicationConfigurationMixedConfigurationTests.java @@ -24,7 +24,7 @@ import org.springframework.boot.test.SpringApplicationConfigurationMixedConfigur import org.springframework.context.annotation.Configuration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import static org.junit.Assert.assertNotNull; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link SpringApplicationContextLoader}. @@ -43,8 +43,8 @@ public class SpringApplicationConfigurationMixedConfigurationTests { @Test public void mixedConfigClasses() { - assertNotNull(this.foo); - assertNotNull(this.config); + assertThat(this.foo).isNotNull(); + assertThat(this.config).isNotNull(); } @Configuration diff --git a/spring-boot/src/test/java/org/springframework/boot/test/SpringApplicationConfigurationXmlConventionConfigurationTests.java b/spring-boot/src/test/java/org/springframework/boot/test/SpringApplicationConfigurationXmlConventionConfigurationTests.java index 1173773943..10eb8f2ca2 100644 --- a/spring-boot/src/test/java/org/springframework/boot/test/SpringApplicationConfigurationXmlConventionConfigurationTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/test/SpringApplicationConfigurationXmlConventionConfigurationTests.java @@ -22,8 +22,7 @@ import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link SpringApplicationContextLoader} finding XML config. @@ -39,7 +38,7 @@ public class SpringApplicationConfigurationXmlConventionConfigurationTests { @Test public void xmlConfigLoaded() { - assertThat(this.foo, equalTo("World")); + assertThat(this.foo).isEqualTo("World"); } } diff --git a/spring-boot/src/test/java/org/springframework/boot/test/SpringApplicationContextLoaderTests.java b/spring-boot/src/test/java/org/springframework/boot/test/SpringApplicationContextLoaderTests.java index e62b8593d9..90f5c15c61 100644 --- a/spring-boot/src/test/java/org/springframework/boot/test/SpringApplicationContextLoaderTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/test/SpringApplicationContextLoaderTests.java @@ -27,8 +27,7 @@ import org.springframework.test.context.TestContextManager; import org.springframework.test.context.support.TestPropertySourceUtils; import org.springframework.test.util.ReflectionTestUtils; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link SpringApplicationContextLoader} @@ -93,8 +92,8 @@ public class SpringApplicationContextLoaderTests { } private void assertKey(Map actual, String key, Object value) { - assertTrue("Key '" + key + "' not found", actual.containsKey(key)); - assertEquals(value, actual.get(key)); + assertThat(actual.containsKey(key)).as("Key '" + key + "' not found").isTrue(); + assertThat(actual.get(key)).isEqualTo(value); } @IntegrationTest({ "key=myValue", "anotherKey:anotherValue" }) diff --git a/spring-boot/src/test/java/org/springframework/boot/test/SpringApplicationIntegrationTestPropertyLocationTests.java b/spring-boot/src/test/java/org/springframework/boot/test/SpringApplicationIntegrationTestPropertyLocationTests.java index 09640382f2..296eff3ea9 100644 --- a/spring-boot/src/test/java/org/springframework/boot/test/SpringApplicationIntegrationTestPropertyLocationTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/test/SpringApplicationIntegrationTestPropertyLocationTests.java @@ -31,8 +31,7 @@ import org.springframework.test.context.TestPropertySource; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.WebAppConfiguration; -import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link IntegrationTest} with {@link TestPropertySource} locations. @@ -51,10 +50,10 @@ public class SpringApplicationIntegrationTestPropertyLocationTests { @Test public void loadedProperties() throws Exception { - assertThat(this.environment.getProperty("value1"), equalTo("123")); - assertThat(this.environment.getProperty("value2"), equalTo("456")); - assertThat(this.environment.getProperty("annotation-referenced"), - equalTo("fromfile")); + assertThat(this.environment.getProperty("value1")).isEqualTo("123"); + assertThat(this.environment.getProperty("value2")).isEqualTo("456"); + assertThat(this.environment.getProperty("annotation-referenced")) + .isEqualTo("fromfile"); } @Configuration @@ -71,9 +70,9 @@ public class SpringApplicationIntegrationTestPropertyLocationTests { @PostConstruct void checkValues() { - assertThat(this.value1, equalTo("123")); - assertThat(this.value2, equalTo("456")); - assertThat(this.annotationReferenced, equalTo("fromfile")); + assertThat(this.value1).isEqualTo("123"); + assertThat(this.value2).isEqualTo("456"); + assertThat(this.annotationReferenced).isEqualTo("fromfile"); } } diff --git a/spring-boot/src/test/java/org/springframework/boot/test/SpringApplicationIntegrationTestTests.java b/spring-boot/src/test/java/org/springframework/boot/test/SpringApplicationIntegrationTestTests.java index e1837197d3..1058b1db7a 100644 --- a/spring-boot/src/test/java/org/springframework/boot/test/SpringApplicationIntegrationTestTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/test/SpringApplicationIntegrationTestTests.java @@ -39,9 +39,7 @@ import org.springframework.web.context.support.WebApplicationContextUtils; import org.springframework.web.servlet.DispatcherServlet; import org.springframework.web.servlet.config.annotation.EnableWebMvc; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertSame; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link IntegrationTest} @@ -68,21 +66,20 @@ public class SpringApplicationIntegrationTestTests { @Test public void runAndTestHttpEndpoint() { - assertNotEquals(8080, this.port); - assertNotEquals(0, this.port); + assertThat(this.port).isNotEqualTo(8080).isNotEqualTo(0); String body = new RestTemplate() .getForObject("http://localhost:" + this.port + "/", String.class); - assertEquals("Hello World", body); + assertThat(body).isEqualTo("Hello World"); } @Test public void annotationAttributesOverridePropertiesFile() throws Exception { - assertEquals(123, this.value); + assertThat(this.value).isEqualTo(123); } @Test public void validateWebApplicationContextIsSet() { - assertSame(this.context, + assertThat(this.context).isSameAs( WebApplicationContextUtils.getWebApplicationContext(this.servletContext)); } diff --git a/spring-boot/src/test/java/org/springframework/boot/test/SpringApplicationMockMvcTests.java b/spring-boot/src/test/java/org/springframework/boot/test/SpringApplicationMockMvcTests.java index 1abd57a183..a2a3bba343 100644 --- a/spring-boot/src/test/java/org/springframework/boot/test/SpringApplicationMockMvcTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/test/SpringApplicationMockMvcTests.java @@ -35,7 +35,7 @@ import org.springframework.web.context.WebApplicationContext; import org.springframework.web.context.support.WebApplicationContextUtils; import org.springframework.web.servlet.config.annotation.EnableWebMvc; -import static org.junit.Assert.assertSame; +import static org.assertj.core.api.Assertions.assertThat; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @@ -71,7 +71,7 @@ public class SpringApplicationMockMvcTests { @Test public void validateWebApplicationContextIsSet() { - assertSame(this.context, + assertThat(this.context).isSameAs( WebApplicationContextUtils.getWebApplicationContext(this.servletContext)); } diff --git a/spring-boot/src/test/java/org/springframework/boot/test/SpringApplicationWebIntegrationTestTests.java b/spring-boot/src/test/java/org/springframework/boot/test/SpringApplicationWebIntegrationTestTests.java index 46c67d676c..5558012da9 100644 --- a/spring-boot/src/test/java/org/springframework/boot/test/SpringApplicationWebIntegrationTestTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/test/SpringApplicationWebIntegrationTestTests.java @@ -38,9 +38,7 @@ import org.springframework.web.context.support.WebApplicationContextUtils; import org.springframework.web.servlet.DispatcherServlet; import org.springframework.web.servlet.config.annotation.EnableWebMvc; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertSame; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link IntegrationTest} @@ -66,21 +64,20 @@ public class SpringApplicationWebIntegrationTestTests { @Test public void runAndTestHttpEndpoint() { - assertNotEquals(8080, this.port); - assertNotEquals(0, this.port); + assertThat(this.port).isNotEqualTo(8080).isNotEqualTo(0); String body = new RestTemplate() .getForObject("http://localhost:" + this.port + "/", String.class); - assertEquals("Hello World", body); + assertThat(body).isEqualTo("Hello World"); } @Test public void annotationAttributesOverridePropertiesFile() throws Exception { - assertEquals(123, this.value); + assertThat(this.value).isEqualTo(123); } @Test public void validateWebApplicationContextIsSet() { - assertSame(this.context, + assertThat(this.context).isSameAs( WebApplicationContextUtils.getWebApplicationContext(this.servletContext)); } diff --git a/spring-boot/src/test/java/org/springframework/boot/test/SpringBootMockServletContextTests.java b/spring-boot/src/test/java/org/springframework/boot/test/SpringBootMockServletContextTests.java index b21a55c5f0..f5cfe99fdf 100644 --- a/spring-boot/src/test/java/org/springframework/boot/test/SpringBootMockServletContextTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/test/SpringBootMockServletContextTests.java @@ -32,11 +32,8 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.WebAppConfiguration; import org.springframework.web.context.ServletContextAware; -import static org.hamcrest.Matchers.containsString; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.not; +import static org.assertj.core.api.Assertions.assertThat; import static org.hamcrest.Matchers.nullValue; -import static org.junit.Assert.assertThat; /** * Tests for {@link SpringBootMockServletContext}. @@ -67,9 +64,8 @@ public class SpringBootMockServletContextTests implements ServletContextAware { private void testResource(String path, String expectedLocation) throws MalformedURLException { URL resource = this.servletContext.getResource(path); - assertThat("Path " + path + " not found", resource, not(nullValue())); - assertThat("Path " + path + " not in " + expectedLocation, resource.getPath(), - containsString(expectedLocation)); + assertThat(resource).isNotNull(); + assertThat(resource.getPath()).contains(expectedLocation); } // gh-2654 @@ -84,18 +80,17 @@ public class SpringBootMockServletContextTests implements ServletContextAware { }; }; URL resource = context.getResource("/"); - assertThat(resource, not(nullValue())); + assertThat(resource).isNotEqualTo(nullValue()); File file = new File(URLDecoder.decode(resource.getPath(), "UTF-8")); - assertThat("File " + file + " exists", file.exists(), equalTo(true)); - assertThat("File " + file + " is directory", file.isDirectory(), equalTo(true)); + assertThat(file).exists().isDirectory(); String[] contents = file.list(new FilenameFilter() { @Override public boolean accept(File dir, String name) { return !(".".equals(name) || "..".equals(name)); } }); - assertThat(contents, not(nullValue())); - assertThat(contents.length, equalTo(0)); + assertThat(contents).isNotEqualTo(nullValue()); + assertThat(contents.length).isEqualTo(0); } @Configuration diff --git a/spring-boot/src/test/java/org/springframework/boot/test/TestRestTemplateTests.java b/spring-boot/src/test/java/org/springframework/boot/test/TestRestTemplateTests.java index df95495a73..d0b2041ab6 100644 --- a/spring-boot/src/test/java/org/springframework/boot/test/TestRestTemplateTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/test/TestRestTemplateTests.java @@ -24,9 +24,7 @@ import org.springframework.boot.test.TestRestTemplate.HttpClientOption; import org.springframework.http.client.HttpComponentsClientHttpRequestFactory; import org.springframework.http.client.InterceptingClientHttpRequestFactory; -import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link TestRestTemplate}. @@ -39,14 +37,14 @@ public class TestRestTemplateTests { @Test public void simple() { // The Apache client is on the classpath so we get the fully-fledged factory - assertTrue(new TestRestTemplate() - .getRequestFactory() instanceof HttpComponentsClientHttpRequestFactory); + assertThat(new TestRestTemplate().getRequestFactory()) + .isInstanceOf(HttpComponentsClientHttpRequestFactory.class); } @Test public void authenticated() { - assertTrue(new TestRestTemplate("user", "password") - .getRequestFactory() instanceof InterceptingClientHttpRequestFactory); + assertThat(new TestRestTemplate("user", "password").getRequestFactory()) + .isInstanceOf(InterceptingClientHttpRequestFactory.class); } @Test @@ -56,7 +54,7 @@ public class TestRestTemplateTests { CustomHttpComponentsClientHttpRequestFactory factory = (CustomHttpComponentsClientHttpRequestFactory) template .getRequestFactory(); RequestConfig config = factory.getRequestConfig(); - assertThat(config.isRedirectsEnabled(), equalTo(true)); + assertThat(config.isRedirectsEnabled()).isTrue(); } } diff --git a/spring-boot/src/test/java/org/springframework/boot/type/classreading/ConcurrentReferenceCachingMetadataReaderFactoryTests.java b/spring-boot/src/test/java/org/springframework/boot/type/classreading/ConcurrentReferenceCachingMetadataReaderFactoryTests.java index 8395d2db06..68c422959f 100644 --- a/spring-boot/src/test/java/org/springframework/boot/type/classreading/ConcurrentReferenceCachingMetadataReaderFactoryTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/type/classreading/ConcurrentReferenceCachingMetadataReaderFactoryTests.java @@ -23,9 +23,8 @@ import org.junit.Test; import org.springframework.core.io.Resource; import org.springframework.core.type.classreading.MetadataReader; -import static org.hamcrest.Matchers.not; +import static org.assertj.core.api.Assertions.assertThat; import static org.hamcrest.Matchers.sameInstance; -import static org.junit.Assert.assertThat; import static org.mockito.Matchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.spy; @@ -45,7 +44,7 @@ public class ConcurrentReferenceCachingMetadataReaderFactoryTests { new TestConcurrentReferenceCachingMetadataReaderFactory()); MetadataReader metadataReader1 = factory.getMetadataReader(getClass().getName()); MetadataReader metadataReader2 = factory.getMetadataReader(getClass().getName()); - assertThat(metadataReader1, sameInstance(metadataReader2)); + assertThat(metadataReader1).isSameAs(metadataReader2); verify(factory, times(1)).createMetadataReader((Resource) any()); } @@ -56,7 +55,7 @@ public class ConcurrentReferenceCachingMetadataReaderFactoryTests { MetadataReader metadataReader1 = factory.getMetadataReader(getClass().getName()); factory.clearCache(); MetadataReader metadataReader2 = factory.getMetadataReader(getClass().getName()); - assertThat(metadataReader1, not(sameInstance(metadataReader2))); + assertThat(metadataReader1).isNotEqualTo(sameInstance(metadataReader2)); verify(factory, times(2)).createMetadataReader((Resource) any()); } diff --git a/spring-boot/src/test/java/org/springframework/boot/web/servlet/ServletComponentScanIntegrationTests.java b/spring-boot/src/test/java/org/springframework/boot/web/servlet/ServletComponentScanIntegrationTests.java index d5c02aee7f..039dcdef98 100644 --- a/spring-boot/src/test/java/org/springframework/boot/web/servlet/ServletComponentScanIntegrationTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/web/servlet/ServletComponentScanIntegrationTests.java @@ -26,9 +26,7 @@ import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.client.RestTemplate; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.is; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; /** * Integration tests for {@link ServletComponentScan} @@ -55,7 +53,7 @@ public class ServletComponentScanIntegrationTests { String port = this.context.getEnvironment().getProperty("local.server.port"); String response = new RestTemplate() .getForObject("http://localhost:" + port + "/test", String.class); - assertThat(response, is(equalTo("alpha bravo"))); + assertThat(response).isEqualTo("alpha bravo"); } @Configuration diff --git a/spring-boot/src/test/java/org/springframework/boot/web/servlet/ServletComponentScanRegistrarTests.java b/spring-boot/src/test/java/org/springframework/boot/web/servlet/ServletComponentScanRegistrarTests.java index dcfc518758..218cb9f5d4 100644 --- a/spring-boot/src/test/java/org/springframework/boot/web/servlet/ServletComponentScanRegistrarTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/web/servlet/ServletComponentScanRegistrarTests.java @@ -24,8 +24,7 @@ import org.junit.rules.ExpectedException; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.context.annotation.Configuration; -import static org.hamcrest.Matchers.containsInAnyOrder; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link ServletComponentScanRegistrar} @@ -51,8 +50,8 @@ public class ServletComponentScanRegistrarTests { this.context = new AnnotationConfigApplicationContext(ValuePackages.class); ServletComponentRegisteringPostProcessor postProcessor = this.context .getBean(ServletComponentRegisteringPostProcessor.class); - assertThat(postProcessor.getPackagesToScan(), - containsInAnyOrder("com.example.foo", "com.example.bar")); + assertThat(postProcessor.getPackagesToScan()).contains("com.example.foo", + "com.example.bar"); } @Test @@ -60,8 +59,8 @@ public class ServletComponentScanRegistrarTests { this.context = new AnnotationConfigApplicationContext(BasePackages.class); ServletComponentRegisteringPostProcessor postProcessor = this.context .getBean(ServletComponentRegisteringPostProcessor.class); - assertThat(postProcessor.getPackagesToScan(), - containsInAnyOrder("com.example.foo", "com.example.bar")); + assertThat(postProcessor.getPackagesToScan()).contains("com.example.foo", + "com.example.bar"); } @Test @@ -69,8 +68,8 @@ public class ServletComponentScanRegistrarTests { this.context = new AnnotationConfigApplicationContext(BasePackageClasses.class); ServletComponentRegisteringPostProcessor postProcessor = this.context .getBean(ServletComponentRegisteringPostProcessor.class); - assertThat(postProcessor.getPackagesToScan(), - containsInAnyOrder(getClass().getPackage().getName())); + assertThat(postProcessor.getPackagesToScan()) + .contains(getClass().getPackage().getName()); } @Test @@ -81,8 +80,8 @@ public class ServletComponentScanRegistrarTests { this.context = new AnnotationConfigApplicationContext(ValueAndBasePackages.class); ServletComponentRegisteringPostProcessor postProcessor = this.context .getBean(ServletComponentRegisteringPostProcessor.class); - assertThat(postProcessor.getPackagesToScan(), - containsInAnyOrder(getClass().getPackage().getName())); + assertThat(postProcessor.getPackagesToScan()) + .contains(getClass().getPackage().getName()); } @Test @@ -91,8 +90,8 @@ public class ServletComponentScanRegistrarTests { AdditionalPackages.class); ServletComponentRegisteringPostProcessor postProcessor = this.context .getBean(ServletComponentRegisteringPostProcessor.class); - assertThat(postProcessor.getPackagesToScan(), containsInAnyOrder( - "com.example.foo", "com.example.bar", "com.example.baz")); + assertThat(postProcessor.getPackagesToScan()).contains("com.example.foo", + "com.example.bar", "com.example.baz"); } @Configuration diff --git a/spring-boot/src/test/java/org/springframework/boot/web/servlet/WebFilterHandlerTests.java b/spring-boot/src/test/java/org/springframework/boot/web/servlet/WebFilterHandlerTests.java index 68b223c1d8..b5c7b5b43d 100644 --- a/spring-boot/src/test/java/org/springframework/boot/web/servlet/WebFilterHandlerTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/web/servlet/WebFilterHandlerTests.java @@ -19,6 +19,7 @@ package org.springframework.boot.web.servlet; import java.io.IOException; import java.util.EnumSet; import java.util.Map; +import java.util.Set; import javax.servlet.DispatcherType; import javax.servlet.Filter; @@ -40,12 +41,7 @@ import org.springframework.beans.factory.support.SimpleBeanDefinitionRegistry; import org.springframework.context.annotation.ScannedGenericBeanDefinition; import org.springframework.core.type.classreading.SimpleMetadataReaderFactory; -import static org.hamcrest.Matchers.arrayContaining; -import static org.hamcrest.Matchers.arrayWithSize; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.hasEntry; -import static org.hamcrest.Matchers.is; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link WebFilterHandler} @@ -71,16 +67,16 @@ public class WebFilterHandlerTests { BeanDefinition filterRegistrationBean = this.registry .getBeanDefinition(DefaultConfigurationFilter.class.getName()); MutablePropertyValues propertyValues = filterRegistrationBean.getPropertyValues(); - assertThat(propertyValues.get("asyncSupported"), is((Object) false)); - assertThat((EnumSet) propertyValues.get("dispatcherTypes"), - is(EnumSet.of(DispatcherType.REQUEST))); - assertThat(((Map) propertyValues.get("initParameters")).size(), - is(0)); - assertThat((String[]) propertyValues.get("servletNames"), is(arrayWithSize(0))); - assertThat((String[]) propertyValues.get("urlPatterns"), is(arrayWithSize(0))); - assertThat(propertyValues.get("name"), - is((Object) DefaultConfigurationFilter.class.getName())); - assertThat(propertyValues.get("filter"), is(equalTo((Object) scanned))); + assertThat(propertyValues.get("asyncSupported")).isEqualTo(false); + assertThat((EnumSet) propertyValues.get("dispatcherTypes")) + .containsExactly(DispatcherType.REQUEST); + assertThat(((Map) propertyValues.get("initParameters"))) + .isEmpty(); + assertThat((String[]) propertyValues.get("servletNames")).isEmpty(); + assertThat((String[]) propertyValues.get("urlPatterns")).isEmpty(); + assertThat(propertyValues.get("name")) + .isEqualTo(DefaultConfigurationFilter.class.getName()); + assertThat(propertyValues.get("filter")).isEqualTo(scanned); } @Test @@ -91,7 +87,7 @@ public class WebFilterHandlerTests { this.handler.handle(scanned, this.registry); BeanDefinition filterRegistrationBean = this.registry.getBeanDefinition("custom"); MutablePropertyValues propertyValues = filterRegistrationBean.getPropertyValues(); - assertThat(propertyValues.get("name"), is((Object) "custom")); + assertThat(propertyValues.get("name")).isEqualTo("custom"); } @Test @@ -99,17 +95,18 @@ public class WebFilterHandlerTests { BeanDefinition filterRegistrationBean = getBeanDefinition( AsyncSupportedFilter.class); MutablePropertyValues propertyValues = filterRegistrationBean.getPropertyValues(); - assertThat(propertyValues.get("asyncSupported"), is((Object) true)); + assertThat(propertyValues.get("asyncSupported")).isEqualTo(true); } @Test + @SuppressWarnings("unchecked") public void dispatcherTypes() throws IOException { BeanDefinition filterRegistrationBean = getBeanDefinition( DispatcherTypesFilter.class); MutablePropertyValues propertyValues = filterRegistrationBean.getPropertyValues(); - assertThat(propertyValues.get("dispatcherTypes"), - is((Object) EnumSet.of(DispatcherType.FORWARD, DispatcherType.INCLUDE, - DispatcherType.REQUEST))); + assertThat((Set) propertyValues.get("dispatcherTypes")) + .containsExactly(DispatcherType.FORWARD, DispatcherType.INCLUDE, + DispatcherType.REQUEST); } @SuppressWarnings("unchecked") @@ -118,10 +115,8 @@ public class WebFilterHandlerTests { BeanDefinition filterRegistrationBean = getBeanDefinition( InitParametersFilter.class); MutablePropertyValues propertyValues = filterRegistrationBean.getPropertyValues(); - assertThat((Map) propertyValues.get("initParameters"), - hasEntry("a", "alpha")); - assertThat((Map) propertyValues.get("initParameters"), - hasEntry("b", "bravo")); + assertThat((Map) propertyValues.get("initParameters")) + .containsEntry("a", "alpha").containsEntry("b", "bravo"); } @Test @@ -129,8 +124,8 @@ public class WebFilterHandlerTests { BeanDefinition filterRegistrationBean = getBeanDefinition( ServletNamesFilter.class); MutablePropertyValues propertyValues = filterRegistrationBean.getPropertyValues(); - assertThat((String[]) propertyValues.get("servletNames"), - is(arrayContaining("alpha", "bravo"))); + assertThat((String[]) propertyValues.get("servletNames")).contains("alpha", + "bravo"); } @Test @@ -138,8 +133,8 @@ public class WebFilterHandlerTests { BeanDefinition filterRegistrationBean = getBeanDefinition( UrlPatternsFilter.class); MutablePropertyValues propertyValues = filterRegistrationBean.getPropertyValues(); - assertThat((String[]) propertyValues.get("urlPatterns"), - is(arrayContaining("alpha", "bravo"))); + assertThat((String[]) propertyValues.get("urlPatterns")).contains("alpha", + "bravo"); } @Test @@ -147,8 +142,8 @@ public class WebFilterHandlerTests { BeanDefinition filterRegistrationBean = getBeanDefinition( UrlPatternsFromValueFilter.class); MutablePropertyValues propertyValues = filterRegistrationBean.getPropertyValues(); - assertThat((String[]) propertyValues.get("urlPatterns"), - is(arrayContaining("alpha", "bravo"))); + assertThat((String[]) propertyValues.get("urlPatterns")).contains("alpha", + "bravo"); } @Test diff --git a/spring-boot/src/test/java/org/springframework/boot/web/servlet/WebServletHandlerTests.java b/spring-boot/src/test/java/org/springframework/boot/web/servlet/WebServletHandlerTests.java index 52b817e1f2..ef35b62ae2 100644 --- a/spring-boot/src/test/java/org/springframework/boot/web/servlet/WebServletHandlerTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/web/servlet/WebServletHandlerTests.java @@ -33,12 +33,7 @@ import org.springframework.beans.factory.support.SimpleBeanDefinitionRegistry; import org.springframework.context.annotation.ScannedGenericBeanDefinition; import org.springframework.core.type.classreading.SimpleMetadataReaderFactory; -import static org.hamcrest.Matchers.arrayContaining; -import static org.hamcrest.Matchers.arrayWithSize; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.hasEntry; -import static org.hamcrest.Matchers.is; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link WebServletHandler}. @@ -65,14 +60,14 @@ public class WebServletHandlerTests { .getBeanDefinition(DefaultConfigurationServlet.class.getName()); MutablePropertyValues propertyValues = servletRegistrationBean .getPropertyValues(); - assertThat(propertyValues.get("asyncSupported"), is((Object) false)); - assertThat(((Map) propertyValues.get("initParameters")).size(), - is(0)); - assertThat((Integer) propertyValues.get("loadOnStartup"), is(-1)); - assertThat(propertyValues.get("name"), - is((Object) DefaultConfigurationServlet.class.getName())); - assertThat((String[]) propertyValues.get("urlMappings"), is(arrayWithSize(0))); - assertThat(propertyValues.get("servlet"), is(equalTo((Object) scanned))); + assertThat(propertyValues.get("asyncSupported")).isEqualTo(false); + assertThat(((Map) propertyValues.get("initParameters"))) + .isEmpty(); + assertThat((Integer) propertyValues.get("loadOnStartup")).isEqualTo(-1); + assertThat(propertyValues.get("name")) + .isEqualTo(DefaultConfigurationServlet.class.getName()); + assertThat((String[]) propertyValues.get("urlMappings")).isEmpty(); + assertThat(propertyValues.get("servlet")).isEqualTo(scanned); } @Test @@ -85,7 +80,7 @@ public class WebServletHandlerTests { .getBeanDefinition("custom"); MutablePropertyValues propertyValues = servletRegistrationBean .getPropertyValues(); - assertThat(propertyValues.get("name"), is((Object) "custom")); + assertThat(propertyValues.get("name")).isEqualTo("custom"); } @Test @@ -94,7 +89,7 @@ public class WebServletHandlerTests { AsyncSupportedServlet.class); MutablePropertyValues propertyValues = servletRegistrationBean .getPropertyValues(); - assertThat(propertyValues.get("asyncSupported"), is((Object) true)); + assertThat(propertyValues.get("asyncSupported")).isEqualTo(true); } @SuppressWarnings("unchecked") @@ -104,10 +99,8 @@ public class WebServletHandlerTests { InitParametersServlet.class); MutablePropertyValues propertyValues = servletRegistrationBean .getPropertyValues(); - assertThat((Map) propertyValues.get("initParameters"), - hasEntry("a", "alpha")); - assertThat((Map) propertyValues.get("initParameters"), - hasEntry("b", "bravo")); + assertThat((Map) propertyValues.get("initParameters")) + .containsEntry("a", "alpha").containsEntry("b", "bravo"); } @Test @@ -116,8 +109,8 @@ public class WebServletHandlerTests { UrlPatternsServlet.class); MutablePropertyValues propertyValues = servletRegistrationBean .getPropertyValues(); - assertThat((String[]) propertyValues.get("urlMappings"), - is(arrayContaining("alpha", "bravo"))); + assertThat((String[]) propertyValues.get("urlMappings")).contains("alpha", + "bravo"); } @Test @@ -126,8 +119,8 @@ public class WebServletHandlerTests { UrlPatternsFromValueServlet.class); MutablePropertyValues propertyValues = servletRegistrationBean .getPropertyValues(); - assertThat((String[]) propertyValues.get("urlMappings"), - is(arrayContaining("alpha", "bravo"))); + assertThat((String[]) propertyValues.get("urlMappings")).contains("alpha", + "bravo"); } @Test diff --git a/spring-boot/src/test/java/org/springframework/boot/web/servlet/view/velocity/EmbeddedVelocityToolboxViewTests.java b/spring-boot/src/test/java/org/springframework/boot/web/servlet/view/velocity/EmbeddedVelocityToolboxViewTests.java index 976b5e4722..2a56f625d5 100644 --- a/spring-boot/src/test/java/org/springframework/boot/web/servlet/view/velocity/EmbeddedVelocityToolboxViewTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/web/servlet/view/velocity/EmbeddedVelocityToolboxViewTests.java @@ -33,9 +33,7 @@ import org.springframework.context.annotation.Configuration; import org.springframework.web.context.support.AnnotationConfigWebApplicationContext; import org.springframework.web.servlet.view.velocity.VelocityConfigurer; -import static org.hamcrest.Matchers.contains; -import static org.hamcrest.Matchers.notNullValue; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link EmbeddedVelocityToolboxView}. @@ -50,13 +48,13 @@ public class EmbeddedVelocityToolboxViewTests { @Test public void loadsContextFromClassPath() throws Exception { ToolContext context = getToolContext(PATH + "/toolbox.xml"); - assertThat(context.getToolbox().keySet(), contains("math")); + assertThat(context.getToolbox().keySet()).contains("math"); } @Test public void loadsWithoutConfig() throws Exception { ToolContext context = getToolContext(null); - assertThat(context, notNullValue()); + assertThat(context).isNotNull(); } private ToolContext getToolContext(String toolboxConfigLocation) throws Exception { diff --git a/spring-boot/src/test/java/org/springframework/boot/web/servlet/view/velocity/EmbeddedVelocityViewResolverTests.java b/spring-boot/src/test/java/org/springframework/boot/web/servlet/view/velocity/EmbeddedVelocityViewResolverTests.java index 8722a88836..7f85263d3e 100644 --- a/spring-boot/src/test/java/org/springframework/boot/web/servlet/view/velocity/EmbeddedVelocityViewResolverTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/web/servlet/view/velocity/EmbeddedVelocityViewResolverTests.java @@ -27,7 +27,7 @@ import org.springframework.web.context.support.AnnotationConfigWebApplicationCon import org.springframework.web.servlet.view.velocity.VelocityConfigurer; import org.springframework.web.servlet.view.velocity.VelocityView; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link EmbeddedVelocityViewResolver}. @@ -42,7 +42,7 @@ public class EmbeddedVelocityViewResolverTests { EmbeddedVelocityViewResolver resolver = context .getBean(EmbeddedVelocityViewResolver.class); Object viewClass = ReflectionTestUtils.getField(resolver, "viewClass"); - assertEquals(VelocityView.class, viewClass); + assertThat(viewClass).isEqualTo(VelocityView.class); } @Test @@ -51,7 +51,7 @@ public class EmbeddedVelocityViewResolverTests { EmbeddedVelocityViewResolver resolver = context .getBean(EmbeddedVelocityViewResolver.class); Object viewClass = ReflectionTestUtils.getField(resolver, "viewClass"); - assertEquals(EmbeddedVelocityToolboxView.class, viewClass); + assertThat(viewClass).isEqualTo(EmbeddedVelocityToolboxView.class); } private ApplicationContext loadContext(Class config) { diff --git a/spring-boot/src/test/java/org/springframework/boot/yaml/ArrayDocumentMatcherTests.java b/spring-boot/src/test/java/org/springframework/boot/yaml/ArrayDocumentMatcherTests.java index 8d0fc8234b..8ad0884ffb 100644 --- a/spring-boot/src/test/java/org/springframework/boot/yaml/ArrayDocumentMatcherTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/yaml/ArrayDocumentMatcherTests.java @@ -25,7 +25,7 @@ import org.springframework.beans.factory.config.YamlProcessor.MatchStatus; import org.springframework.core.io.ByteArrayResource; import org.springframework.core.io.support.PropertiesLoaderUtils; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link ArrayDocumentMatcher}. @@ -37,20 +37,22 @@ public class ArrayDocumentMatcherTests { @Test public void testMatchesSingleValue() throws IOException { ArrayDocumentMatcher matcher = new ArrayDocumentMatcher("foo", "bar"); - assertEquals(MatchStatus.FOUND, matcher.matches(getProperties("foo: bar"))); + assertThat(matcher.matches(getProperties("foo: bar"))) + .isEqualTo(MatchStatus.FOUND); } @Test public void testDoesNotMatchesIndexedArray() throws IOException { ArrayDocumentMatcher matcher = new ArrayDocumentMatcher("foo", "bar"); - assertEquals(MatchStatus.ABSTAIN, - matcher.matches(getProperties("foo[0]: bar\nfoo[1]: spam"))); + assertThat(matcher.matches(getProperties("foo[0]: bar\nfoo[1]: spam"))) + .isEqualTo(MatchStatus.ABSTAIN); } @Test public void testMatchesCommaSeparatedArray() throws IOException { ArrayDocumentMatcher matcher = new ArrayDocumentMatcher("foo", "bar"); - assertEquals(MatchStatus.FOUND, matcher.matches(getProperties("foo: bar,spam"))); + assertThat(matcher.matches(getProperties("foo: bar,spam"))) + .isEqualTo(MatchStatus.FOUND); } private Properties getProperties(String values) throws IOException {