From e19e3209d9fcb40f3ccb0485652e931977b13947 Mon Sep 17 00:00:00 2001 From: Phillip Webb Date: Sat, 6 Feb 2016 14:48:27 -0800 Subject: [PATCH 01/10] 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 { From a5ae81c1c195588d08d36b5a4c29a83d101e6f76 Mon Sep 17 00:00:00 2001 From: Phillip Webb Date: Sat, 6 Feb 2016 14:48:43 -0800 Subject: [PATCH 02/10] Use AssertJ in spring-boot-autoconfigure See gh-5083 --- .../AutoConfigurationPackagesTests.java | 13 +- .../AutoConfigurationReproTests.java | 6 +- .../AutoConfigurationSorterTests.java | 68 ++---- ...eAutoConfigurationImportSelectorTests.java | 66 +++--- ...urceAutoConfigurationIntegrationTests.java | 6 +- ...geSourceAutoConfigurationProfileTests.java | 6 +- .../MessageSourceAutoConfigurationTests.java | 46 ++-- ...ertyPlaceholderAutoConfigurationTests.java | 8 +- .../boot/autoconfigure/SpringJUnitTests.java | 7 +- ...icationAdminJmxAutoConfigurationTests.java | 15 +- .../amqp/RabbitAutoConfigurationTests.java | 70 +++--- .../amqp/RabbitPropertiesTests.java | 61 +++-- .../aop/AopAutoConfigurationTests.java | 15 +- .../batch/BatchAutoConfigurationTests.java | 71 +++--- .../JobExecutionExitCodeGeneratorTests.java | 8 +- .../JobLauncherCommandLineRunnerTests.java | 14 +- .../cache/CacheAutoConfigurationTests.java | 159 ++++++------- .../CassandraAutoConfigurationTests.java | 13 +- .../cloud/CloudAutoConfigurationTests.java | 5 +- .../condition/AllNestedConditionsTests.java | 11 +- .../condition/AnyNestedConditionTests.java | 11 +- .../ConditionEvaluationReportTests.java | 92 ++++---- .../condition/ConditionalOnBeanTests.java | 32 ++- .../condition/ConditionalOnClassTests.java | 20 +- .../ConditionalOnExpressionTests.java | 10 +- .../condition/ConditionalOnJavaTests.java | 30 +-- .../condition/ConditionalOnJndiTests.java | 14 +- .../ConditionalOnMissingBeanTests.java | 72 +++--- .../ConditionalOnMissingClassTests.java | 12 +- .../ConditionalOnNotWebApplicationTests.java | 10 +- .../condition/ConditionalOnPropertyTests.java | 53 +++-- .../condition/ConditionalOnResourceTests.java | 14 +- .../ConditionalOnSingleCandidateTests.java | 18 +- .../ConditionalOnWebApplicationTests.java | 10 +- .../condition/NoneNestedConditionsTests.java | 11 +- .../condition/ResourceConditionTests.java | 9 +- ...ationPropertiesAutoConfigurationTests.java | 7 +- ...tionTranslationAutoConfigurationTests.java | 11 +- .../CassandraDataAutoConfigurationTests.java | 5 +- ...draRepositoriesAutoConfigurationTests.java | 10 +- .../ElasticsearchAutoConfigurationTests.java | 29 ++- ...asticsearchDataAutoConfigurationTests.java | 15 +- ...rchRepositoriesAutoConfigurationTests.java | 10 +- ...JpaRepositoriesAutoConfigurationTests.java | 18 +- .../jpa/JpaWebAutoConfigurationTests.java | 12 +- ...ngoRepositoriesAutoConfigurationTests.java | 14 +- .../MongoDataAutoConfigurationTests.java | 21 +- ...ngoRepositoriesAutoConfigurationTests.java | 16 +- .../redis/RedisAutoConfigurationTests.java | 37 ++- ...positoryRestMvcAutoConfigurationTests.java | 60 +++-- ...olrRepositoriesAutoConfigurationTests.java | 17 +- .../SpringDataWebAutoConfigurationTests.java | 8 +- .../flyway/FlywayAutoConfigurationTests.java | 40 ++-- .../FreeMarkerAutoConfigurationTests.java | 40 ++-- ...rkerTemplateAvailabilityProviderTests.java | 24 +- .../GroovyTemplateAutoConfigurationTests.java | 46 ++-- .../gson/GsonAutoConfigurationTests.java | 4 +- .../h2/H2ConsoleAutoConfigurationTests.java | 29 +-- .../HypermediaAutoConfigurationTests.java | 27 +-- .../HazelcastAutoConfigurationTests.java | 32 ++- ...stJpaDependencyAutoConfigurationTests.java | 31 ++- .../IntegrationAutoConfigurationTests.java | 8 +- .../JacksonAutoConfigurationTests.java | 162 ++++++------- ...mmonsDbcpDataSourceConfigurationTests.java | 30 ++- .../DataSourceAutoConfigurationTests.java | 64 +++-- .../jdbc/DataSourceInitializerTests.java | 62 ++--- .../DataSourceJsonSerializationTests.java | 9 +- .../jdbc/DataSourcePropertiesTests.java | 38 +-- ...nsactionManagerAutoConfigurationTests.java | 30 ++- .../jdbc/DatabaseDriverTests.java | 11 +- .../EmbeddedDataSourceConfigurationTests.java | 4 +- .../jdbc/EmbeddedDatabaseConnectionTests.java | 15 +- .../HikariDataSourceConfigurationTests.java | 17 +- .../JndiDataSourceAutoConfigurationTests.java | 15 +- .../TomcatDataSourceConfigurationTests.java | 33 ++- .../XADataSourceAutoConfigurationTests.java | 16 +- .../AbstractDataSourcePoolMetadataTests.java | 26 ++- ...mmonsDbcp2DataSourcePoolMetadataTests.java | 14 +- ...ommonsDbcpDataSourcePoolMetadataTests.java | 13 +- .../DataSourcePoolMetadataProvidersTests.java | 12 +- .../HikariDataSourcePoolMetadataTests.java | 6 +- .../TomcatDataSourcePoolMetadataTests.java | 6 +- ...igurationCustomFilterContextPathTests.java | 4 +- ...utoConfigurationCustomFilterPathTests.java | 4 +- ...gurationCustomServletContextPathTests.java | 4 +- ...toConfigurationCustomServletPathTests.java | 4 +- ...toConfigurationDefaultFilterPathTests.java | 4 +- ...oConfigurationDefaultServletPathTests.java | 4 +- ...utoConfigurationServletContainerTests.java | 11 +- ...figurationWithoutApplicationPathTests.java | 4 +- .../jms/JmsAutoConfigurationTests.java | 158 ++++++------- .../autoconfigure/jms/JmsPropertiesTests.java | 11 +- .../ActiveMQAutoConfigurationTests.java | 22 +- .../jms/activemq/ActiveMQPropertiesTests.java | 20 +- .../ArtemisAutoConfigurationTests.java | 56 ++--- ...emisEmbeddedConfigurationFactoryTests.java | 18 +- .../HornetQAutoConfigurationTests.java | 52 ++--- ...netQEmbeddedConfigurationFactoryTests.java | 18 +- .../jmx/JmxAutoConfigurationTests.java | 15 +- .../jooq/JooqAutoConfigurationTests.java | 62 +++-- .../LiquibaseAutoConfigurationTests.java | 42 ++-- ...gurationReportLoggingInitializerTests.java | 29 +-- .../MailSenderAutoConfigurationTests.java | 45 ++-- ...ingViewResolverAutoConfigurationTests.java | 66 +++--- .../DeviceResolverAutoConfigurationTests.java | 15 +- .../SitePreferenceAutoConfigurationTests.java | 25 +- .../mongo/MongoAutoConfigurationTests.java | 12 +- .../mongo/MongoPropertiesTests.java | 25 +- .../EmbeddedMongoAutoConfigurationTests.java | 22 +- ...acheAutoConfigurationIntegrationTests.java | 6 +- .../MustacheStandaloneIntegrationTests.java | 21 +- .../web/MustacheViewResolverTests.java | 21 +- .../mustache/web/MustacheViewTests.java | 4 +- .../web/MustacheWebIntegrationTests.java | 10 +- .../AbstractJpaAutoConfigurationTests.java | 39 ++-- ...tomHibernateJpaAutoConfigurationTests.java | 10 +- .../HibernateJpaAutoConfigurationTests.java | 28 +-- .../ReactorAutoConfigurationTests.java | 7 +- .../SecurityAutoConfigurationTests.java | 86 ++++--- .../security/SecurityPropertiesTests.java | 43 ++-- ...ringBootWebSecurityConfigurationTests.java | 29 +-- .../oauth2/OAuth2AutoConfigurationTests.java | 94 ++++---- .../FixedAuthoritiesExtractorTests.java | 18 +- .../ResourceServerPropertiesTests.java | 7 +- ...ServerTokenServicesConfigurationTests.java | 30 ++- ...serInfoTokenServicesRefreshTokenTests.java | 15 +- .../resource/UserInfoTokenServicesTests.java | 11 +- .../SendGridAutoConfigurationTests.java | 25 +- .../SessionAutoConfigurationTests.java | 6 +- .../AbstractSocialAutoConfigurationTests.java | 12 +- .../FacebookAutoConfigurationTests.java | 4 +- .../LinkedInAutoConfigurationTests.java | 4 +- .../MultiApiAutoConfigurationTests.java | 20 +- .../social/TwitterAutoConfigurationTests.java | 4 +- .../template/ViewResolverPropertiesTests.java | 15 +- ...tAutoConfigurationImportSelectorTests.java | 5 +- .../ThymeleafAutoConfigurationTests.java | 41 ++-- ...leafTemplateAvailabilityProviderTests.java | 22 +- .../TransactionAutoConfigurationTests.java | 15 +- .../jta/JtaAutoConfigurationTests.java | 38 ++- .../VelocityAutoConfigurationTests.java | 57 ++--- ...cityTemplateAvailabilityProviderTests.java | 23 +- ...asicErrorControllerDirectMockMvcTests.java | 8 +- .../BasicErrorControllerIntegrationTests.java | 47 ++-- .../web/BasicErrorControllerMockMvcTests.java | 11 +- ...onditionalOnEnabledResourceChainTests.java | 13 +- .../web/DefaultErrorAttributesTests.java | 83 +++---- .../web/DefaultErrorViewIntegrationTests.java | 16 +- ...spatcherServletAutoConfigurationTests.java | 47 ++-- ...ervletContainerAutoConfigurationTests.java | 25 +- .../web/FilterOrderingIntegrationTests.java | 17 +- .../HttpEncodingAutoConfigurationTests.java | 14 +- ...ssageConvertersAutoConfigurationTests.java | 43 ++-- .../web/HttpMessageConvertersTests.java | 63 +++-- .../JspTemplateAvailabilityProviderTests.java | 9 +- .../web/MultipartAutoConfigurationTests.java | 76 +++--- ...cursivePropertyPlaceholderHelperTests.java | 7 +- .../RemappedErrorViewIntegrationTests.java | 10 +- .../web/ResourcePropertiesTests.java | 10 +- ...erverPropertiesAutoConfigurationTests.java | 21 +- .../web/ServerPropertiesTests.java | 83 ++++--- .../web/WebMvcAutoConfigurationTests.java | 221 ++++++++---------- .../WebSocketAutoConfigurationTests.java | 6 +- ...SocketMessagingAutoConfigurationTests.java | 12 +- 164 files changed, 2104 insertions(+), 2500 deletions(-) mode change 100755 => 100644 spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/template/ViewResolverPropertiesTests.java mode change 100755 => 100644 spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/JspTemplateAvailabilityProviderTests.java mode change 100755 => 100644 spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/ResourcePropertiesTests.java diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/AutoConfigurationPackagesTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/AutoConfigurationPackagesTests.java index 34882348a3..35c39cd687 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/AutoConfigurationPackagesTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/AutoConfigurationPackagesTests.java @@ -16,7 +16,6 @@ package org.springframework.boot.autoconfigure; -import java.util.Collections; import java.util.List; import org.junit.Rule; @@ -30,10 +29,7 @@ import org.springframework.context.annotation.AnnotationConfigApplicationContext import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.hasItems; -import static org.hamcrest.Matchers.hasSize; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link AutoConfigurationPackages}. @@ -51,8 +47,8 @@ public class AutoConfigurationPackagesTests { public void setAndGet() { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext( ConfigWithRegistrar.class); - assertThat(AutoConfigurationPackages.get(context.getBeanFactory()), - equalTo(Collections.singletonList(getClass().getPackage().getName()))); + assertThat(AutoConfigurationPackages.get(context.getBeanFactory())) + .containsExactly(getClass().getPackage().getName()); } @Test @@ -72,8 +68,7 @@ public class AutoConfigurationPackagesTests { List packages = AutoConfigurationPackages.get(context.getBeanFactory()); Package package1 = FirstConfiguration.class.getPackage(); Package package2 = SecondConfiguration.class.getPackage(); - assertThat(packages, hasItems(package1.getName(), package2.getName())); - assertThat(packages, hasSize(2)); + assertThat(packages).containsOnly(package1.getName(), package2.getName()); } @Configuration diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/AutoConfigurationReproTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/AutoConfigurationReproTests.java index f3d4a485a4..9490780120 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/AutoConfigurationReproTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/AutoConfigurationReproTests.java @@ -27,8 +27,7 @@ import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.ImportResource; import org.springframework.context.support.PropertySourcesPlaceholderConfigurer; -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. @@ -54,7 +53,7 @@ public class AutoConfigurationReproTests { ServerPropertiesAutoConfiguration.class); this.context = application.run("--server.port=0"); String bean = (String) this.context.getBean("earlyInit"); - assertThat(bean, equalTo("bucket")); + assertThat(bean).isEqualTo("bucket"); } @Configuration @@ -66,4 +65,5 @@ public class AutoConfigurationReproTests { public static class EarlyInitConfig { } + } diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/AutoConfigurationSorterTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/AutoConfigurationSorterTests.java index 5d57082407..6545344050 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/AutoConfigurationSorterTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/AutoConfigurationSorterTests.java @@ -16,13 +16,9 @@ package org.springframework.boot.autoconfigure; -import java.util.ArrayList; import java.util.Arrays; import java.util.List; -import org.hamcrest.Description; -import org.hamcrest.Matcher; -import org.hamcrest.core.IsEqual; import org.junit.Before; import org.junit.Rule; import org.junit.Test; @@ -31,7 +27,7 @@ import org.junit.rules.ExpectedException; import org.springframework.core.Ordered; import org.springframework.core.type.classreading.CachingMetadataReaderFactory; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link AutoConfigurationSorter}. @@ -68,39 +64,39 @@ public class AutoConfigurationSorterTests { public void byOrderAnnotation() throws Exception { List actual = this.sorter .getInPriorityOrder(Arrays.asList(LOWEST, HIGHEST)); - assertThat(actual, nameMatcher(HIGHEST, LOWEST)); + assertThat(actual).containsExactly(HIGHEST, LOWEST); } @Test public void byAutoConfigureAfter() throws Exception { List actual = this.sorter.getInPriorityOrder(Arrays.asList(A, B, C)); - assertThat(actual, nameMatcher(C, B, A)); + assertThat(actual).containsExactly(C, B, A); } @Test public void byAutoConfigureBefore() throws Exception { List actual = this.sorter.getInPriorityOrder(Arrays.asList(X, Y, Z)); - assertThat(actual, nameMatcher(Z, Y, X)); + assertThat(actual).containsExactly(Z, Y, X); } @Test public void byAutoConfigureAfterDoubles() throws Exception { List actual = this.sorter.getInPriorityOrder(Arrays.asList(A, B, C, E)); - assertThat(actual, nameMatcher(C, E, B, A)); + assertThat(actual).containsExactly(C, E, B, A); } @Test public void byAutoConfigureMixedBeforeAndAfter() throws Exception { List actual = this.sorter .getInPriorityOrder(Arrays.asList(A, B, C, W, X)); - assertThat(actual, nameMatcher(C, W, B, A, X)); + assertThat(actual).containsExactly(C, W, B, A, X); } @Test public void byAutoConfigureMixedBeforeAndAfterWithClassNames() throws Exception { List actual = this.sorter .getInPriorityOrder(Arrays.asList(A2, B, C, W2, X)); - assertThat(actual, nameMatcher(C, W2, B, A2, X)); + assertThat(actual).containsExactly(C, W2, B, A2, X); } @Test @@ -108,13 +104,13 @@ public class AutoConfigurationSorterTests { throws Exception { List actual = this.sorter .getInPriorityOrder(Arrays.asList(W, X, A, B, C)); - assertThat(actual, nameMatcher(C, W, B, A, X)); + assertThat(actual).containsExactly(C, W, B, A, X); } @Test public void byAutoConfigureAfterWithMissing() throws Exception { List actual = this.sorter.getInPriorityOrder(Arrays.asList(A, B)); - assertThat(actual, nameMatcher(B, A)); + assertThat(actual).containsExactly(B, A); } @Test @@ -124,87 +120,67 @@ public class AutoConfigurationSorterTests { this.sorter.getInPriorityOrder(Arrays.asList(A, B, C, D)); } - private Matcher> nameMatcher(String... names) { - - final List list = Arrays.asList(names); - - return new IsEqual>(list) { - - @Override - public void describeMismatch(Object item, Description description) { - @SuppressWarnings("unchecked") - List items = (List) item; - description.appendText("was ").appendValue(prettify(items)); - } - - @Override - public void describeTo(Description description) { - description.appendValue(prettify(list)); - } - - private String prettify(List items) { - List pretty = new ArrayList(); - for (String item : items) { - if (item.contains("$AutoConfigure")) { - item = item.substring(item.indexOf("$AutoConfigure") - + "$AutoConfigure".length()); - } - pretty.add(item); - } - return pretty.toString(); - } - }; - - } - @AutoConfigureOrder(Ordered.LOWEST_PRECEDENCE) public static class OrderLowest { + } @AutoConfigureOrder(Ordered.HIGHEST_PRECEDENCE) public static class OrderHighest { + } @AutoConfigureAfter(AutoConfigureB.class) public static class AutoConfigureA { + } @AutoConfigureAfter(name = "org.springframework.boot.autoconfigure.AutoConfigurationSorterTests$AutoConfigureB") public static class AutoConfigureA2 { + } @AutoConfigureAfter({ AutoConfigureC.class, AutoConfigureD.class, AutoConfigureE.class }) public static class AutoConfigureB { + } public static class AutoConfigureC { + } @AutoConfigureAfter(AutoConfigureA.class) public static class AutoConfigureD { + } public static class AutoConfigureE { + } @AutoConfigureBefore(AutoConfigureB.class) public static class AutoConfigureW { + } @AutoConfigureBefore(name = "org.springframework.boot.autoconfigure.AutoConfigurationSorterTests$AutoConfigureB") public static class AutoConfigureW2 { + } public static class AutoConfigureX { + } @AutoConfigureBefore(AutoConfigureX.class) public static class AutoConfigureY { + } @AutoConfigureBefore(AutoConfigureY.class) public static class AutoConfigureZ { + } } diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/EnableAutoConfigurationImportSelectorTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/EnableAutoConfigurationImportSelectorTests.java index 5640a2b2bb..b824ce5c3b 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/EnableAutoConfigurationImportSelectorTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/EnableAutoConfigurationImportSelectorTests.java @@ -37,12 +37,7 @@ import org.springframework.core.type.AnnotationMetadata; import org.springframework.mock.env.MockEnvironment; 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.hasSize; -import static org.hamcrest.Matchers.is; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.BDDMockito.given; /** @@ -77,13 +72,10 @@ public class EnableAutoConfigurationImportSelectorTests { public void importsAreSelected() { configureExclusions(new String[0], new String[0], new String[0]); String[] imports = this.importSelector.selectImports(this.annotationMetadata); - assertThat(imports.length, - is(equalTo(SpringFactoriesLoader - .loadFactoryNames(EnableAutoConfiguration.class, - getClass().getClassLoader()) - .size()))); - assertThat(ConditionEvaluationReport.get(this.beanFactory).getExclusions(), - hasSize(0)); + assertThat(imports).hasSameSizeAs(SpringFactoriesLoader.loadFactoryNames( + EnableAutoConfiguration.class, getClass().getClassLoader())); + assertThat(ConditionEvaluationReport.get(this.beanFactory).getExclusions()) + .isEmpty(); } @Test @@ -91,10 +83,9 @@ public class EnableAutoConfigurationImportSelectorTests { configureExclusions(new String[] { FreeMarkerAutoConfiguration.class.getName() }, new String[0], new String[0]); String[] imports = this.importSelector.selectImports(this.annotationMetadata); - assertThat(imports.length, - is(equalTo(getAutoConfigurationClassNames().size() - 1))); - assertThat(ConditionEvaluationReport.get(this.beanFactory).getExclusions(), - contains(FreeMarkerAutoConfiguration.class.getName())); + assertThat(imports).hasSize(getAutoConfigurationClassNames().size() - 1); + assertThat(ConditionEvaluationReport.get(this.beanFactory).getExclusions()) + .contains(FreeMarkerAutoConfiguration.class.getName()); } @Test @@ -103,10 +94,9 @@ public class EnableAutoConfigurationImportSelectorTests { new String[] { VelocityAutoConfiguration.class.getName() }, new String[0]); String[] imports = this.importSelector.selectImports(this.annotationMetadata); - assertThat(imports.length, - is(equalTo(getAutoConfigurationClassNames().size() - 1))); - assertThat(ConditionEvaluationReport.get(this.beanFactory).getExclusions(), - contains(VelocityAutoConfiguration.class.getName())); + assertThat(imports).hasSize(getAutoConfigurationClassNames().size() - 1); + assertThat(ConditionEvaluationReport.get(this.beanFactory).getExclusions()) + .contains(VelocityAutoConfiguration.class.getName()); } @Test @@ -114,10 +104,9 @@ public class EnableAutoConfigurationImportSelectorTests { configureExclusions(new String[0], new String[0], new String[] { FreeMarkerAutoConfiguration.class.getName() }); String[] imports = this.importSelector.selectImports(this.annotationMetadata); - assertThat(imports.length, - is(equalTo(getAutoConfigurationClassNames().size() - 1))); - assertThat(ConditionEvaluationReport.get(this.beanFactory).getExclusions(), - contains(FreeMarkerAutoConfiguration.class.getName())); + assertThat(imports).hasSize(getAutoConfigurationClassNames().size() - 1); + assertThat(ConditionEvaluationReport.get(this.beanFactory).getExclusions()) + .contains(FreeMarkerAutoConfiguration.class.getName()); } @Test @@ -126,11 +115,10 @@ public class EnableAutoConfigurationImportSelectorTests { new String[] { FreeMarkerAutoConfiguration.class.getName(), VelocityAutoConfiguration.class.getName() }); String[] imports = this.importSelector.selectImports(this.annotationMetadata); - assertThat(imports.length, - is(equalTo(getAutoConfigurationClassNames().size() - 2))); - assertThat(ConditionEvaluationReport.get(this.beanFactory).getExclusions(), - containsInAnyOrder(FreeMarkerAutoConfiguration.class.getName(), - VelocityAutoConfiguration.class.getName())); + assertThat(imports).hasSize(getAutoConfigurationClassNames().size() - 2); + assertThat(ConditionEvaluationReport.get(this.beanFactory).getExclusions()) + .contains(FreeMarkerAutoConfiguration.class.getName(), + VelocityAutoConfiguration.class.getName()); } @Test @@ -141,11 +129,10 @@ public class EnableAutoConfigurationImportSelectorTests { this.environment.setProperty("spring.autoconfigure.exclude[1]", VelocityAutoConfiguration.class.getName()); String[] imports = this.importSelector.selectImports(this.annotationMetadata); - assertThat(imports.length, - is(equalTo(getAutoConfigurationClassNames().size() - 2))); - assertThat(ConditionEvaluationReport.get(this.beanFactory).getExclusions(), - containsInAnyOrder(FreeMarkerAutoConfiguration.class.getName(), - VelocityAutoConfiguration.class.getName())); + assertThat(imports).hasSize(getAutoConfigurationClassNames().size() - 2); + assertThat(ConditionEvaluationReport.get(this.beanFactory).getExclusions()) + .contains(FreeMarkerAutoConfiguration.class.getName(), + VelocityAutoConfiguration.class.getName()); } @Test @@ -154,12 +141,11 @@ public class EnableAutoConfigurationImportSelectorTests { new String[] { FreeMarkerAutoConfiguration.class.getName() }, new String[] { ThymeleafAutoConfiguration.class.getName() }); String[] imports = this.importSelector.selectImports(this.annotationMetadata); - assertThat(imports.length, - is(equalTo(getAutoConfigurationClassNames().size() - 3))); - assertThat(ConditionEvaluationReport.get(this.beanFactory).getExclusions(), - containsInAnyOrder(FreeMarkerAutoConfiguration.class.getName(), + assertThat(imports).hasSize(getAutoConfigurationClassNames().size() - 3); + assertThat(ConditionEvaluationReport.get(this.beanFactory).getExclusions()) + .contains(FreeMarkerAutoConfiguration.class.getName(), VelocityAutoConfiguration.class.getName(), - ThymeleafAutoConfiguration.class.getName())); + ThymeleafAutoConfiguration.class.getName()); } private void configureExclusions(String[] classExclusion, String[] nameExclusion, diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/MessageSourceAutoConfigurationIntegrationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/MessageSourceAutoConfigurationIntegrationTests.java index 1fdff68289..0c4897a0c4 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/MessageSourceAutoConfigurationIntegrationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/MessageSourceAutoConfigurationIntegrationTests.java @@ -29,7 +29,7 @@ import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.Configuration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link MessageSourceAutoConfiguration}. @@ -47,8 +47,8 @@ public class MessageSourceAutoConfigurationIntegrationTests { @Test public void testMessageSourceFromPropertySourceAnnotation() throws Exception { - assertEquals("bar", - this.context.getMessage("foo", null, "Foo message", Locale.UK)); + assertThat(this.context.getMessage("foo", null, "Foo message", Locale.UK)) + .isEqualTo("bar"); } @Configuration diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/MessageSourceAutoConfigurationProfileTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/MessageSourceAutoConfigurationProfileTests.java index f62a36f9b5..5c3776f441 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/MessageSourceAutoConfigurationProfileTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/MessageSourceAutoConfigurationProfileTests.java @@ -29,7 +29,7 @@ import org.springframework.context.annotation.Configuration; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link MessageSourceAutoConfiguration}. @@ -47,8 +47,8 @@ public class MessageSourceAutoConfigurationProfileTests { @Test public void testMessageSourceFromPropertySourceAnnotation() throws Exception { - assertEquals("bar", - this.context.getMessage("foo", null, "Foo message", Locale.UK)); + assertThat(this.context.getMessage("foo", null, "Foo message", Locale.UK)) + .isEqualTo("bar"); } @Configuration diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/MessageSourceAutoConfigurationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/MessageSourceAutoConfigurationTests.java index 50662b0ad8..25e56f9b6c 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/MessageSourceAutoConfigurationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/MessageSourceAutoConfigurationTests.java @@ -32,9 +32,7 @@ import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.PropertySource; -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 MessageSourceAutoConfiguration}. @@ -57,38 +55,39 @@ public class MessageSourceAutoConfigurationTests { @Test public void testDefaultMessageSource() throws Exception { load(); - assertEquals("Foo message", - this.context.getMessage("foo", null, "Foo message", Locale.UK)); + assertThat(this.context.getMessage("foo", null, "Foo message", Locale.UK)) + .isEqualTo("Foo message"); } @Test public void testMessageSourceCreated() throws Exception { load("spring.messages.basename:test/messages"); - assertEquals("bar", - this.context.getMessage("foo", null, "Foo message", Locale.UK)); + assertThat(this.context.getMessage("foo", null, "Foo message", Locale.UK)) + .isEqualTo("bar"); } @Test public void testEncodingWorks() throws Exception { load("spring.messages.basename:test/swedish"); - assertEquals("Some text with some swedish öäå!", - this.context.getMessage("foo", null, "Foo message", Locale.UK)); + assertThat(this.context.getMessage("foo", null, "Foo message", Locale.UK)) + .isEqualTo("Some text with some swedish öäå!"); } @Test public void testMultipleMessageSourceCreated() throws Exception { load("spring.messages.basename:test/messages,test/messages2"); - assertEquals("bar", - this.context.getMessage("foo", null, "Foo message", Locale.UK)); - assertEquals("bar-bar", - this.context.getMessage("foo-foo", null, "Foo-Foo message", Locale.UK)); + assertThat(this.context.getMessage("foo", null, "Foo message", Locale.UK)) + .isEqualTo("bar"); + assertThat(this.context.getMessage("foo-foo", null, "Foo-Foo message", Locale.UK)) + .isEqualTo("bar-bar"); } @Test public void testBadEncoding() throws Exception { load("spring.messages.encoding:rubbish"); // Bad encoding just means the messages are ignored - assertEquals("blah", this.context.getMessage("foo", null, "blah", Locale.UK)); + assertThat(this.context.getMessage("foo", null, "blah", Locale.UK)) + .isEqualTo("blah"); } @Test @@ -98,24 +97,23 @@ public class MessageSourceAutoConfigurationTests { this.context.register(Config.class, MessageSourceAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); this.context.refresh(); - assertEquals("bar", - this.context.getMessage("foo", null, "Foo message", Locale.UK)); + assertThat(this.context.getMessage("foo", null, "Foo message", Locale.UK)) + .isEqualTo("bar"); } @Test public void testFallbackDefault() throws Exception { load("spring.messages.basename:test/messages"); - - assertTrue(this.context.getBean(MessageSourceAutoConfiguration.class) - .isFallbackToSystemLocale()); + assertThat(this.context.getBean(MessageSourceAutoConfiguration.class) + .isFallbackToSystemLocale()).isTrue(); } @Test public void testFallbackTurnOff() throws Exception { load("spring.messages.basename:test/messages", "spring.messages.fallback-to-system-locale:false"); - assertFalse(this.context.getBean(MessageSourceAutoConfiguration.class) - .isFallbackToSystemLocale()); + assertThat(this.context.getBean(MessageSourceAutoConfiguration.class) + .isFallbackToSystemLocale()).isFalse(); } @Test @@ -125,7 +123,7 @@ public class MessageSourceAutoConfigurationTests { MessageSourceAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); this.context.refresh(); - assertEquals("foo", this.context.getMessage("foo", null, null, null)); + assertThat(this.context.getMessage("foo", null, null, null)).isEqualTo("foo"); } @Test @@ -140,8 +138,8 @@ public class MessageSourceAutoConfigurationTests { this.context.register(MessageSourceAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); this.context.refresh(); - assertEquals("bar", - this.context.getMessage("foo", null, "Foo message", Locale.UK)); + assertThat(this.context.getMessage("foo", null, "Foo message", Locale.UK)) + .isEqualTo("bar"); } finally { parent.close(); diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/PropertyPlaceholderAutoConfigurationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/PropertyPlaceholderAutoConfigurationTests.java index 777e5b8dd6..b27b8c20a0 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/PropertyPlaceholderAutoConfigurationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/PropertyPlaceholderAutoConfigurationTests.java @@ -27,7 +27,7 @@ import org.springframework.context.annotation.Configuration; import org.springframework.context.support.PropertySourcesPlaceholderConfigurer; import org.springframework.util.StringUtils; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link PropertyPlaceholderAutoConfiguration}. @@ -51,7 +51,8 @@ public class PropertyPlaceholderAutoConfigurationTests { PlaceholderConfig.class); EnvironmentTestUtils.addEnvironment(this.context, "foo:two"); this.context.refresh(); - assertEquals("two", this.context.getBean(PlaceholderConfig.class).getFoo()); + assertThat(this.context.getBean(PlaceholderConfig.class).getFoo()) + .isEqualTo("two"); } @Test @@ -60,7 +61,8 @@ public class PropertyPlaceholderAutoConfigurationTests { PlaceholderConfig.class, PlaceholdersOverride.class); EnvironmentTestUtils.addEnvironment(this.context, "foo:two"); this.context.refresh(); - assertEquals("spam", this.context.getBean(PlaceholderConfig.class).getFoo()); + assertThat(this.context.getBean(PlaceholderConfig.class).getFoo()) + .isEqualTo("spam"); } @Configuration diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/SpringJUnitTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/SpringJUnitTests.java index f6e56f1a5b..114dd0ca02 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/SpringJUnitTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/SpringJUnitTests.java @@ -28,8 +28,7 @@ import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Dave Syer @@ -46,12 +45,12 @@ public class SpringJUnitTests { @Test public void testContextCreated() { - assertNotNull(this.context); + assertThat(this.context).isNotNull(); } @Test public void testContextInitialized() { - assertEquals("bucket", this.foo); + assertThat(this.foo).isEqualTo("bucket"); } @Configuration diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/admin/SpringApplicationAdminJmxAutoConfigurationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/admin/SpringApplicationAdminJmxAutoConfigurationTests.java index 7fdbb444d1..9a670b3664 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/admin/SpringApplicationAdminJmxAutoConfigurationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/admin/SpringApplicationAdminJmxAutoConfigurationTests.java @@ -40,9 +40,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.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.fail; /** @@ -90,7 +88,8 @@ public class SpringApplicationAdminJmxAutoConfigurationTests { load(ENABLE_ADMIN_PROP); ObjectName objectName = createDefaultObjectName(); ObjectInstance objectInstance = this.mBeanServer.getObjectInstance(objectName); - assertNotNull("Lifecycle bean should have been registered", objectInstance); + assertThat(objectInstance).as("Lifecycle bean should have been registered") + .isNotNull(); } @Test @@ -122,13 +121,13 @@ public class SpringApplicationAdminJmxAutoConfigurationTests { JmxAutoConfiguration.class, SpringApplicationAdminJmxAutoConfiguration.class) .run("--" + ENABLE_ADMIN_PROP, "--server.port=0"); - assertTrue(this.context instanceof EmbeddedWebApplicationContext); - assertEquals(true, this.mBeanServer.getAttribute(createDefaultObjectName(), - "EmbeddedWebApplication")); + assertThat(this.context).isInstanceOf(EmbeddedWebApplicationContext.class); + assertThat(this.mBeanServer.getAttribute(createDefaultObjectName(), + "EmbeddedWebApplication")).isEqualTo(Boolean.TRUE); int expected = ((EmbeddedWebApplicationContext) this.context) .getEmbeddedServletContainer().getPort(); String actual = getProperty(createDefaultObjectName(), "local.server.port"); - assertEquals(String.valueOf(expected), actual); + assertThat(actual).isEqualTo(String.valueOf(expected)); } private ObjectName createDefaultObjectName() { diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/amqp/RabbitAutoConfigurationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/amqp/RabbitAutoConfigurationTests.java index 209570cec2..fda5e22b9a 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/amqp/RabbitAutoConfigurationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/amqp/RabbitAutoConfigurationTests.java @@ -43,9 +43,7 @@ import org.springframework.context.annotation.AnnotationConfigApplicationContext import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; -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; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; @@ -78,12 +76,12 @@ public class RabbitAutoConfigurationTests { CachingConnectionFactory connectionFactory = this.context .getBean(CachingConnectionFactory.class); RabbitAdmin amqpAdmin = this.context.getBean(RabbitAdmin.class); - assertEquals(connectionFactory, rabbitTemplate.getConnectionFactory()); - assertEquals(rabbitTemplate, messagingTemplate.getRabbitTemplate()); - assertNotNull(amqpAdmin); - assertEquals("localhost", connectionFactory.getHost()); - assertTrue("Listener container factory should be created by default", - this.context.containsBean("rabbitListenerContainerFactory")); + assertThat(rabbitTemplate.getConnectionFactory()).isEqualTo(connectionFactory); + assertThat(messagingTemplate.getRabbitTemplate()).isEqualTo(rabbitTemplate); + assertThat(amqpAdmin).isNotNull(); + assertThat(connectionFactory.getHost()).isEqualTo("localhost"); + assertThat(this.context.containsBean("rabbitListenerContainerFactory")) + .as("Listener container factory should be created by default").isTrue(); } @Test @@ -93,9 +91,9 @@ public class RabbitAutoConfigurationTests { "spring.rabbitmq.password:secret", "spring.rabbitmq.virtual_host:/vhost"); CachingConnectionFactory connectionFactory = this.context .getBean(CachingConnectionFactory.class); - assertEquals("remote-server", connectionFactory.getHost()); - assertEquals(9000, connectionFactory.getPort()); - assertEquals("/vhost", connectionFactory.getVirtualHost()); + assertThat(connectionFactory.getHost()).isEqualTo("remote-server"); + assertThat(connectionFactory.getPort()).isEqualTo(9000); + assertThat(connectionFactory.getVirtualHost()).isEqualTo("/vhost"); } @Test @@ -103,7 +101,7 @@ public class RabbitAutoConfigurationTests { load(TestConfiguration.class, "spring.rabbitmq.virtual_host:"); CachingConnectionFactory connectionFactory = this.context .getBean(CachingConnectionFactory.class); - assertEquals("/", connectionFactory.getVirtualHost()); + assertThat(connectionFactory.getVirtualHost()).isEqualTo("/"); } @Test @@ -111,7 +109,7 @@ public class RabbitAutoConfigurationTests { load(TestConfiguration.class, "spring.rabbitmq.virtual_host:foo"); CachingConnectionFactory connectionFactory = this.context .getBean(CachingConnectionFactory.class); - assertEquals("foo", connectionFactory.getVirtualHost()); + assertThat(connectionFactory.getVirtualHost()).isEqualTo("foo"); } @Test @@ -119,7 +117,7 @@ public class RabbitAutoConfigurationTests { load(TestConfiguration.class, "spring.rabbitmq.virtual_host:///foo"); CachingConnectionFactory connectionFactory = this.context .getBean(CachingConnectionFactory.class); - assertEquals("///foo", connectionFactory.getVirtualHost()); + assertThat(connectionFactory.getVirtualHost()).isEqualTo("///foo"); } @Test @@ -127,7 +125,7 @@ public class RabbitAutoConfigurationTests { load(TestConfiguration.class, "spring.rabbitmq.virtual_host:/"); CachingConnectionFactory connectionFactory = this.context .getBean(CachingConnectionFactory.class); - assertEquals("/", connectionFactory.getVirtualHost()); + assertThat(connectionFactory.getVirtualHost()).isEqualTo("/"); } @Test @@ -136,17 +134,17 @@ public class RabbitAutoConfigurationTests { RabbitTemplate rabbitTemplate = this.context.getBean(RabbitTemplate.class); CachingConnectionFactory connectionFactory = this.context .getBean(CachingConnectionFactory.class); - assertEquals(rabbitTemplate.getConnectionFactory(), connectionFactory); - assertEquals("otherserver", connectionFactory.getHost()); - assertEquals(8001, connectionFactory.getPort()); + assertThat(connectionFactory).isEqualTo(rabbitTemplate.getConnectionFactory()); + assertThat(connectionFactory.getHost()).isEqualTo("otherserver"); + assertThat(connectionFactory.getPort()).isEqualTo(8001); } @Test public void testRabbitTemplateBackOff() { load(TestConfiguration3.class); RabbitTemplate rabbitTemplate = this.context.getBean(RabbitTemplate.class); - assertEquals(this.context.getBean("testMessageConverter"), - rabbitTemplate.getMessageConverter()); + assertThat(rabbitTemplate.getMessageConverter()) + .isEqualTo(this.context.getBean("testMessageConverter")); } @Test @@ -154,7 +152,7 @@ public class RabbitAutoConfigurationTests { load(TestConfiguration4.class); RabbitMessagingTemplate messagingTemplate = this.context .getBean(RabbitMessagingTemplate.class); - assertEquals("fooBar", messagingTemplate.getDefaultDestination()); + assertThat(messagingTemplate.getDefaultDestination()).isEqualTo("fooBar"); } @Test @@ -173,8 +171,8 @@ public class RabbitAutoConfigurationTests { RabbitListenerContainerFactory rabbitListenerContainerFactory = this.context .getBean("rabbitListenerContainerFactory", RabbitListenerContainerFactory.class); - assertEquals(SimpleRabbitListenerContainerFactory.class, - rabbitListenerContainerFactory.getClass()); + assertThat(rabbitListenerContainerFactory.getClass()) + .isEqualTo(SimpleRabbitListenerContainerFactory.class); } @Test @@ -199,12 +197,13 @@ public class RabbitAutoConfigurationTests { .getBean("rabbitListenerContainerFactory", SimpleRabbitListenerContainerFactory.class); DirectFieldAccessor dfa = new DirectFieldAccessor(rabbitListenerContainerFactory); - assertEquals(false, dfa.getPropertyValue("autoStartup")); - assertEquals(AcknowledgeMode.MANUAL, dfa.getPropertyValue("acknowledgeMode")); - assertEquals(5, dfa.getPropertyValue("concurrentConsumers")); - assertEquals(10, dfa.getPropertyValue("maxConcurrentConsumers")); - assertEquals(40, dfa.getPropertyValue("prefetchCount")); - assertEquals(20, dfa.getPropertyValue("txSize")); + assertThat(dfa.getPropertyValue("autoStartup")).isEqualTo(Boolean.FALSE); + assertThat(dfa.getPropertyValue("acknowledgeMode")) + .isEqualTo(AcknowledgeMode.MANUAL); + assertThat(dfa.getPropertyValue("concurrentConsumers")).isEqualTo(5); + assertThat(dfa.getPropertyValue("maxConcurrentConsumers")).isEqualTo(10); + assertThat(dfa.getPropertyValue("prefetchCount")).isEqualTo(40); + assertThat(dfa.getPropertyValue("txSize")).isEqualTo(20); } @Test @@ -221,23 +220,24 @@ public class RabbitAutoConfigurationTests { public void customizeRequestedHeartBeat() { load(TestConfiguration.class, "spring.rabbitmq.requestedHeartbeat:20"); com.rabbitmq.client.ConnectionFactory rabbitConnectionFactory = getTargetConnectionFactory(); - assertEquals(20, rabbitConnectionFactory.getRequestedHeartbeat()); + assertThat(rabbitConnectionFactory.getRequestedHeartbeat()).isEqualTo(20); } @Test public void noSslByDefault() { load(TestConfiguration.class); com.rabbitmq.client.ConnectionFactory rabbitConnectionFactory = getTargetConnectionFactory(); - assertEquals("Must use default SocketFactory", SocketFactory.getDefault(), - rabbitConnectionFactory.getSocketFactory()); + assertThat(rabbitConnectionFactory.getSocketFactory()) + .as("Must use default SocketFactory") + .isEqualTo(SocketFactory.getDefault()); } @Test public void enableSsl() { load(TestConfiguration.class, "spring.rabbitmq.ssl.enabled:true"); com.rabbitmq.client.ConnectionFactory rabbitConnectionFactory = getTargetConnectionFactory(); - assertTrue("SocketFactory must use SSL", - rabbitConnectionFactory.getSocketFactory() instanceof SSLSocketFactory); + assertThat(rabbitConnectionFactory.getSocketFactory()) + .as("SocketFactory must use SSL").isInstanceOf(SSLSocketFactory.class); } @Test diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/amqp/RabbitPropertiesTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/amqp/RabbitPropertiesTests.java index f5c0df981a..b33869d85f 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/amqp/RabbitPropertiesTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/amqp/RabbitPropertiesTests.java @@ -18,8 +18,7 @@ package org.springframework.boot.autoconfigure.amqp; import org.junit.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link RabbitProperties}. @@ -33,90 +32,90 @@ public class RabbitPropertiesTests { @Test public void addressesNotSet() { - assertEquals("localhost", this.properties.getHost()); - assertEquals(5672, this.properties.getPort()); + assertThat(this.properties.getHost()).isEqualTo("localhost"); + assertThat(this.properties.getPort()).isEqualTo(5672); } @Test public void addressesSingleValued() { this.properties.setAddresses("myhost:9999"); - assertEquals("myhost", this.properties.getHost()); - assertEquals(9999, this.properties.getPort()); + assertThat(this.properties.getHost()).isEqualTo("myhost"); + assertThat(this.properties.getPort()).isEqualTo(9999); } @Test public void addressesDoubleValued() { this.properties.setAddresses("myhost:9999,otherhost:1111"); - assertNull(this.properties.getHost()); - assertEquals(9999, this.properties.getPort()); + assertThat(this.properties.getHost()).isNull(); + assertThat(this.properties.getPort()).isEqualTo(9999); } @Test public void addressesDoubleValuedWithCredentials() { this.properties.setAddresses("myhost:9999,root:password@otherhost:1111/host"); - assertNull(this.properties.getHost()); - assertEquals(9999, this.properties.getPort()); - assertEquals("root", this.properties.getUsername()); - assertEquals("host", this.properties.getVirtualHost()); + assertThat(this.properties.getHost()).isNull(); + assertThat(this.properties.getPort()).isEqualTo(9999); + assertThat(this.properties.getUsername()).isEqualTo("root"); + assertThat(this.properties.getVirtualHost()).isEqualTo("host"); } @Test public void addressesDoubleValuedPreservesOrder() { this.properties.setAddresses("myhost:9999,ahost:1111/host"); - assertNull(this.properties.getHost()); - assertEquals("myhost:9999,ahost:1111", this.properties.getAddresses()); + assertThat(this.properties.getHost()).isNull(); + assertThat(this.properties.getAddresses()).isEqualTo("myhost:9999,ahost:1111"); } @Test public void addressesSingleValuedWithCredentials() { this.properties.setAddresses("amqp://root:password@otherhost:1111/host"); - assertEquals("otherhost", this.properties.getHost()); - assertEquals(1111, this.properties.getPort()); - assertEquals("root", this.properties.getUsername()); - assertEquals("host", this.properties.getVirtualHost()); + assertThat(this.properties.getHost()).isEqualTo("otherhost"); + assertThat(this.properties.getPort()).isEqualTo(1111); + assertThat(this.properties.getUsername()).isEqualTo("root"); + assertThat(this.properties.getVirtualHost()).isEqualTo("host"); } @Test public void addressesSingleValuedWithCredentialsDefaultPort() { this.properties.setAddresses("amqp://root:password@lemur.cloudamqp.com/host"); - assertEquals("lemur.cloudamqp.com", this.properties.getHost()); - assertEquals(5672, this.properties.getPort()); - assertEquals("root", this.properties.getUsername()); - assertEquals("host", this.properties.getVirtualHost()); - assertEquals("lemur.cloudamqp.com:5672", this.properties.getAddresses()); + assertThat(this.properties.getHost()).isEqualTo("lemur.cloudamqp.com"); + assertThat(this.properties.getPort()).isEqualTo(5672); + assertThat(this.properties.getUsername()).isEqualTo("root"); + assertThat(this.properties.getVirtualHost()).isEqualTo("host"); + assertThat(this.properties.getAddresses()).isEqualTo("lemur.cloudamqp.com:5672"); } @Test public void addressWithTrailingSlash() { this.properties.setAddresses("amqp://root:password@otherhost:1111/"); - assertEquals("otherhost", this.properties.getHost()); - assertEquals(1111, this.properties.getPort()); - assertEquals("root", this.properties.getUsername()); - assertEquals("/", this.properties.getVirtualHost()); + assertThat(this.properties.getHost()).isEqualTo("otherhost"); + assertThat(this.properties.getPort()).isEqualTo(1111); + assertThat(this.properties.getUsername()).isEqualTo("root"); + assertThat(this.properties.getVirtualHost()).isEqualTo("/"); } @Test public void testDefaultVirtualHost() { this.properties.setVirtualHost("/"); - assertEquals("/", this.properties.getVirtualHost()); + assertThat(this.properties.getVirtualHost()).isEqualTo("/"); } @Test public void testEmptyVirtualHost() { this.properties.setVirtualHost(""); - assertEquals("/", this.properties.getVirtualHost()); + assertThat(this.properties.getVirtualHost()).isEqualTo("/"); } @Test public void testCustomVirtualHost() { this.properties.setVirtualHost("myvHost"); - assertEquals("myvHost", this.properties.getVirtualHost()); + assertThat(this.properties.getVirtualHost()).isEqualTo("myvHost"); } @Test public void testCustomFalsyVirtualHost() { this.properties.setVirtualHost("/myvHost"); - assertEquals("/myvHost", this.properties.getVirtualHost()); + assertThat(this.properties.getVirtualHost()).isEqualTo("/myvHost"); } } diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/aop/AopAutoConfigurationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/aop/AopAutoConfigurationTests.java index 0247a74280..ad276ad12d 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/aop/AopAutoConfigurationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/aop/AopAutoConfigurationTests.java @@ -26,8 +26,7 @@ import org.springframework.context.annotation.AnnotationConfigApplicationContext import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link AopAutoConfiguration}. @@ -46,10 +45,10 @@ public class AopAutoConfigurationTests { EnvironmentTestUtils.addEnvironment(this.context, "spring.aop.auto:false"); this.context.refresh(); TestAspect aspect = this.context.getBean(TestAspect.class); - assertFalse(aspect.isCalled()); + assertThat(aspect.isCalled()).isFalse(); TestBean bean = this.context.getBean(TestBean.class); bean.foo(); - assertFalse(aspect.isCalled()); + assertThat(aspect.isCalled()).isFalse(); } @Test @@ -61,10 +60,10 @@ public class AopAutoConfigurationTests { "spring.aop.proxyTargetClass:true"); this.context.refresh(); TestAspect aspect = this.context.getBean(TestAspect.class); - assertFalse(aspect.isCalled()); + assertThat(aspect.isCalled()).isFalse(); TestBean bean = this.context.getBean(TestBean.class); bean.foo(); - assertTrue(aspect.isCalled()); + assertThat(aspect.isCalled()).isTrue(); } @Test @@ -76,10 +75,10 @@ public class AopAutoConfigurationTests { "spring.aop.proxyTargetClass:false"); this.context.refresh(); TestAspect aspect = this.context.getBean(TestAspect.class); - assertFalse(aspect.isCalled()); + assertThat(aspect.isCalled()).isFalse(); TestInterface bean = this.context.getBean(TestInterface.class); bean.foo(); - assertTrue(aspect.isCalled()); + assertThat(aspect.isCalled()).isTrue(); } @Configuration diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/batch/BatchAutoConfigurationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/batch/BatchAutoConfigurationTests.java index bc994d1042..ec2e07636a 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/batch/BatchAutoConfigurationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/batch/BatchAutoConfigurationTests.java @@ -60,10 +60,7 @@ import org.springframework.jdbc.BadSqlGrammarException; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.transaction.PlatformTransactionManager; -import static org.junit.Assert.assertEquals; -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 BatchAutoConfiguration}. @@ -92,10 +89,10 @@ public class BatchAutoConfigurationTests { EmbeddedDataSourceConfiguration.class, BatchAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); this.context.refresh(); - assertNotNull(this.context.getBean(JobLauncher.class)); - assertNotNull(this.context.getBean(JobExplorer.class)); - assertEquals(0, new JdbcTemplate(this.context.getBean(DataSource.class)) - .queryForList("select * from BATCH_JOB_EXECUTION").size()); + assertThat(this.context.getBean(JobLauncher.class)).isNotNull(); + assertThat(this.context.getBean(JobExplorer.class)).isNotNull(); + assertThat(new JdbcTemplate(this.context.getBean(DataSource.class)) + .queryForList("select * from BATCH_JOB_EXECUTION")).isEmpty(); } @Test @@ -104,10 +101,10 @@ public class BatchAutoConfigurationTests { this.context.register(TestCustomConfiguration.class, BatchAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); this.context.refresh(); - assertNotNull(this.context.getBean(JobLauncher.class)); + assertThat(this.context.getBean(JobLauncher.class)).isNotNull(); JobExplorer explorer = this.context.getBean(JobExplorer.class); - assertNotNull(explorer); - assertEquals(0, explorer.getJobInstances("job", 0, 100).size()); + assertThat(explorer).isNotNull(); + assertThat(explorer.getJobInstances("job", 0, 100)).isEmpty(); } @Test @@ -117,8 +114,10 @@ public class BatchAutoConfigurationTests { EmbeddedDataSourceConfiguration.class, PropertyPlaceholderAutoConfiguration.class); this.context.refresh(); - assertEquals(0, this.context.getBeanNamesForType(JobLauncher.class).length); - assertEquals(0, this.context.getBeanNamesForType(JobRepository.class).length); + assertThat(this.context.getBeanNamesForType(JobLauncher.class).length) + .isEqualTo(0); + assertThat(this.context.getBeanNamesForType(JobRepository.class).length) + .isEqualTo(0); } @Test @@ -128,10 +127,10 @@ public class BatchAutoConfigurationTests { EmbeddedDataSourceConfiguration.class, BatchAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); this.context.refresh(); - assertNotNull(this.context.getBean(JobLauncher.class)); + assertThat(this.context.getBean(JobLauncher.class)).isNotNull(); this.context.getBean(JobLauncherCommandLineRunner.class).run(); - assertNotNull(this.context.getBean(JobRepository.class).getLastJobExecution("job", - new JobParameters())); + assertThat(this.context.getBean(JobRepository.class).getLastJobExecution("job", + new JobParameters())).isNotNull(); } @Test @@ -144,10 +143,10 @@ public class BatchAutoConfigurationTests { PropertyPlaceholderAutoConfiguration.class); this.context.refresh(); JobRepository repository = this.context.getBean(JobRepository.class); - assertNotNull(this.context.getBean(JobLauncher.class)); + assertThat(this.context.getBean(JobLauncher.class)).isNotNull(); this.context.getBean(JobLauncherCommandLineRunner.class).run(); - assertNotNull(repository.getLastJobExecution("discreteRegisteredJob", - new JobParameters())); + assertThat(repository.getLastJobExecution("discreteRegisteredJob", + new JobParameters())).isNotNull(); } @Test @@ -159,10 +158,11 @@ public class BatchAutoConfigurationTests { EmbeddedDataSourceConfiguration.class, BatchAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); this.context.refresh(); - assertNotNull(this.context.getBean(JobLauncher.class)); + assertThat(this.context.getBean(JobLauncher.class)).isNotNull(); this.context.getBean(JobLauncherCommandLineRunner.class).run(); - assertNotNull(this.context.getBean(JobRepository.class) - .getLastJobExecution("discreteLocalJob", new JobParameters())); + assertThat(this.context.getBean(JobRepository.class) + .getLastJobExecution("discreteLocalJob", new JobParameters())) + .isNotNull(); } @Test @@ -174,8 +174,9 @@ public class BatchAutoConfigurationTests { EmbeddedDataSourceConfiguration.class, BatchAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); this.context.refresh(); - assertNotNull(this.context.getBean(JobLauncher.class)); - assertEquals(0, this.context.getBeanNamesForType(CommandLineRunner.class).length); + assertThat(this.context.getBean(JobLauncher.class)).isNotNull(); + assertThat(this.context.getBeanNamesForType(CommandLineRunner.class).length) + .isEqualTo(0); } @Test @@ -188,7 +189,7 @@ public class BatchAutoConfigurationTests { EmbeddedDataSourceConfiguration.class, BatchAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); this.context.refresh(); - assertNotNull(this.context.getBean(JobLauncher.class)); + assertThat(this.context.getBean(JobLauncher.class)).isNotNull(); this.expected.expect(BadSqlGrammarException.class); new JdbcTemplate(this.context.getBean(DataSource.class)) .queryForList("select * from BATCH_JOB_EXECUTION"); @@ -206,11 +207,12 @@ public class BatchAutoConfigurationTests { PlatformTransactionManager transactionManager = this.context .getBean(PlatformTransactionManager.class); // It's a lazy proxy, but it does render its target if you ask for toString(): - assertTrue(transactionManager.toString().contains("JpaTransactionManager")); - assertNotNull(this.context.getBean(EntityManagerFactory.class)); + assertThat(transactionManager.toString().contains("JpaTransactionManager")) + .isTrue(); + assertThat(this.context.getBean(EntityManagerFactory.class)).isNotNull(); // Ensure the JobRepository can be used (no problem with isolation level) - assertNull(this.context.getBean(JobRepository.class).getLastJobExecution("job", - new JobParameters())); + assertThat(this.context.getBean(JobRepository.class).getLastJobExecution("job", + new JobParameters())).isNull(); } @Test @@ -225,13 +227,14 @@ public class BatchAutoConfigurationTests { HibernateJpaAutoConfiguration.class, BatchAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); this.context.refresh(); - assertNotNull(this.context.getBean(JobLauncher.class)); - assertEquals(0, new JdbcTemplate(this.context.getBean(DataSource.class)) - .queryForList("select * from PREFIX_JOB_EXECUTION").size()); + assertThat(this.context.getBean(JobLauncher.class)).isNotNull(); + assertThat(new JdbcTemplate(this.context.getBean(DataSource.class)) + .queryForList("select * from PREFIX_JOB_EXECUTION")).isEmpty(); JobExplorer jobExplorer = this.context.getBean(JobExplorer.class); - assertEquals(0, jobExplorer.findRunningJobExecutions("test").size()); + assertThat(jobExplorer.findRunningJobExecutions("test")).isEmpty(); JobRepository jobRepository = this.context.getBean(JobRepository.class); - assertNull(jobRepository.getLastJobExecution("test", new JobParameters())); + assertThat(jobRepository.getLastJobExecution("test", new JobParameters())) + .isNull(); } @Configuration diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/batch/JobExecutionExitCodeGeneratorTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/batch/JobExecutionExitCodeGeneratorTests.java index c42186d31c..d4a4484f43 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/batch/JobExecutionExitCodeGeneratorTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/batch/JobExecutionExitCodeGeneratorTests.java @@ -21,7 +21,7 @@ import org.junit.Test; import org.springframework.batch.core.BatchStatus; import org.springframework.batch.core.JobExecution; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link JobExecutionExitCodeGenerator}. @@ -35,7 +35,7 @@ public class JobExecutionExitCodeGeneratorTests { @Test public void testExitCodeForRunning() { this.generator.onApplicationEvent(new JobExecutionEvent(new JobExecution(0L))); - assertEquals(1, this.generator.getExitCode()); + assertThat(this.generator.getExitCode()).isEqualTo(1); } @Test @@ -43,7 +43,7 @@ public class JobExecutionExitCodeGeneratorTests { JobExecution execution = new JobExecution(0L); execution.setStatus(BatchStatus.COMPLETED); this.generator.onApplicationEvent(new JobExecutionEvent(execution)); - assertEquals(0, this.generator.getExitCode()); + assertThat(this.generator.getExitCode()).isEqualTo(0); } @Test @@ -51,7 +51,7 @@ public class JobExecutionExitCodeGeneratorTests { JobExecution execution = new JobExecution(0L); execution.setStatus(BatchStatus.FAILED); this.generator.onApplicationEvent(new JobExecutionEvent(execution)); - assertEquals(5, this.generator.getExitCode()); + assertThat(this.generator.getExitCode()).isEqualTo(5); } } diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/batch/JobLauncherCommandLineRunnerTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/batch/JobLauncherCommandLineRunnerTests.java index d1c2eb3856..ab5fd2e8e5 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/batch/JobLauncherCommandLineRunnerTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/batch/JobLauncherCommandLineRunnerTests.java @@ -44,7 +44,7 @@ import org.springframework.context.annotation.Configuration; import org.springframework.core.task.SyncTaskExecutor; import org.springframework.transaction.PlatformTransactionManager; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link JobLauncherCommandLineRunner}. @@ -97,10 +97,10 @@ public class JobLauncherCommandLineRunnerTests { @Test public void basicExecution() throws Exception { this.runner.execute(this.job, new JobParameters()); - assertEquals(1, this.jobExplorer.getJobInstances("job", 0, 100).size()); + assertThat(this.jobExplorer.getJobInstances("job", 0, 100)).hasSize(1); this.runner.execute(this.job, new JobParametersBuilder().addLong("id", 1L).toJobParameters()); - assertEquals(2, this.jobExplorer.getJobInstances("job", 0, 100).size()); + assertThat(this.jobExplorer.getJobInstances("job", 0, 100)).hasSize(2); } @Test @@ -109,7 +109,7 @@ public class JobLauncherCommandLineRunnerTests { .incrementer(new RunIdIncrementer()).build(); this.runner.execute(this.job, new JobParameters()); this.runner.execute(this.job, new JobParameters()); - assertEquals(2, this.jobExplorer.getJobInstances("job", 0, 100).size()); + assertThat(this.jobExplorer.getJobInstances("job", 0, 100)).hasSize(2); } @Test @@ -124,7 +124,7 @@ public class JobLauncherCommandLineRunnerTests { }).build()).incrementer(new RunIdIncrementer()).build(); this.runner.execute(this.job, new JobParameters()); this.runner.execute(this.job, new JobParameters()); - assertEquals(1, this.jobExplorer.getJobInstances("job", 0, 100).size()); + assertThat(this.jobExplorer.getJobInstances("job", 0, 100)).hasSize(1); } @Test @@ -141,7 +141,7 @@ public class JobLauncherCommandLineRunnerTests { this.runner.execute(this.job, new JobParameters()); // A failed job that is not restartable does not re-use the job params of // the last execution, but creates a new job instance when running it again. - assertEquals(2, this.jobExplorer.getJobInstances("job", 0, 100).size()); + assertThat(this.jobExplorer.getJobInstances("job", 0, 100)).hasSize(2); } @Test @@ -158,7 +158,7 @@ public class JobLauncherCommandLineRunnerTests { .addLong("foo", 2L, false).toJobParameters(); this.runner.execute(this.job, jobParameters); this.runner.execute(this.job, jobParameters); - assertEquals(1, this.jobExplorer.getJobInstances("job", 0, 100).size()); + assertThat(this.jobExplorer.getJobInstances("job", 0, 100)).hasSize(1); } @Configuration diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/cache/CacheAutoConfigurationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/cache/CacheAutoConfigurationTests.java index 79403b0deb..d67b095895 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/cache/CacheAutoConfigurationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/cache/CacheAutoConfigurationTests.java @@ -68,14 +68,7 @@ import org.springframework.core.io.Resource; import org.springframework.data.redis.cache.RedisCacheManager; import org.springframework.data.redis.core.RedisTemplate; -import static org.hamcrest.CoreMatchers.equalTo; -import static org.hamcrest.CoreMatchers.instanceOf; -import static org.hamcrest.Matchers.contains; -import static org.hamcrest.Matchers.containsInAnyOrder; -import static org.hamcrest.Matchers.empty; -import static org.hamcrest.Matchers.hasSize; -import static org.hamcrest.Matchers.not; -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.times; @@ -113,8 +106,7 @@ public class CacheAutoConfigurationTests { load(CustomCacheManagerConfiguration.class); ConcurrentMapCacheManager cacheManager = validateCacheManager( ConcurrentMapCacheManager.class); - assertThat(cacheManager.getCacheNames(), contains("custom1")); - assertThat(cacheManager.getCacheNames(), hasSize(1)); + assertThat(cacheManager.getCacheNames()).containsOnly("custom1"); } @Test @@ -122,8 +114,7 @@ public class CacheAutoConfigurationTests { load(CustomCacheManagerFromSupportConfiguration.class); ConcurrentMapCacheManager cacheManager = validateCacheManager( ConcurrentMapCacheManager.class); - assertThat(cacheManager.getCacheNames(), contains("custom1")); - assertThat(cacheManager.getCacheNames(), hasSize(1)); + assertThat(cacheManager.getCacheNames()).containsOnly("custom1"); } @Test @@ -146,7 +137,7 @@ public class CacheAutoConfigurationTests { load(DefaultCacheConfiguration.class, "spring.cache.type=simple"); ConcurrentMapCacheManager cacheManager = validateCacheManager( ConcurrentMapCacheManager.class); - assertThat(cacheManager.getCacheNames(), empty()); + assertThat(cacheManager.getCacheNames()).isEmpty(); } @Test @@ -155,19 +146,18 @@ public class CacheAutoConfigurationTests { "spring.cache.cacheNames[0]=foo", "spring.cache.cacheNames[1]=bar"); ConcurrentMapCacheManager cacheManager = validateCacheManager( ConcurrentMapCacheManager.class); - assertThat(cacheManager.getCacheNames(), containsInAnyOrder("foo", "bar")); - assertThat(cacheManager.getCacheNames(), hasSize(2)); + assertThat(cacheManager.getCacheNames()).containsOnly("foo", "bar"); } @Test public void genericCacheWithCaches() { load(GenericCacheConfiguration.class); SimpleCacheManager cacheManager = validateCacheManager(SimpleCacheManager.class); - assertThat(cacheManager.getCache("first"), - equalTo(this.context.getBean("firstCache"))); - assertThat(cacheManager.getCache("second"), - equalTo(this.context.getBean("secondCache"))); - assertThat(cacheManager.getCacheNames(), hasSize(2)); + assertThat(cacheManager.getCache("first")) + .isEqualTo(this.context.getBean("firstCache")); + assertThat(cacheManager.getCache("second")) + .isEqualTo(this.context.getBean("secondCache")); + assertThat(cacheManager.getCacheNames()).hasSize(2); } @Test @@ -182,18 +172,18 @@ public class CacheAutoConfigurationTests { public void genericCacheExplicitWithCaches() { load(GenericCacheConfiguration.class, "spring.cache.type=generic"); SimpleCacheManager cacheManager = validateCacheManager(SimpleCacheManager.class); - assertThat(cacheManager.getCache("first"), - equalTo(this.context.getBean("firstCache"))); - assertThat(cacheManager.getCache("second"), - equalTo(this.context.getBean("secondCache"))); - assertThat(cacheManager.getCacheNames(), hasSize(2)); + assertThat(cacheManager.getCache("first")) + .isEqualTo(this.context.getBean("firstCache")); + assertThat(cacheManager.getCache("second")) + .isEqualTo(this.context.getBean("secondCache")); + assertThat(cacheManager.getCacheNames()).hasSize(2); } @Test public void redisCacheExplicit() { load(RedisCacheConfiguration.class, "spring.cache.type=redis"); RedisCacheManager cacheManager = validateCacheManager(RedisCacheManager.class); - assertThat(cacheManager.getCacheNames(), empty()); + assertThat(cacheManager.getCacheNames()).isEmpty(); } @Test @@ -201,15 +191,14 @@ public class CacheAutoConfigurationTests { load(RedisCacheConfiguration.class, "spring.cache.type=redis", "spring.cache.cacheNames[0]=foo", "spring.cache.cacheNames[1]=bar"); RedisCacheManager cacheManager = validateCacheManager(RedisCacheManager.class); - assertThat(cacheManager.getCacheNames(), containsInAnyOrder("foo", "bar")); - assertThat(cacheManager.getCacheNames(), hasSize(2)); + assertThat(cacheManager.getCacheNames()).containsOnly("foo", "bar"); } @Test public void noOpCacheExplicit() { load(DefaultCacheConfiguration.class, "spring.cache.type=none"); NoOpCacheManager cacheManager = validateCacheManager(NoOpCacheManager.class); - assertThat(cacheManager.getCacheNames(), empty()); + assertThat(cacheManager.getCacheNames()).isEmpty(); } @Test @@ -226,9 +215,9 @@ public class CacheAutoConfigurationTests { load(DefaultCacheConfiguration.class, "spring.cache.type=jcache", "spring.cache.jcache.provider=" + cachingProviderFqn); JCacheCacheManager cacheManager = validateCacheManager(JCacheCacheManager.class); - assertThat(cacheManager.getCacheNames(), empty()); - assertThat(this.context.getBean(javax.cache.CacheManager.class), - equalTo(cacheManager.getCacheManager())); + assertThat(cacheManager.getCacheNames()).isEmpty(); + assertThat(this.context.getBean(javax.cache.CacheManager.class)) + .isEqualTo(cacheManager.getCacheManager()); } @Test @@ -238,8 +227,7 @@ public class CacheAutoConfigurationTests { "spring.cache.jcache.provider=" + cachingProviderFqn, "spring.cache.cacheNames[0]=foo", "spring.cache.cacheNames[1]=bar"); JCacheCacheManager cacheManager = validateCacheManager(JCacheCacheManager.class); - assertThat(cacheManager.getCacheNames(), containsInAnyOrder("foo", "bar")); - assertThat(cacheManager.getCacheNames(), hasSize(2)); + assertThat(cacheManager.getCacheNames()).containsOnly("foo", "bar"); } @Test @@ -249,9 +237,7 @@ public class CacheAutoConfigurationTests { "spring.cache.jcache.provider=" + cachingProviderFqn, "spring.cache.cacheNames[0]=one", "spring.cache.cacheNames[1]=two"); JCacheCacheManager cacheManager = validateCacheManager(JCacheCacheManager.class); - assertThat(cacheManager.getCacheNames(), containsInAnyOrder("one", "two")); - assertThat(cacheManager.getCacheNames(), hasSize(2)); - + assertThat(cacheManager.getCacheNames()).containsOnly("one", "two"); CompleteConfiguration defaultCacheConfiguration = this.context .getBean(CompleteConfiguration.class); verify(cacheManager.getCacheManager()).createCache("one", @@ -264,8 +250,8 @@ public class CacheAutoConfigurationTests { public void jCacheCacheWithExistingJCacheManager() { load(JCacheCustomCacheManager.class, "spring.cache.type=jcache"); JCacheCacheManager cacheManager = validateCacheManager(JCacheCacheManager.class); - assertThat(cacheManager.getCacheManager(), - equalTo(this.context.getBean("customJCacheCacheManager"))); + assertThat(cacheManager.getCacheManager()) + .isEqualTo(this.context.getBean("customJCacheCacheManager")); } @Test @@ -286,8 +272,8 @@ public class CacheAutoConfigurationTests { "spring.cache.jcache.config=" + configLocation); JCacheCacheManager cacheManager = validateCacheManager(JCacheCacheManager.class); Resource configResource = new ClassPathResource(configLocation); - assertThat(cacheManager.getCacheManager().getURI(), - equalTo(configResource.getURI())); + assertThat(cacheManager.getCacheManager().getURI()) + .isEqualTo(configResource.getURI()); } @Test @@ -307,11 +293,9 @@ public class CacheAutoConfigurationTests { load(DefaultCacheConfiguration.class, "spring.cache.type=ehcache"); EhCacheCacheManager cacheManager = validateCacheManager( EhCacheCacheManager.class); - assertThat(cacheManager.getCacheNames(), - containsInAnyOrder("cacheTest1", "cacheTest2")); - assertThat(cacheManager.getCacheNames(), hasSize(2)); - assertThat(this.context.getBean(net.sf.ehcache.CacheManager.class), - equalTo(cacheManager.getCacheManager())); + assertThat(cacheManager.getCacheNames()).containsOnly("cacheTest1", "cacheTest2"); + assertThat(this.context.getBean(net.sf.ehcache.CacheManager.class)) + .isEqualTo(cacheManager.getCacheManager()); } @Test @@ -320,9 +304,8 @@ public class CacheAutoConfigurationTests { "spring.cache.ehcache.config=cache/ehcache-override.xml"); EhCacheCacheManager cacheManager = validateCacheManager( EhCacheCacheManager.class); - assertThat(cacheManager.getCacheNames(), - containsInAnyOrder("cacheOverrideTest1", "cacheOverrideTest2")); - assertThat(cacheManager.getCacheNames(), hasSize(2)); + assertThat(cacheManager.getCacheNames()).containsOnly("cacheOverrideTest1", + "cacheOverrideTest2"); } @Test @@ -330,8 +313,8 @@ public class CacheAutoConfigurationTests { load(EhCacheCustomCacheManager.class, "spring.cache.type=ehcache"); EhCacheCacheManager cacheManager = validateCacheManager( EhCacheCacheManager.class); - assertThat(cacheManager.getCacheManager(), - equalTo(this.context.getBean("customEhCacheCacheManager"))); + assertThat(cacheManager.getCacheManager()) + .isEqualTo(this.context.getBean("customEhCacheCacheManager")); } @Test @@ -341,11 +324,10 @@ public class CacheAutoConfigurationTests { HazelcastCacheManager.class); // NOTE: the hazelcast implementation knows about a cache in a lazy manner. cacheManager.getCache("defaultCache"); - assertThat(cacheManager.getCacheNames(), containsInAnyOrder("defaultCache")); - assertThat(cacheManager.getCacheNames(), hasSize(1)); - assertThat(this.context.getBean(HazelcastInstance.class), - equalTo(new DirectFieldAccessor(cacheManager) - .getPropertyValue("hazelcastInstance"))); + assertThat(cacheManager.getCacheNames()).containsOnly("defaultCache"); + assertThat(this.context.getBean(HazelcastInstance.class)) + .isEqualTo(new DirectFieldAccessor(cacheManager) + .getPropertyValue("hazelcastInstance")); } @Test @@ -355,8 +337,7 @@ public class CacheAutoConfigurationTests { HazelcastCacheManager cacheManager = validateCacheManager( HazelcastCacheManager.class); cacheManager.getCache("foobar"); - assertThat(cacheManager.getCacheNames(), containsInAnyOrder("foobar")); - assertThat(cacheManager.getCacheNames(), hasSize(1)); + assertThat(cacheManager.getCacheNames()).containsOnly("foobar"); } @Test @@ -372,10 +353,9 @@ public class CacheAutoConfigurationTests { load(HazelcastCustomHazelcastInstance.class, "spring.cache.type=hazelcast"); HazelcastCacheManager cacheManager = validateCacheManager( HazelcastCacheManager.class); - assertThat( - new DirectFieldAccessor(cacheManager) - .getPropertyValue("hazelcastInstance"), - equalTo(this.context.getBean("customHazelcastInstance"))); + assertThat(new DirectFieldAccessor(cacheManager) + .getPropertyValue("hazelcastInstance")) + .isEqualTo(this.context.getBean("customHazelcastInstance")); } @Test @@ -392,10 +372,10 @@ public class CacheAutoConfigurationTests { HazelcastCacheManager.class); HazelcastInstance hazelcastInstance = this.context .getBean(HazelcastInstance.class); - assertThat(new DirectFieldAccessor(cacheManager).getPropertyValue( - "hazelcastInstance"), equalTo((Object) hazelcastInstance)); - assertThat(hazelcastInstance.getConfig().getConfigurationFile(), - equalTo(new ClassPathResource(mainConfig).getFile())); + assertThat(new DirectFieldAccessor(cacheManager) + .getPropertyValue("hazelcastInstance")).isEqualTo(hazelcastInstance); + assertThat(hazelcastInstance.getConfig().getConfigurationFile()) + .isEqualTo(new ClassPathResource(mainConfig).getFile()); } @Test @@ -418,11 +398,11 @@ public class CacheAutoConfigurationTests { HazelcastCacheManager.class); HazelcastInstance cacheHazelcastInstance = (HazelcastInstance) new DirectFieldAccessor( cacheManager).getPropertyValue("hazelcastInstance"); - assertThat(cacheHazelcastInstance, not(hazelcastInstance)); // Our custom - assertThat(hazelcastInstance.getConfig().getConfigurationFile(), - equalTo(new ClassPathResource(mainConfig).getFile())); - assertThat(cacheHazelcastInstance.getConfig().getConfigurationFile(), - equalTo(new ClassPathResource(cacheConfig).getFile())); + assertThat(cacheHazelcastInstance).isNotEqualTo(hazelcastInstance); // Our custom + assertThat(hazelcastInstance.getConfig().getConfigurationFile()) + .isEqualTo(new ClassPathResource(mainConfig).getFile()); + assertThat(cacheHazelcastInstance.getConfig().getConfigurationFile()) + .isEqualTo(new ClassPathResource(cacheConfig).getFile()); } @Test @@ -432,8 +412,7 @@ public class CacheAutoConfigurationTests { "spring.cache.jcache.provider=" + cachingProviderFqn, "spring.cache.cacheNames[0]=foo", "spring.cache.cacheNames[1]=bar"); JCacheCacheManager cacheManager = validateCacheManager(JCacheCacheManager.class); - assertThat(cacheManager.getCacheNames(), containsInAnyOrder("foo", "bar")); - assertThat(cacheManager.getCacheNames(), hasSize(2)); + assertThat(cacheManager.getCacheNames()).containsOnly("foo", "bar"); } @Test @@ -446,8 +425,8 @@ public class CacheAutoConfigurationTests { JCacheCacheManager cacheManager = validateCacheManager(JCacheCacheManager.class); Resource configResource = new ClassPathResource(configLocation); - assertThat(cacheManager.getCacheManager().getURI(), - equalTo(configResource.getURI())); + assertThat(cacheManager.getCacheManager().getURI()) + .isEqualTo(configResource.getURI()); } @Test @@ -456,7 +435,7 @@ public class CacheAutoConfigurationTests { "spring.cache.infinispan.config=infinispan.xml"); SpringEmbeddedCacheManager cacheManager = validateCacheManager( SpringEmbeddedCacheManager.class); - assertThat(cacheManager.getCacheNames(), containsInAnyOrder("foo", "bar")); + assertThat(cacheManager.getCacheNames()).contains("foo", "bar"); } @Test @@ -465,8 +444,7 @@ public class CacheAutoConfigurationTests { "spring.cache.cacheNames[0]=foo", "spring.cache.cacheNames[1]=bar"); SpringEmbeddedCacheManager cacheManager = validateCacheManager( SpringEmbeddedCacheManager.class); - assertThat(cacheManager.getCacheNames(), containsInAnyOrder("foo", "bar")); - assertThat(cacheManager.getCacheNames(), hasSize(2)); + assertThat(cacheManager.getCacheNames()).containsOnly("foo", "bar"); } @Test @@ -475,9 +453,7 @@ public class CacheAutoConfigurationTests { "spring.cache.cacheNames[0]=foo", "spring.cache.cacheNames[1]=bar"); SpringEmbeddedCacheManager cacheManager = validateCacheManager( SpringEmbeddedCacheManager.class); - assertThat(cacheManager.getCacheNames(), containsInAnyOrder("foo", "bar")); - assertThat(cacheManager.getCacheNames(), hasSize(2)); - + assertThat(cacheManager.getCacheNames()).containsOnly("foo", "bar"); ConfigurationBuilder defaultConfigurationBuilder = this.context .getBean(ConfigurationBuilder.class); verify(defaultConfigurationBuilder, times(2)).build(); @@ -490,8 +466,7 @@ public class CacheAutoConfigurationTests { "spring.cache.jcache.provider=" + cachingProviderFqn, "spring.cache.cacheNames[0]=foo", "spring.cache.cacheNames[1]=bar"); JCacheCacheManager cacheManager = validateCacheManager(JCacheCacheManager.class); - assertThat(cacheManager.getCacheNames(), containsInAnyOrder("foo", "bar")); - assertThat(cacheManager.getCacheNames(), hasSize(2)); + assertThat(cacheManager.getCacheNames()).containsOnly("foo", "bar"); } @Test @@ -504,8 +479,8 @@ public class CacheAutoConfigurationTests { JCacheCacheManager cacheManager = validateCacheManager(JCacheCacheManager.class); Resource configResource = new ClassPathResource(configLocation); - assertThat(cacheManager.getCacheManager().getURI(), - equalTo(configResource.getURI())); + assertThat(cacheManager.getCacheManager().getURI()) + .isEqualTo(configResource.getURI()); } @Test @@ -515,9 +490,8 @@ public class CacheAutoConfigurationTests { "spring.cache.jcache.provider=" + cachingProviderFqn, "spring.cache.cacheNames[0]=foo", "spring.cache.cacheNames[1]=bar"); JCacheCacheManager cacheManager = validateCacheManager(JCacheCacheManager.class); - assertThat(cacheManager.getCacheNames(), containsInAnyOrder("foo", "custom1")); // see - // customizer - assertThat(cacheManager.getCacheNames(), hasSize(2)); + // see customizer + assertThat(cacheManager.getCacheNames()).containsOnly("foo", "custom1"); } @Test @@ -528,7 +502,7 @@ public class CacheAutoConfigurationTests { Cache foo = cacheManager.getCache("foo"); foo.get("1"); // See next tests: no spec given so stats should be disabled - assertThat(((GuavaCache) foo).getNativeCache().stats().missCount(), equalTo(0L)); + assertThat(((GuavaCache) foo).getNativeCache().stats().missCount()).isEqualTo(0L); } @Test @@ -548,16 +522,15 @@ public class CacheAutoConfigurationTests { private void validateGuavaCacheWithStats() { GuavaCacheManager cacheManager = validateCacheManager(GuavaCacheManager.class); - assertThat(cacheManager.getCacheNames(), containsInAnyOrder("foo", "bar")); - assertThat(cacheManager.getCacheNames(), hasSize(2)); + assertThat(cacheManager.getCacheNames()).containsOnly("foo", "bar"); Cache foo = cacheManager.getCache("foo"); foo.get("1"); - assertThat(((GuavaCache) foo).getNativeCache().stats().missCount(), equalTo(1L)); + assertThat(((GuavaCache) foo).getNativeCache().stats().missCount()).isEqualTo(1L); } private T validateCacheManager(Class type) { CacheManager cacheManager = this.context.getBean(CacheManager.class); - assertThat("Wrong cache manager type", cacheManager, instanceOf(type)); + assertThat(cacheManager).as("Wrong cache manager type").isInstanceOf(type); return type.cast(cacheManager); } diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/cassandra/CassandraAutoConfigurationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/cassandra/CassandraAutoConfigurationTests.java index f175fbe1ea..fd0f7e352f 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/cassandra/CassandraAutoConfigurationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/cassandra/CassandraAutoConfigurationTests.java @@ -24,10 +24,7 @@ import org.springframework.boot.autoconfigure.PropertyPlaceholderAutoConfigurati import org.springframework.boot.test.EnvironmentTestUtils; import org.springframework.context.annotation.AnnotationConfigApplicationContext; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.startsWith; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link CassandraAutoConfiguration} @@ -48,17 +45,17 @@ public class CassandraAutoConfigurationTests { @Test public void createClusterWithDefault() { this.context = doLoad(); - assertEquals(1, this.context.getBeanNamesForType(Cluster.class).length); + assertThat(this.context.getBeanNamesForType(Cluster.class).length).isEqualTo(1); Cluster cluster = this.context.getBean(Cluster.class); - assertThat(cluster.getClusterName(), startsWith("cluster")); + assertThat(cluster.getClusterName()).startsWith("cluster"); } @Test public void createClusterWithOverrides() { this.context = doLoad("spring.data.cassandra.cluster-name=testcluster"); - assertEquals(1, this.context.getBeanNamesForType(Cluster.class).length); + assertThat(this.context.getBeanNamesForType(Cluster.class).length).isEqualTo(1); Cluster cluster = this.context.getBean(Cluster.class); - assertThat(cluster.getClusterName(), equalTo("testcluster")); + assertThat(cluster.getClusterName()).isEqualTo("testcluster"); } private AnnotationConfigApplicationContext doLoad(String... environment) { diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/cloud/CloudAutoConfigurationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/cloud/CloudAutoConfigurationTests.java index a888b60db8..f0f9322ced 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/cloud/CloudAutoConfigurationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/cloud/CloudAutoConfigurationTests.java @@ -29,8 +29,7 @@ import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; import org.springframework.boot.autoconfigure.mongo.MongoAutoConfiguration; import org.springframework.core.type.classreading.CachingMetadataReaderFactory; -import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link CloudAutoConfiguration}. @@ -50,7 +49,7 @@ public class CloudAutoConfigurationTests { classNames.add(JpaRepositoriesAutoConfiguration.class.getName()); classNames.add(CloudAutoConfiguration.class.getName()); List ordered = sorter.getInPriorityOrder(classNames); - assertThat(ordered.get(0), equalTo(CloudAutoConfiguration.class.getName())); + assertThat(ordered.get(0)).isEqualTo(CloudAutoConfiguration.class.getName()); } } diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/AllNestedConditionsTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/AllNestedConditionsTests.java index a6e8c1c6c6..986aa0a172 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/AllNestedConditionsTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/AllNestedConditionsTests.java @@ -24,8 +24,7 @@ import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Conditional; 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 for {@link AllNestedConditions}. @@ -35,28 +34,28 @@ public class AllNestedConditionsTests { @Test public void neither() throws Exception { AnnotationConfigApplicationContext context = load(Config.class); - assertThat(context.containsBean("myBean"), equalTo(false)); + assertThat(context.containsBean("myBean")).isFalse(); context.close(); } @Test public void propertyA() throws Exception { AnnotationConfigApplicationContext context = load(Config.class, "a:a"); - assertThat(context.containsBean("myBean"), equalTo(false)); + assertThat(context.containsBean("myBean")).isFalse(); context.close(); } @Test public void propertyB() throws Exception { AnnotationConfigApplicationContext context = load(Config.class, "b:b"); - assertThat(context.containsBean("myBean"), equalTo(false)); + assertThat(context.containsBean("myBean")).isFalse(); context.close(); } @Test public void both() throws Exception { AnnotationConfigApplicationContext context = load(Config.class, "a:a", "b:b"); - assertThat(context.containsBean("myBean"), equalTo(true)); + assertThat(context.containsBean("myBean")).isTrue(); context.close(); } diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/AnyNestedConditionTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/AnyNestedConditionTests.java index 69e8fa86bf..b447f6ff89 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/AnyNestedConditionTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/AnyNestedConditionTests.java @@ -24,8 +24,7 @@ import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Conditional; 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 for {@link AnyNestedCondition}. @@ -37,28 +36,28 @@ public class AnyNestedConditionTests { @Test public void neither() throws Exception { AnnotationConfigApplicationContext context = load(OnPropertyAorBCondition.class); - assertThat(context.containsBean("myBean"), equalTo(false)); + assertThat(context.containsBean("myBean")).isFalse(); context.close(); } @Test public void propertyA() throws Exception { AnnotationConfigApplicationContext context = load(Config.class, "a:a"); - assertThat(context.containsBean("myBean"), equalTo(true)); + assertThat(context.containsBean("myBean")).isTrue(); context.close(); } @Test public void propertyB() throws Exception { AnnotationConfigApplicationContext context = load(Config.class, "b:b"); - assertThat(context.containsBean("myBean"), equalTo(true)); + assertThat(context.containsBean("myBean")).isTrue(); context.close(); } @Test public void both() throws Exception { AnnotationConfigApplicationContext context = load(Config.class, "a:a", "b:b"); - assertThat(context.containsBean("myBean"), equalTo(true)); + assertThat(context.containsBean("myBean")).isTrue(); context.close(); } diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionEvaluationReportTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionEvaluationReportTests.java index 7a4787d128..039734e7c5 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionEvaluationReportTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionEvaluationReportTests.java @@ -21,7 +21,6 @@ import java.util.Iterator; import java.util.List; import java.util.Map; -import org.hamcrest.Matcher; import org.junit.Before; import org.junit.Test; import org.mockito.Mock; @@ -34,6 +33,7 @@ import org.springframework.boot.autoconfigure.condition.ConditionEvaluationRepor import org.springframework.boot.autoconfigure.web.MultipartAutoConfiguration; import org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration; import org.springframework.boot.test.EnvironmentTestUtils; +import org.springframework.boot.test.assertj.Matched; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Condition; @@ -45,13 +45,9 @@ import org.springframework.context.annotation.Import; import org.springframework.core.type.AnnotatedTypeMetadata; import org.springframework.util.ClassUtils; +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.hasItem; -import static org.hamcrest.Matchers.not; import static org.hamcrest.Matchers.nullValue; -import static org.hamcrest.Matchers.sameInstance; -import static org.junit.Assert.assertThat; /** * Tests for {@link ConditionEvaluationReport}. @@ -89,9 +85,8 @@ public class ConditionEvaluationReportTests { @Test public void get() throws Exception { - assertThat(this.report, not(nullValue())); - assertThat(this.report, - sameInstance(ConditionEvaluationReport.get(this.beanFactory))); + assertThat(this.report).isNotEqualTo(nullValue()); + assertThat(this.report).isSameAs(ConditionEvaluationReport.get(this.beanFactory)); } @Test @@ -99,18 +94,15 @@ public class ConditionEvaluationReportTests { this.beanFactory.setParentBeanFactory(new DefaultListableBeanFactory()); ConditionEvaluationReport.get((ConfigurableListableBeanFactory) this.beanFactory .getParentBeanFactory()); - assertThat(this.report, - sameInstance(ConditionEvaluationReport.get(this.beanFactory))); - assertThat(this.report, not(nullValue())); - assertThat(this.report.getParent(), not(nullValue())); + assertThat(this.report).isSameAs(ConditionEvaluationReport.get(this.beanFactory)); + assertThat(this.report).isNotEqualTo(nullValue()); + assertThat(this.report.getParent()).isNotEqualTo(nullValue()); ConditionEvaluationReport.get((ConfigurableListableBeanFactory) this.beanFactory .getParentBeanFactory()); - assertThat(this.report, - sameInstance(ConditionEvaluationReport.get(this.beanFactory))); - assertThat(this.report.getParent(), - sameInstance(ConditionEvaluationReport - .get((ConfigurableListableBeanFactory) this.beanFactory - .getParentBeanFactory()))); + assertThat(this.report).isSameAs(ConditionEvaluationReport.get(this.beanFactory)); + assertThat(this.report.getParent()).isSameAs(ConditionEvaluationReport + .get((ConfigurableListableBeanFactory) this.beanFactory + .getParentBeanFactory())); } @Test @@ -120,10 +112,10 @@ public class ConditionEvaluationReportTests { ConditionEvaluationReport.get((ConfigurableListableBeanFactory) this.beanFactory .getParentBeanFactory()); this.report = ConditionEvaluationReport.get(this.beanFactory); - assertThat(this.report, not(nullValue())); - assertThat(this.report, not(sameInstance(this.report.getParent()))); - assertThat(this.report.getParent(), not(nullValue())); - assertThat(this.report.getParent().getParent(), nullValue()); + assertThat(this.report).isNotNull(); + assertThat(this.report).isNotSameAs(this.report.getParent()); + assertThat(this.report.getParent()).isNotNull(); + assertThat(this.report.getParent().getParent()).isNull(); } @Test @@ -136,37 +128,37 @@ public class ConditionEvaluationReportTests { this.report.recordConditionEvaluation("b", this.condition3, this.outcome3); Map map = this.report .getConditionAndOutcomesBySource(); - assertThat(map.size(), equalTo(2)); + assertThat(map.size()).isEqualTo(2); Iterator iterator = map.get("a").iterator(); ConditionAndOutcome conditionAndOutcome = iterator.next(); - assertThat(conditionAndOutcome.getCondition(), equalTo(this.condition1)); - assertThat(conditionAndOutcome.getOutcome(), equalTo(this.outcome1)); + assertThat(conditionAndOutcome.getCondition()).isEqualTo(this.condition1); + assertThat(conditionAndOutcome.getOutcome()).isEqualTo(this.outcome1); conditionAndOutcome = iterator.next(); - assertThat(conditionAndOutcome.getCondition(), equalTo(this.condition2)); - assertThat(conditionAndOutcome.getOutcome(), equalTo(this.outcome2)); - assertThat(iterator.hasNext(), equalTo(false)); + assertThat(conditionAndOutcome.getCondition()).isEqualTo(this.condition2); + assertThat(conditionAndOutcome.getOutcome()).isEqualTo(this.outcome2); + assertThat(iterator.hasNext()).isFalse(); iterator = map.get("b").iterator(); conditionAndOutcome = iterator.next(); - assertThat(conditionAndOutcome.getCondition(), equalTo(this.condition3)); - assertThat(conditionAndOutcome.getOutcome(), equalTo(this.outcome3)); - assertThat(iterator.hasNext(), equalTo(false)); + assertThat(conditionAndOutcome.getCondition()).isEqualTo(this.condition3); + assertThat(conditionAndOutcome.getOutcome()).isEqualTo(this.outcome3); + assertThat(iterator.hasNext()).isFalse(); } @Test public void fullMatch() throws Exception { prepareMatches(true, true, true); - assertThat(this.report.getConditionAndOutcomesBySource().get("a").isFullMatch(), - equalTo(true)); + assertThat(this.report.getConditionAndOutcomesBySource().get("a").isFullMatch()) + .isTrue(); } @Test public void notFullMatch() throws Exception { prepareMatches(true, false, true); - assertThat(this.report.getConditionAndOutcomesBySource().get("a").isFullMatch(), - equalTo(false)); + assertThat(this.report.getConditionAndOutcomesBySource().get("a").isFullMatch()) + .isFalse(); } private void prepareMatches(boolean m1, boolean m2, boolean m3) { @@ -183,7 +175,7 @@ public class ConditionEvaluationReportTests { public void springBootConditionPopulatesReport() throws Exception { ConditionEvaluationReport report = ConditionEvaluationReport.get( new AnnotationConfigApplicationContext(Config.class).getBeanFactory()); - assertThat(report.getConditionAndOutcomesBySource().size(), not(equalTo(0))); + assertThat(report.getConditionAndOutcomesBySource().size()).isNotEqualTo(0); } @Test @@ -195,16 +187,16 @@ public class ConditionEvaluationReportTests { ConditionAndOutcome outcome3 = new ConditionAndOutcome(this.condition3, new ConditionOutcome(true, "Message 2")); - assertThat(outcome1, equalTo(outcome1)); - assertThat(outcome1, not(equalTo(outcome2))); - assertThat(outcome2, equalTo(outcome3)); + assertThat(outcome1).isEqualTo(outcome1); + assertThat(outcome1).isNotEqualTo(outcome2); + assertThat(outcome2).isEqualTo(outcome3); ConditionAndOutcomes outcomes = new ConditionAndOutcomes(); outcomes.add(this.condition1, new ConditionOutcome(true, "Message 1")); outcomes.add(this.condition2, new ConditionOutcome(true, "Message 2")); outcomes.add(this.condition3, new ConditionOutcome(true, "Message 2")); - assertThat(getNumberOfOutcomes(outcomes), equalTo(2)); + assertThat(getNumberOfOutcomes(outcomes)).isEqualTo(2); } @Test @@ -217,17 +209,16 @@ public class ConditionEvaluationReportTests { ConditionAndOutcomes outcomes = report.getConditionAndOutcomesBySource() .get(autoconfigKey); - assertThat(outcomes, not(nullValue())); - assertThat(getNumberOfOutcomes(outcomes), equalTo(2)); + assertThat(outcomes).isNotEqualTo(nullValue()); + assertThat(getNumberOfOutcomes(outcomes)).isEqualTo(2); List messages = new ArrayList(); for (ConditionAndOutcome outcome : outcomes) { messages.add(outcome.getOutcome().getMessage()); } - - Matcher onClassMessage = containsString("@ConditionalOnClass " - + "classes found: javax.servlet.Servlet,org.springframework.web.multipart.support.StandardServletMultipartResolver"); - assertThat(messages, hasItem(onClassMessage)); + assertThat(messages).areAtLeastOne(Matched.by( + containsString("@ConditionalOnClass classes found: javax.servlet.Servlet," + + "org.springframework.web.multipart.support.StandardServletMultipartResolver"))); context.close(); } @@ -241,12 +232,11 @@ public class ConditionEvaluationReportTests { .get(context.getBeanFactory()); Map sourceOutcomes = report .getConditionAndOutcomesBySource(); - assertThat(context.containsBean("negativeOuterPositiveInnerBean"), - equalTo(false)); + assertThat(context.containsBean("negativeOuterPositiveInnerBean")).isFalse(); String negativeConfig = NegativeOuterConfig.class.getName(); - assertThat(sourceOutcomes.get(negativeConfig).isFullMatch(), equalTo(false)); + assertThat(sourceOutcomes.get(negativeConfig).isFullMatch()).isFalse(); String positiveConfig = NegativeOuterConfig.PositiveInnerConfig.class.getName(); - assertThat(sourceOutcomes.get(positiveConfig).isFullMatch(), equalTo(false)); + assertThat(sourceOutcomes.get(positiveConfig).isFullMatch()).isFalse(); } private int getNumberOfOutcomes(ConditionAndOutcomes outcomes) { diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnBeanTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnBeanTests.java index ca7413ab03..e8bfb92a23 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnBeanTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnBeanTests.java @@ -33,9 +33,7 @@ import org.springframework.context.support.PropertySourcesPlaceholderConfigurer; import org.springframework.core.type.AnnotationMetadata; import org.springframework.scheduling.annotation.EnableScheduling; -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 ConditionalOnBean}. @@ -50,8 +48,8 @@ public class ConditionalOnBeanTests { public void testNameOnBeanCondition() { this.context.register(FooConfiguration.class, OnBeanNameConfiguration.class); this.context.refresh(); - assertTrue(this.context.containsBean("bar")); - assertEquals("bar", this.context.getBean("bar")); + assertThat(this.context.containsBean("bar")).isTrue(); + assertThat(this.context.getBean("bar")).isEqualTo("bar"); } @Test @@ -64,7 +62,7 @@ public class ConditionalOnBeanTests { * specified in the different attributes of @ConditionalOnBean are combined with * logical OR (not AND) so if any of them match the condition is true. */ - assertFalse(this.context.containsBean("bar")); + assertThat(this.context.containsBean("bar")).isFalse(); } @Test @@ -72,31 +70,31 @@ public class ConditionalOnBeanTests { this.context.register(OnBeanNameConfiguration.class, FooConfiguration.class); this.context.refresh(); // Ideally this should be true - assertFalse(this.context.containsBean("bar")); + assertThat(this.context.containsBean("bar")).isFalse(); } @Test public void testClassOnBeanCondition() { this.context.register(FooConfiguration.class, OnBeanClassConfiguration.class); this.context.refresh(); - assertTrue(this.context.containsBean("bar")); - assertEquals("bar", this.context.getBean("bar")); + assertThat(this.context.containsBean("bar")).isTrue(); + assertThat(this.context.getBean("bar")).isEqualTo("bar"); } @Test public void testClassOnBeanClassNameCondition() { this.context.register(FooConfiguration.class, OnBeanClassNameConfiguration.class); this.context.refresh(); - assertTrue(this.context.containsBean("bar")); - assertEquals("bar", this.context.getBean("bar")); + assertThat(this.context.containsBean("bar")).isTrue(); + assertThat(this.context.getBean("bar")).isEqualTo("bar"); } @Test public void testOnBeanConditionWithXml() { this.context.register(XmlConfiguration.class, OnBeanNameConfiguration.class); this.context.refresh(); - assertTrue(this.context.containsBean("bar")); - assertEquals("bar", this.context.getBean("bar")); + assertThat(this.context.containsBean("bar")).isTrue(); + assertThat(this.context.getBean("bar")).isEqualTo("bar"); } @Test @@ -104,15 +102,15 @@ public class ConditionalOnBeanTests { this.context.register(CombinedXmlConfiguration.class); this.context.refresh(); // Ideally this should be true - assertFalse(this.context.containsBean("bar")); + assertThat(this.context.containsBean("bar")).isFalse(); } @Test public void testAnnotationOnBeanCondition() { this.context.register(FooConfiguration.class, OnAnnotationConfiguration.class); this.context.refresh(); - assertTrue(this.context.containsBean("bar")); - assertEquals("bar", this.context.getBean("bar")); + assertThat(this.context.containsBean("bar")).isTrue(); + assertThat(this.context.getBean("bar")).isEqualTo("bar"); } @Test @@ -120,7 +118,7 @@ public class ConditionalOnBeanTests { this.context.register(FooConfiguration.class, OnBeanMissingClassConfiguration.class); this.context.refresh(); - assertFalse(this.context.containsBean("bar")); + assertThat(this.context.containsBean("bar")).isFalse(); } @Test diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnClassTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnClassTests.java index 15a201c34c..30301b1041 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnClassTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnClassTests.java @@ -24,9 +24,7 @@ import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; import org.springframework.context.annotation.ImportResource; -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 ConditionalOnClass}. @@ -41,32 +39,32 @@ public class ConditionalOnClassTests { public void testVanillaOnClassCondition() { this.context.register(BasicConfiguration.class, FooConfiguration.class); this.context.refresh(); - assertTrue(this.context.containsBean("bar")); - assertEquals("bar", this.context.getBean("bar")); + assertThat(this.context.containsBean("bar")).isTrue(); + assertThat(this.context.getBean("bar")).isEqualTo("bar"); } @Test public void testMissingOnClassCondition() { this.context.register(MissingConfiguration.class, FooConfiguration.class); this.context.refresh(); - assertFalse(this.context.containsBean("bar")); - assertEquals("foo", this.context.getBean("foo")); + assertThat(this.context.containsBean("bar")).isFalse(); + assertThat(this.context.getBean("foo")).isEqualTo("foo"); } @Test public void testOnClassConditionWithXml() { this.context.register(BasicConfiguration.class, XmlConfiguration.class); this.context.refresh(); - assertTrue(this.context.containsBean("bar")); - assertEquals("bar", this.context.getBean("bar")); + assertThat(this.context.containsBean("bar")).isTrue(); + assertThat(this.context.getBean("bar")).isEqualTo("bar"); } @Test public void testOnClassConditionWithCombinedXml() { this.context.register(CombinedXmlConfiguration.class); this.context.refresh(); - assertTrue(this.context.containsBean("bar")); - assertEquals("bar", this.context.getBean("bar")); + assertThat(this.context.containsBean("bar")).isTrue(); + assertThat(this.context.getBean("bar")).isEqualTo("bar"); } @Configuration diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnExpressionTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnExpressionTests.java index 999e9ce370..b22878acc9 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnExpressionTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnExpressionTests.java @@ -22,9 +22,7 @@ import org.springframework.context.annotation.AnnotationConfigApplicationContext import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; -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 ConditionalOnExpression}. @@ -39,15 +37,15 @@ public class ConditionalOnExpressionTests { public void testResourceExists() { this.context.register(BasicConfiguration.class); this.context.refresh(); - assertTrue(this.context.containsBean("foo")); - assertEquals("foo", this.context.getBean("foo")); + assertThat(this.context.containsBean("foo")).isTrue(); + assertThat(this.context.getBean("foo")).isEqualTo("foo"); } @Test public void testResourceNotExists() { this.context.register(MissingConfiguration.class); this.context.refresh(); - assertFalse(this.context.containsBean("foo")); + assertThat(this.context.containsBean("foo")).isFalse(); } @Configuration diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnJavaTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnJavaTests.java index 5553715d0d..6a43cde490 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnJavaTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnJavaTests.java @@ -25,7 +25,6 @@ import java.util.List; import java.util.ServiceLoader; import java.util.function.Function; -import org.hamcrest.Matcher; import org.junit.Test; import org.springframework.boot.autoconfigure.condition.ConditionalOnJava.JavaVersion; @@ -35,10 +34,7 @@ import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.util.ReflectionUtils; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.iterableWithSize; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link ConditionalOnJava}. @@ -84,37 +80,37 @@ public class ConditionalOnJavaTests { public void equalOrNewerMessage() throws Exception { ConditionOutcome outcome = this.condition.getMatchOutcome(Range.EQUAL_OR_NEWER, JavaVersion.SEVEN, JavaVersion.SIX); - assertThat(outcome.getMessage(), - equalTo("Required JVM version " + "1.6 or newer found 1.7")); + assertThat(outcome.getMessage()) + .isEqualTo("Required JVM version " + "1.6 or newer found 1.7"); } @Test public void olderThanMessage() throws Exception { ConditionOutcome outcome = this.condition.getMatchOutcome(Range.OLDER_THAN, JavaVersion.SEVEN, JavaVersion.SIX); - assertThat(outcome.getMessage(), - equalTo("Required JVM version " + "older than 1.6 found 1.7")); + assertThat(outcome.getMessage()) + .isEqualTo("Required JVM version " + "older than 1.6 found 1.7"); } @Test public void java8IsDetected() throws Exception { - assertThat(getJavaVersion(), is("1.8")); + assertThat(getJavaVersion()).isEqualTo("1.8"); } @Test public void java7IsDetected() throws Exception { - assertThat(getJavaVersion(Function.class), is("1.7")); + assertThat(getJavaVersion(Function.class)).isEqualTo("1.7"); } @Test public void java6IsDetected() throws Exception { - assertThat(getJavaVersion(Function.class, Files.class), is("1.6")); + assertThat(getJavaVersion(Function.class, Files.class)).isEqualTo("1.6"); } @Test public void java6IsTheFallback() throws Exception { - assertThat(getJavaVersion(Function.class, Files.class, ServiceLoader.class), - is("1.6")); + assertThat(getJavaVersion(Function.class, Files.class, ServiceLoader.class)) + .isEqualTo("1.6"); } private String getJavaVersion(Class... hiddenClasses) throws Exception { @@ -135,7 +131,7 @@ public class ConditionalOnJavaTests { boolean expected) { ConditionOutcome outcome = this.condition.getMatchOutcome(range, runningVersion, version); - assertThat(outcome.getMessage(), outcome.isMatch(), equalTo(expected)); + assertThat(outcome.isMatch()).as(outcome.getMessage()).isEqualTo(expected); } private void registerAndRefresh(Class annotatedClasses) { @@ -144,9 +140,7 @@ public class ConditionalOnJavaTests { } private void assertPresent(boolean expected) { - int expectedNumber = expected ? 1 : 0; - Matcher> matcher = iterableWithSize(expectedNumber); - assertThat(this.context.getBeansOfType(String.class).values(), is(matcher)); + assertThat(this.context.getBeansOfType(String.class)).hasSize(expected ? 1 : 0); } private final class ClassHidingClassLoader extends URLClassLoader { diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnJndiTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnJndiTests.java index dec83e3d4e..5ea8b897a6 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnJndiTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnJndiTests.java @@ -21,7 +21,6 @@ import java.util.Map; import javax.naming.Context; -import org.hamcrest.Matcher; import org.junit.After; import org.junit.Before; import org.junit.Test; @@ -35,10 +34,7 @@ import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.type.AnnotatedTypeMetadata; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.iterableWithSize; -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; @@ -114,7 +110,7 @@ public class ConditionalOnJndiTests { public void jndiLocationNotFound() { ConditionOutcome outcome = this.condition.getMatchOutcome(null, mockMetaData("java:/a")); - assertThat(outcome.isMatch(), equalTo(false)); + assertThat(outcome.isMatch()).isFalse(); } @Test @@ -122,7 +118,7 @@ public class ConditionalOnJndiTests { this.condition.setFoundLocation("java:/b"); ConditionOutcome outcome = this.condition.getMatchOutcome(null, mockMetaData("java:/a", "java:/b")); - assertThat(outcome.isMatch(), equalTo(true)); + assertThat(outcome.isMatch()).isTrue(); } private void setupJndi() { @@ -132,9 +128,7 @@ public class ConditionalOnJndiTests { } private void assertPresent(boolean expected) { - int expectedNumber = expected ? 1 : 0; - Matcher> matcher = iterableWithSize(expectedNumber); - assertThat(this.context.getBeansOfType(String.class).values(), is(matcher)); + assertThat(this.context.getBeansOfType(String.class)).hasSize(expected ? 1 : 0); } private void load(Class config, String... environment) { diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnMissingBeanTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnMissingBeanTests.java index 32da9f90bc..658a1da722 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnMissingBeanTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnMissingBeanTests.java @@ -34,12 +34,7 @@ import org.springframework.core.type.AnnotationMetadata; import org.springframework.scheduling.annotation.EnableScheduling; import org.springframework.util.Assert; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.is; -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; /** * Tests for {@link ConditionalOnMissingBean}. @@ -58,8 +53,8 @@ public class ConditionalOnMissingBeanTests { public void testNameOnMissingBeanCondition() { this.context.register(FooConfiguration.class, OnBeanNameConfiguration.class); this.context.refresh(); - assertFalse(this.context.containsBean("bar")); - assertEquals("foo", this.context.getBean("foo")); + assertThat(this.context.containsBean("bar")).isFalse(); + assertThat(this.context.getBean("foo")).isEqualTo("foo"); } @Test @@ -67,8 +62,8 @@ public class ConditionalOnMissingBeanTests { this.context.register(OnBeanNameConfiguration.class, FooConfiguration.class); this.context.refresh(); // FIXME: ideally this would be false, but the ordering is a problem - assertTrue(this.context.containsBean("bar")); - assertEquals("foo", this.context.getBean("foo")); + assertThat(this.context.containsBean("bar")).isTrue(); + assertThat(this.context.getBean("foo")).isEqualTo("foo"); } @Test @@ -79,7 +74,7 @@ public class ConditionalOnMissingBeanTests { childContext.setParent(this.context); childContext.register(HierarchyConsidered.class); childContext.refresh(); - assertFalse(childContext.containsLocalBean("bar")); + assertThat(childContext.containsLocalBean("bar")).isFalse(); } @Test @@ -90,22 +85,22 @@ public class ConditionalOnMissingBeanTests { childContext.setParent(this.context); childContext.register(HierarchyNotConsidered.class); childContext.refresh(); - assertTrue(childContext.containsLocalBean("bar")); + assertThat(childContext.containsLocalBean("bar")).isTrue(); } @Test public void impliedOnBeanMethod() throws Exception { this.context.register(ExampleBeanConfiguration.class, ImpliedOnBeanMethod.class); this.context.refresh(); - assertThat(this.context.getBeansOfType(ExampleBean.class).size(), equalTo(1)); + assertThat(this.context.getBeansOfType(ExampleBean.class).size()).isEqualTo(1); } @Test public void testAnnotationOnMissingBeanCondition() { this.context.register(FooConfiguration.class, OnAnnotationConfiguration.class); this.context.refresh(); - assertFalse(this.context.containsBean("bar")); - assertEquals("foo", this.context.getBean("foo")); + assertThat(this.context.containsBean("bar")).isFalse(); + assertThat(this.context.getBean("foo")).isEqualTo("foo"); } // Rigorous test for SPR-11069 @@ -115,9 +110,9 @@ public class ConditionalOnMissingBeanTests { FactoryBeanXmlConfiguration.class, PropertyPlaceholderAutoConfiguration.class); this.context.refresh(); - assertFalse(this.context.containsBean("bar")); - assertTrue(this.context.containsBean("example")); - assertEquals("foo", this.context.getBean("foo")); + assertThat(this.context.containsBean("bar")).isFalse(); + assertThat(this.context.containsBean("example")).isTrue(); + assertThat(this.context.getBean("foo")).isEqualTo("foo"); } @Test @@ -126,8 +121,8 @@ public class ConditionalOnMissingBeanTests { ConditionalOnFactoryBean.class, PropertyPlaceholderAutoConfiguration.class); this.context.refresh(); - assertThat(this.context.getBean(ExampleBean.class).toString(), - equalTo("fromFactory")); + assertThat(this.context.getBean(ExampleBean.class).toString()) + .isEqualTo("fromFactory"); } @Test @@ -137,8 +132,8 @@ public class ConditionalOnMissingBeanTests { PropertyPlaceholderAutoConfiguration.class); EnvironmentTestUtils.addEnvironment(this.context, "theValue:foo"); this.context.refresh(); - assertThat(this.context.getBean(ExampleBean.class).toString(), - equalTo("fromFactory")); + assertThat(this.context.getBean(ExampleBean.class).toString()) + .isEqualTo("fromFactory"); } @Test @@ -147,8 +142,8 @@ public class ConditionalOnMissingBeanTests { ConditionalOnFactoryBean.class, PropertyPlaceholderAutoConfiguration.class); this.context.refresh(); - assertThat(this.context.getBean(ExampleBean.class).toString(), - equalTo("fromFactory")); + assertThat(this.context.getBean(ExampleBean.class).toString()) + .isEqualTo("fromFactory"); } @Test @@ -158,8 +153,7 @@ public class ConditionalOnMissingBeanTests { PropertyPlaceholderAutoConfiguration.class); this.context.refresh(); // We could not tell that the FactoryBean would ultimately create an ExampleBean - assertThat(this.context.getBeansOfType(ExampleBean.class).values().size(), - equalTo(2)); + assertThat(this.context.getBeansOfType(ExampleBean.class).values()).hasSize(2); } @Test @@ -168,8 +162,8 @@ public class ConditionalOnMissingBeanTests { ConditionalOnFactoryBean.class, PropertyPlaceholderAutoConfiguration.class); this.context.refresh(); - assertThat(this.context.getBean(ExampleBean.class).toString(), - equalTo("fromFactory")); + assertThat(this.context.getBean(ExampleBean.class).toString()) + .isEqualTo("fromFactory"); } @Test @@ -178,8 +172,8 @@ public class ConditionalOnMissingBeanTests { ConditionalOnFactoryBean.class, PropertyPlaceholderAutoConfiguration.class); this.context.refresh(); - assertThat(this.context.getBean(ExampleBean.class).toString(), - equalTo("fromFactory")); + assertThat(this.context.getBean(ExampleBean.class).toString()) + .isEqualTo("fromFactory"); } @Test @@ -188,8 +182,8 @@ public class ConditionalOnMissingBeanTests { ConditionalOnFactoryBean.class, PropertyPlaceholderAutoConfiguration.class); this.context.refresh(); - assertThat(this.context.getBean(ExampleBean.class).toString(), - equalTo("fromFactory")); + assertThat(this.context.getBean(ExampleBean.class).toString()) + .isEqualTo("fromFactory"); } @Test @@ -198,8 +192,8 @@ public class ConditionalOnMissingBeanTests { ConditionalOnFactoryBean.class, PropertyPlaceholderAutoConfiguration.class); this.context.refresh(); - assertThat(this.context.getBean(ExampleBean.class).toString(), - equalTo("fromFactory")); + assertThat(this.context.getBean(ExampleBean.class).toString()) + .isEqualTo("fromFactory"); } @Test @@ -208,9 +202,8 @@ public class ConditionalOnMissingBeanTests { ConditionalOnIgnoredSubclass.class, PropertyPlaceholderAutoConfiguration.class); this.context.refresh(); - assertThat(this.context.getBeansOfType(ExampleBean.class).size(), is(equalTo(2))); - assertThat(this.context.getBeansOfType(CustomExampleBean.class).size(), - is(equalTo(1))); + assertThat(this.context.getBeansOfType(ExampleBean.class)).hasSize(2); + assertThat(this.context.getBeansOfType(CustomExampleBean.class)).hasSize(1); } @Test @@ -219,9 +212,8 @@ public class ConditionalOnMissingBeanTests { ConditionalOnIgnoredSubclassByName.class, PropertyPlaceholderAutoConfiguration.class); this.context.refresh(); - assertThat(this.context.getBeansOfType(ExampleBean.class).size(), is(equalTo(2))); - assertThat(this.context.getBeansOfType(CustomExampleBean.class).size(), - is(equalTo(1))); + assertThat(this.context.getBeansOfType(ExampleBean.class)).hasSize(2); + assertThat(this.context.getBeansOfType(CustomExampleBean.class)).hasSize(1); } @Configuration diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnMissingClassTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnMissingClassTests.java index c9a604dc5f..ce8156ff72 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnMissingClassTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnMissingClassTests.java @@ -22,9 +22,7 @@ import org.springframework.context.annotation.AnnotationConfigApplicationContext import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; -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 ConditionalOnMissingClass}. @@ -39,16 +37,16 @@ public class ConditionalOnMissingClassTests { public void testVanillaOnClassCondition() { this.context.register(BasicConfiguration.class, FooConfiguration.class); this.context.refresh(); - assertFalse(this.context.containsBean("bar")); - assertEquals("foo", this.context.getBean("foo")); + assertThat(this.context.containsBean("bar")).isFalse(); + assertThat(this.context.getBean("foo")).isEqualTo("foo"); } @Test public void testMissingOnClassCondition() { this.context.register(MissingConfiguration.class, FooConfiguration.class); this.context.refresh(); - assertTrue(this.context.containsBean("bar")); - assertEquals("foo", this.context.getBean("foo")); + assertThat(this.context.containsBean("bar")).isTrue(); + assertThat(this.context.getBean("foo")).isEqualTo("foo"); } @Configuration diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnNotWebApplicationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnNotWebApplicationTests.java index 259a77e47a..13ff4c3782 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnNotWebApplicationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnNotWebApplicationTests.java @@ -22,9 +22,7 @@ import org.springframework.context.annotation.AnnotationConfigApplicationContext import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; -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 ConditionalOnNotWebApplication}. @@ -39,15 +37,15 @@ public class ConditionalOnNotWebApplicationTests { public void testWebApplication() { this.context.register(BasicConfiguration.class); this.context.refresh(); - assertTrue(this.context.containsBean("foo")); - assertEquals("foo", this.context.getBean("foo")); + assertThat(this.context.containsBean("foo")).isTrue(); + assertThat(this.context.getBean("foo")).isEqualTo("foo"); } @Test public void testNotWebApplication() { this.context.register(MissingConfiguration.class); this.context.refresh(); - assertFalse(this.context.containsBean("foo")); + assertThat(this.context.containsBean("foo")).isFalse(); } @Configuration diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnPropertyTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnPropertyTests.java index df39c1576f..48492e28de 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnPropertyTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnPropertyTests.java @@ -26,9 +26,8 @@ import org.springframework.context.annotation.AnnotationConfigApplicationContext import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; +import static org.assertj.core.api.Assertions.assertThat; import static org.hamcrest.Matchers.containsString; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; import static org.junit.internal.matchers.ThrowableMessageMatcher.hasMessage; /** @@ -56,159 +55,159 @@ public class ConditionalOnPropertyTests { public void allPropertiesAreDefined() { load(MultiplePropertiesRequiredConfiguration.class, "property1=value1", "property2=value2"); - assertTrue(this.context.containsBean("foo")); + assertThat(this.context.containsBean("foo")).isTrue(); } @Test public void notAllPropertiesAreDefined() { load(MultiplePropertiesRequiredConfiguration.class, "property1=value1"); - assertFalse(this.context.containsBean("foo")); + assertThat(this.context.containsBean("foo")).isFalse(); } @Test public void propertyValueEqualsFalse() { load(MultiplePropertiesRequiredConfiguration.class, "property1=false", "property2=value2"); - assertFalse(this.context.containsBean("foo")); + assertThat(this.context.containsBean("foo")).isFalse(); } @Test public void propertyValueEqualsFALSE() { load(MultiplePropertiesRequiredConfiguration.class, "property1=FALSE", "property2=value2"); - assertFalse(this.context.containsBean("foo")); + assertThat(this.context.containsBean("foo")).isFalse(); } @Test public void relaxedName() { load(RelaxedPropertiesRequiredConfiguration.class, "spring.theRelaxedProperty=value1"); - assertTrue(this.context.containsBean("foo")); + assertThat(this.context.containsBean("foo")).isTrue(); } @Test public void prefixWithoutPeriod() throws Exception { load(RelaxedPropertiesRequiredConfigurationWithShortPrefix.class, "spring.property=value1"); - assertTrue(this.context.containsBean("foo")); + assertThat(this.context.containsBean("foo")).isTrue(); } @Test public void nonRelaxedName() throws Exception { load(NonRelaxedPropertiesRequiredConfiguration.class, "theRelaxedProperty=value1"); - assertFalse(this.context.containsBean("foo")); + assertThat(this.context.containsBean("foo")).isFalse(); } @Test // Enabled by default public void enabledIfNotConfiguredOtherwise() { load(EnabledIfNotConfiguredOtherwiseConfig.class); - assertTrue(this.context.containsBean("foo")); + assertThat(this.context.containsBean("foo")).isTrue(); } @Test public void enabledIfNotConfiguredOtherwiseWithConfig() { load(EnabledIfNotConfiguredOtherwiseConfig.class, "simple.myProperty:false"); - assertFalse(this.context.containsBean("foo")); + assertThat(this.context.containsBean("foo")).isFalse(); } @Test public void enabledIfNotConfiguredOtherwiseWithConfigDifferentCase() { load(EnabledIfNotConfiguredOtherwiseConfig.class, "simple.my-property:FALSE"); - assertFalse(this.context.containsBean("foo")); + assertThat(this.context.containsBean("foo")).isFalse(); } @Test // Disabled by default public void disableIfNotConfiguredOtherwise() { load(DisabledIfNotConfiguredOtherwiseConfig.class); - assertFalse(this.context.containsBean("foo")); + assertThat(this.context.containsBean("foo")).isFalse(); } @Test public void disableIfNotConfiguredOtherwiseWithConfig() { load(DisabledIfNotConfiguredOtherwiseConfig.class, "simple.myProperty:true"); - assertTrue(this.context.containsBean("foo")); + assertThat(this.context.containsBean("foo")).isTrue(); } @Test public void disableIfNotConfiguredOtherwiseWithConfigDifferentCase() { load(DisabledIfNotConfiguredOtherwiseConfig.class, "simple.myproperty:TrUe"); - assertTrue(this.context.containsBean("foo")); + assertThat(this.context.containsBean("foo")).isTrue(); } @Test public void simpleValueIsSet() { load(SimpleValueConfig.class, "simple.myProperty:bar"); - assertTrue(this.context.containsBean("foo")); + assertThat(this.context.containsBean("foo")).isTrue(); } @Test public void caseInsensitive() { load(SimpleValueConfig.class, "simple.myProperty:BaR"); - assertTrue(this.context.containsBean("foo")); + assertThat(this.context.containsBean("foo")).isTrue(); } @Test public void defaultValueIsSet() { load(DefaultValueConfig.class, "simple.myProperty:bar"); - assertTrue(this.context.containsBean("foo")); + assertThat(this.context.containsBean("foo")).isTrue(); } @Test public void defaultValueIsNotSet() { load(DefaultValueConfig.class); - assertTrue(this.context.containsBean("foo")); + assertThat(this.context.containsBean("foo")).isTrue(); } @Test public void defaultValueIsSetDifferentValue() { load(DefaultValueConfig.class, "simple.myProperty:another"); - assertFalse(this.context.containsBean("foo")); + assertThat(this.context.containsBean("foo")).isFalse(); } @Test public void prefix() { load(PrefixValueConfig.class, "simple.myProperty:bar"); - assertTrue(this.context.containsBean("foo")); + assertThat(this.context.containsBean("foo")).isTrue(); } @Test public void relaxedEnabledByDefault() { load(PrefixValueConfig.class, "simple.myProperty:bar"); - assertTrue(this.context.containsBean("foo")); + assertThat(this.context.containsBean("foo")).isTrue(); } @Test public void strictNameMatch() { load(StrictNameConfig.class, "simple.my-property:bar"); - assertTrue(this.context.containsBean("foo")); + assertThat(this.context.containsBean("foo")).isTrue(); } @Test public void strictNameNoMatch() { load(StrictNameConfig.class, "simple.myProperty:bar"); - assertFalse(this.context.containsBean("foo")); + assertThat(this.context.containsBean("foo")).isFalse(); } @Test public void multiValuesAllSet() { load(MultiValuesConfig.class, "simple.my-property:bar", "simple.my-another-property:bar"); - assertTrue(this.context.containsBean("foo")); + assertThat(this.context.containsBean("foo")).isTrue(); } @Test public void multiValuesOnlyOneSet() { load(MultiValuesConfig.class, "simple.my-property:bar"); - assertFalse(this.context.containsBean("foo")); + assertThat(this.context.containsBean("foo")).isFalse(); } @Test public void usingValueAttribute() throws Exception { load(ValueAttribute.class, "some.property"); - assertTrue(this.context.containsBean("foo")); + assertThat(this.context.containsBean("foo")).isTrue(); } @Test diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnResourceTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnResourceTests.java index f0adf99c2f..0ccd64e1e6 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnResourceTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnResourceTests.java @@ -23,9 +23,7 @@ import org.springframework.context.annotation.AnnotationConfigApplicationContext import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; -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 ConditionalOnResource}. @@ -40,8 +38,8 @@ public class ConditionalOnResourceTests { public void testResourceExists() { this.context.register(BasicConfiguration.class); this.context.refresh(); - assertTrue(this.context.containsBean("foo")); - assertEquals("foo", this.context.getBean("foo")); + assertThat(this.context.containsBean("foo")).isTrue(); + assertThat(this.context.getBean("foo")).isEqualTo("foo"); } @Test @@ -49,15 +47,15 @@ public class ConditionalOnResourceTests { EnvironmentTestUtils.addEnvironment(this.context, "schema=schema.sql"); this.context.register(PlaceholderConfiguration.class); this.context.refresh(); - assertTrue(this.context.containsBean("foo")); - assertEquals("foo", this.context.getBean("foo")); + assertThat(this.context.containsBean("foo")).isTrue(); + assertThat(this.context.getBean("foo")).isEqualTo("foo"); } @Test public void testResourceNotExists() { this.context.register(MissingConfiguration.class); this.context.refresh(); - assertFalse(this.context.containsBean("foo")); + assertThat(this.context.containsBean("foo")).isFalse(); } @Configuration diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnSingleCandidateTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnSingleCandidateTests.java index d3031b597b..d5ee6fcd70 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnSingleCandidateTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnSingleCandidateTests.java @@ -26,10 +26,8 @@ import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Primary; +import static org.assertj.core.api.Assertions.assertThat; import static org.hamcrest.CoreMatchers.isA; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; /** * Tests for {@link ConditionalOnSingleCandidate}. @@ -53,36 +51,36 @@ public class ConditionalOnSingleCandidateTests { @Test public void singleCandidateNoCandidate() { load(OnBeanSingleCandidateConfiguration.class); - assertFalse(this.context.containsBean("baz")); + assertThat(this.context.containsBean("baz")).isFalse(); } @Test public void singleCandidateOneCandidate() { load(FooConfiguration.class, OnBeanSingleCandidateConfiguration.class); - assertTrue(this.context.containsBean("baz")); - assertEquals("foo", this.context.getBean("baz")); + assertThat(this.context.containsBean("baz")).isTrue(); + assertThat(this.context.getBean("baz")).isEqualTo("foo"); } @Test public void singleCandidateMultipleCandidates() { load(FooConfiguration.class, BarConfiguration.class, OnBeanSingleCandidateConfiguration.class); - assertFalse(this.context.containsBean("baz")); + assertThat(this.context.containsBean("baz")).isFalse(); } @Test public void singleCandidateMultipleCandidatesOnePrimary() { load(FooPrimaryConfiguration.class, BarConfiguration.class, OnBeanSingleCandidateConfiguration.class); - assertTrue(this.context.containsBean("baz")); - assertEquals("foo", this.context.getBean("baz")); + assertThat(this.context.containsBean("baz")).isTrue(); + assertThat(this.context.getBean("baz")).isEqualTo("foo"); } @Test public void singleCandidateMultipleCandidatesMultiplePrimary() { load(FooPrimaryConfiguration.class, BarPrimaryConfiguration.class, OnBeanSingleCandidateConfiguration.class); - assertFalse(this.context.containsBean("baz")); + assertThat(this.context.containsBean("baz")).isFalse(); } @Test diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnWebApplicationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnWebApplicationTests.java index dfaf827ff8..087d742a3a 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnWebApplicationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnWebApplicationTests.java @@ -23,9 +23,7 @@ import org.springframework.context.annotation.Configuration; import org.springframework.mock.web.MockServletContext; import org.springframework.web.context.support.AnnotationConfigWebApplicationContext; -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 ConditionalOnWebApplication}. @@ -41,8 +39,8 @@ public class ConditionalOnWebApplicationTests { this.context.register(BasicConfiguration.class); this.context.setServletContext(new MockServletContext()); this.context.refresh(); - assertTrue(this.context.containsBean("foo")); - assertEquals("foo", this.context.getBean("foo")); + assertThat(this.context.containsBean("foo")).isTrue(); + assertThat(this.context.getBean("foo")).isEqualTo("foo"); } @Test @@ -50,7 +48,7 @@ public class ConditionalOnWebApplicationTests { this.context.register(MissingConfiguration.class); this.context.setServletContext(new MockServletContext()); this.context.refresh(); - assertFalse(this.context.containsBean("foo")); + assertThat(this.context.containsBean("foo")).isFalse(); } @Configuration diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/NoneNestedConditionsTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/NoneNestedConditionsTests.java index d8275ddbae..d3dd8469b3 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/NoneNestedConditionsTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/NoneNestedConditionsTests.java @@ -24,8 +24,7 @@ import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Conditional; 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 for {@link NoneNestedConditions}. @@ -35,28 +34,28 @@ public class NoneNestedConditionsTests { @Test public void neither() throws Exception { AnnotationConfigApplicationContext context = load(Config.class); - assertThat(context.containsBean("myBean"), equalTo(true)); + assertThat(context.containsBean("myBean")).isTrue(); context.close(); } @Test public void propertyA() throws Exception { AnnotationConfigApplicationContext context = load(Config.class, "a:a"); - assertThat(context.containsBean("myBean"), equalTo(false)); + assertThat(context.containsBean("myBean")).isFalse(); context.close(); } @Test public void propertyB() throws Exception { AnnotationConfigApplicationContext context = load(Config.class, "b:b"); - assertThat(context.containsBean("myBean"), equalTo(false)); + assertThat(context.containsBean("myBean")).isFalse(); context.close(); } @Test public void both() throws Exception { AnnotationConfigApplicationContext context = load(Config.class, "a:a", "b:b"); - assertThat(context.containsBean("myBean"), equalTo(false)); + assertThat(context.containsBean("myBean")).isFalse(); context.close(); } diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ResourceConditionTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ResourceConditionTests.java index b7c94008d6..41c682bcf4 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ResourceConditionTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ResourceConditionTests.java @@ -26,8 +26,7 @@ import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Conditional; import org.springframework.context.annotation.Configuration; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * Test for {@link ResourceCondition}. @@ -48,20 +47,20 @@ public class ResourceConditionTests { @Test public void defaultResourceAndNoExplicitKey() { load(DefaultLocationConfiguration.class); - assertTrue(this.context.containsBean("foo")); + assertThat(this.context.containsBean("foo")).isTrue(); } @Test public void unknownDefaultLocationAndNoExplicitKey() { load(UnknownDefaultLocationConfiguration.class); - assertFalse(this.context.containsBean("foo")); + assertThat(this.context.containsBean("foo")).isFalse(); } @Test public void unknownDefaultLocationAndExplicitKeyToResource() { load(UnknownDefaultLocationConfiguration.class, "spring.foo.test.config=logging.properties"); - assertTrue(this.context.containsBean("foo")); + assertThat(this.context.containsBean("foo")).isTrue(); } private void load(Class config, String... environment) { diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/context/ConfigurationPropertiesAutoConfigurationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/context/ConfigurationPropertiesAutoConfigurationTests.java index fcf001babc..297d9d58bd 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/context/ConfigurationPropertiesAutoConfigurationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/context/ConfigurationPropertiesAutoConfigurationTests.java @@ -26,8 +26,7 @@ import org.springframework.context.annotation.AnnotationConfigApplicationContext import org.springframework.context.annotation.Configuration; import org.springframework.stereotype.Component; -import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link ConfigurationPropertiesAutoConfiguration}. @@ -48,13 +47,13 @@ public class ConfigurationPropertiesAutoConfigurationTests { @Test public void processAnnotatedBean() { load(new Class[] { AutoConfig.class, SampleBean.class }, "foo.name:test"); - assertThat(this.context.getBean(SampleBean.class).getName(), equalTo("test")); + assertThat(this.context.getBean(SampleBean.class).getName()).isEqualTo("test"); } @Test public void processAnnotatedBeanNoAutoConfig() { load(new Class[] { SampleBean.class }, "foo.name:test"); - assertThat(this.context.getBean(SampleBean.class).getName(), equalTo("default")); + assertThat(this.context.getBean(SampleBean.class).getName()).isEqualTo("default"); } private void load(Class[] configs, String... environment) { diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/dao/PersistenceExceptionTranslationAutoConfigurationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/dao/PersistenceExceptionTranslationAutoConfigurationTests.java index cb233bfdd9..94db535cc4 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/dao/PersistenceExceptionTranslationAutoConfigurationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/dao/PersistenceExceptionTranslationAutoConfigurationTests.java @@ -34,10 +34,7 @@ import org.springframework.dao.InvalidDataAccessApiUsageException; import org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor; import org.springframework.stereotype.Repository; -import static org.hamcrest.Matchers.empty; -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; /** * @@ -62,8 +59,8 @@ public class PersistenceExceptionTranslationAutoConfigurationTests { PersistenceExceptionTranslationAutoConfiguration.class); Map beans = this.context .getBeansOfType(PersistenceExceptionTranslationPostProcessor.class); - assertThat(beans.size(), is(equalTo(1))); - assertThat(beans.values().iterator().next().isProxyTargetClass(), equalTo(true)); + assertThat(beans).hasSize(1); + assertThat(beans.values().iterator().next().isProxyTargetClass()).isTrue(); } @Test @@ -75,7 +72,7 @@ public class PersistenceExceptionTranslationAutoConfigurationTests { this.context.refresh(); Map beans = this.context .getBeansOfType(PersistenceExceptionTranslationPostProcessor.class); - assertThat(beans.entrySet(), empty()); + assertThat(beans.entrySet()).isEmpty(); } @Test(expected = IllegalArgumentException.class) diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/cassandra/CassandraDataAutoConfigurationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/cassandra/CassandraDataAutoConfigurationTests.java index e0ecbd3767..76ee196861 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/cassandra/CassandraDataAutoConfigurationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/cassandra/CassandraDataAutoConfigurationTests.java @@ -29,7 +29,7 @@ import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.FilterType; import org.springframework.data.cassandra.core.CassandraTemplate; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; /** @@ -55,7 +55,8 @@ public class CassandraDataAutoConfigurationTests { PropertyPlaceholderAutoConfiguration.class, CassandraAutoConfiguration.class, CassandraDataAutoConfiguration.class); this.context.refresh(); - assertEquals(1, this.context.getBeanNamesForType(CassandraTemplate.class).length); + assertThat(this.context.getBeanNamesForType(CassandraTemplate.class).length) + .isEqualTo(1); } @Configuration diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/cassandra/CassandraRepositoriesAutoConfigurationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/cassandra/CassandraRepositoriesAutoConfigurationTests.java index 1964c6d884..aa5fe1f03d 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/cassandra/CassandraRepositoriesAutoConfigurationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/cassandra/CassandraRepositoriesAutoConfigurationTests.java @@ -36,7 +36,7 @@ import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.FilterType; import org.springframework.data.cassandra.repository.config.EnableCassandraRepositories; -import static org.junit.Assert.assertNotNull; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; /** @@ -61,20 +61,20 @@ public class CassandraRepositoriesAutoConfigurationTests { @Test public void testDefaultRepositoryConfiguration() { addConfigurations(TestConfiguration.class); - assertNotNull(this.context.getBean(CityRepository.class)); - assertNotNull(this.context.getBean(Cluster.class)); + assertThat(this.context.getBean(CityRepository.class)).isNotNull(); + assertThat(this.context.getBean(Cluster.class)).isNotNull(); } @Test public void testNoRepositoryConfiguration() { addConfigurations(TestExcludeConfiguration.class, EmptyConfiguration.class); - assertNotNull(this.context.getBean(Cluster.class)); + assertThat(this.context.getBean(Cluster.class)).isNotNull(); } @Test public void doesNotTriggerDefaultRepositoryDetectionIfCustomized() { addConfigurations(TestExcludeConfiguration.class, CustomizedConfiguration.class); - assertNotNull(this.context.getBean(CityCassandraRepository.class)); + assertThat(this.context.getBean(CityCassandraRepository.class)).isNotNull(); } private void addConfigurations(Class... configurations) { diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/elasticsearch/ElasticsearchAutoConfigurationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/elasticsearch/ElasticsearchAutoConfigurationTests.java index 5756cb7bf1..20a482c0e7 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/elasticsearch/ElasticsearchAutoConfigurationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/elasticsearch/ElasticsearchAutoConfigurationTests.java @@ -30,11 +30,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.hamcrest.Matchers.is; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; /** @@ -66,11 +62,11 @@ public class ElasticsearchAutoConfigurationTests { this.context.register(PropertyPlaceholderAutoConfiguration.class, ElasticsearchAutoConfiguration.class); this.context.refresh(); - assertEquals(1, this.context.getBeanNamesForType(Client.class).length); + assertThat(this.context.getBeanNamesForType(Client.class).length).isEqualTo(1); NodeClient client = (NodeClient) this.context.getBean(Client.class); - assertThat(client.settings().get("foo.bar"), is(equalTo("baz"))); - assertThat(client.settings().get("node.local"), is(equalTo("true"))); - assertThat(client.settings().get("http.enabled"), is(equalTo("false"))); + assertThat(client.settings().get("foo.bar")).isEqualTo("baz"); + assertThat(client.settings().get("node.local")).isEqualTo("true"); + assertThat(client.settings().get("http.enabled")).isEqualTo("false"); } @Test @@ -86,12 +82,12 @@ public class ElasticsearchAutoConfigurationTests { this.context.register(PropertyPlaceholderAutoConfiguration.class, ElasticsearchAutoConfiguration.class); this.context.refresh(); - assertEquals(1, this.context.getBeanNamesForType(Client.class).length); + assertThat(this.context.getBeanNamesForType(Client.class).length).isEqualTo(1); NodeClient client = (NodeClient) this.context.getBean(Client.class); - assertThat(client.settings().get("foo.bar"), is(equalTo("baz"))); - assertThat(client.settings().get("node.local"), is(equalTo("false"))); - assertThat(client.settings().get("node.data"), is(equalTo("true"))); - assertThat(client.settings().get("http.enabled"), is(equalTo("true"))); + assertThat(client.settings().get("foo.bar")).isEqualTo("baz"); + assertThat(client.settings().get("node.local")).isEqualTo("false"); + assertThat(client.settings().get("node.data")).isEqualTo("true"); + assertThat(client.settings().get("http.enabled")).isEqualTo("true"); } @Test @@ -101,8 +97,9 @@ public class ElasticsearchAutoConfigurationTests { PropertyPlaceholderAutoConfiguration.class, ElasticsearchAutoConfiguration.class); this.context.refresh(); - assertEquals(1, this.context.getBeanNamesForType(Client.class).length); - assertSame(this.context.getBean("myClient"), this.context.getBean(Client.class)); + assertThat(this.context.getBeanNamesForType(Client.class).length).isEqualTo(1); + assertThat(this.context.getBean("myClient")) + .isSameAs(this.context.getBean(Client.class)); } @Test diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/elasticsearch/ElasticsearchDataAutoConfigurationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/elasticsearch/ElasticsearchDataAutoConfigurationTests.java index 0aa14bc9cd..dbf2985e57 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/elasticsearch/ElasticsearchDataAutoConfigurationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/elasticsearch/ElasticsearchDataAutoConfigurationTests.java @@ -26,7 +26,7 @@ import org.springframework.data.elasticsearch.core.ElasticsearchTemplate; import org.springframework.data.elasticsearch.core.convert.ElasticsearchConverter; import org.springframework.data.elasticsearch.core.mapping.SimpleElasticsearchMappingContext; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link ElasticsearchDataAutoConfiguration}. @@ -55,8 +55,8 @@ public class ElasticsearchDataAutoConfigurationTests { ElasticsearchAutoConfiguration.class, ElasticsearchDataAutoConfiguration.class); this.context.refresh(); - assertEquals(1, - this.context.getBeanNamesForType(ElasticsearchTemplate.class).length); + assertThat(this.context.getBeanNamesForType(ElasticsearchTemplate.class)) + .hasSize(1); } @Test @@ -69,8 +69,9 @@ public class ElasticsearchDataAutoConfigurationTests { ElasticsearchAutoConfiguration.class, ElasticsearchDataAutoConfiguration.class); this.context.refresh(); - assertEquals(1, this.context - .getBeanNamesForType(SimpleElasticsearchMappingContext.class).length); + assertThat( + this.context.getBeanNamesForType(SimpleElasticsearchMappingContext.class)) + .hasSize(1); } @Test @@ -83,8 +84,8 @@ public class ElasticsearchDataAutoConfigurationTests { ElasticsearchAutoConfiguration.class, ElasticsearchDataAutoConfiguration.class); this.context.refresh(); - assertEquals(1, - this.context.getBeanNamesForType(ElasticsearchConverter.class).length); + assertThat(this.context.getBeanNamesForType(ElasticsearchConverter.class)) + .hasSize(1); } } diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/elasticsearch/ElasticsearchRepositoriesAutoConfigurationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/elasticsearch/ElasticsearchRepositoriesAutoConfigurationTests.java index 5161937857..7f4fc90015 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/elasticsearch/ElasticsearchRepositoriesAutoConfigurationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/elasticsearch/ElasticsearchRepositoriesAutoConfigurationTests.java @@ -31,7 +31,7 @@ import org.springframework.context.annotation.AnnotationConfigApplicationContext import org.springframework.context.annotation.Configuration; import org.springframework.data.elasticsearch.repository.config.EnableElasticsearchRepositories; -import static org.junit.Assert.assertNotNull; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link ElasticsearchRepositoriesAutoConfiguration}. @@ -57,8 +57,8 @@ public class ElasticsearchRepositoriesAutoConfigurationTests { ElasticsearchDataAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); this.context.refresh(); - assertNotNull(this.context.getBean(CityRepository.class)); - assertNotNull(this.context.getBean(Client.class)); + assertThat(this.context.getBean(CityRepository.class)).isNotNull(); + assertThat(this.context.getBean(Client.class)).isNotNull(); } @Test @@ -71,7 +71,7 @@ public class ElasticsearchRepositoriesAutoConfigurationTests { ElasticsearchDataAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); this.context.refresh(); - assertNotNull(this.context.getBean(Client.class)); + assertThat(this.context.getBean(Client.class)).isNotNull(); } @Test @@ -84,7 +84,7 @@ public class ElasticsearchRepositoriesAutoConfigurationTests { ElasticsearchDataAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); this.context.refresh(); - assertNotNull(this.context.getBean(CityElasticsearchDbRepository.class)); + assertThat(this.context.getBean(CityElasticsearchDbRepository.class)).isNotNull(); } private void addElasticsearchProperties(AnnotationConfigApplicationContext context) { diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/jpa/JpaRepositoriesAutoConfigurationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/jpa/JpaRepositoriesAutoConfigurationTests.java index 6f76c95272..8a89145143 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/jpa/JpaRepositoriesAutoConfigurationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/jpa/JpaRepositoriesAutoConfigurationTests.java @@ -37,7 +37,7 @@ import org.springframework.context.annotation.FilterType; import org.springframework.data.jpa.repository.config.EnableJpaRepositories; import org.springframework.transaction.PlatformTransactionManager; -import static org.junit.Assert.assertNotNull; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link JpaRepositoriesAutoConfiguration}. @@ -58,19 +58,19 @@ public class JpaRepositoriesAutoConfigurationTests { public void testDefaultRepositoryConfiguration() throws Exception { prepareApplicationContext(TestConfiguration.class); - assertNotNull(this.context.getBean(CityRepository.class)); - assertNotNull(this.context.getBean(PlatformTransactionManager.class)); - assertNotNull(this.context.getBean(EntityManagerFactory.class)); + assertThat(this.context.getBean(CityRepository.class)).isNotNull(); + assertThat(this.context.getBean(PlatformTransactionManager.class)).isNotNull(); + assertThat(this.context.getBean(EntityManagerFactory.class)).isNotNull(); } @Test public void testOverrideRepositoryConfiguration() throws Exception { prepareApplicationContext(CustomConfiguration.class); - - assertNotNull(this.context.getBean( - org.springframework.boot.autoconfigure.data.alt.jpa.CityJpaRepository.class)); - assertNotNull(this.context.getBean(PlatformTransactionManager.class)); - assertNotNull(this.context.getBean(EntityManagerFactory.class)); + assertThat(this.context.getBean( + org.springframework.boot.autoconfigure.data.alt.jpa.CityJpaRepository.class)) + .isNotNull(); + assertThat(this.context.getBean(PlatformTransactionManager.class)).isNotNull(); + assertThat(this.context.getBean(EntityManagerFactory.class)).isNotNull(); } @Test(expected = NoSuchBeanDefinitionException.class) diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/jpa/JpaWebAutoConfigurationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/jpa/JpaWebAutoConfigurationTests.java index dd77adf67f..f1f5d3e158 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/jpa/JpaWebAutoConfigurationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/jpa/JpaWebAutoConfigurationTests.java @@ -33,8 +33,7 @@ import org.springframework.mock.web.MockServletContext; import org.springframework.web.context.support.AnnotationConfigWebApplicationContext; import org.springframework.web.servlet.config.annotation.EnableWebMvc; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link SpringDataWebAutoConfiguration} and @@ -62,10 +61,11 @@ public class JpaWebAutoConfigurationTests { SpringDataWebAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); this.context.refresh(); - assertNotNull(this.context.getBean(CityRepository.class)); - assertNotNull(this.context.getBean(PageableHandlerMethodArgumentResolver.class)); - assertTrue(this.context.getBean(FormattingConversionService.class) - .canConvert(Long.class, City.class)); + assertThat(this.context.getBean(CityRepository.class)).isNotNull(); + assertThat(this.context.getBean(PageableHandlerMethodArgumentResolver.class)) + .isNotNull(); + assertThat(this.context.getBean(FormattingConversionService.class) + .canConvert(Long.class, City.class)).isTrue(); } @Configuration diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/mongo/MixedMongoRepositoriesAutoConfigurationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/mongo/MixedMongoRepositoriesAutoConfigurationTests.java index daa2eb16a9..a0ba645b1e 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/mongo/MixedMongoRepositoriesAutoConfigurationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/mongo/MixedMongoRepositoriesAutoConfigurationTests.java @@ -42,7 +42,7 @@ import org.springframework.core.type.AnnotationMetadata; import org.springframework.data.jpa.repository.config.EnableJpaRepositories; import org.springframework.data.mongodb.repository.config.EnableMongoRepositories; -import static org.junit.Assert.assertNotNull; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link MongoRepositoriesAutoConfiguration}. @@ -66,7 +66,7 @@ public class MixedMongoRepositoriesAutoConfigurationTests { "spring.datasource.initialize:false"); this.context.register(TestConfiguration.class, BaseConfiguration.class); this.context.refresh(); - assertNotNull(this.context.getBean(CountryRepository.class)); + assertThat(this.context.getBean(CountryRepository.class)).isNotNull(); } @Test @@ -76,8 +76,8 @@ public class MixedMongoRepositoriesAutoConfigurationTests { "spring.datasource.initialize:false"); this.context.register(MixedConfiguration.class, BaseConfiguration.class); this.context.refresh(); - assertNotNull(this.context.getBean(CountryRepository.class)); - assertNotNull(this.context.getBean(CityRepository.class)); + assertThat(this.context.getBean(CountryRepository.class)).isNotNull(); + assertThat(this.context.getBean(CityRepository.class)).isNotNull(); } @Test @@ -87,7 +87,7 @@ public class MixedMongoRepositoriesAutoConfigurationTests { "spring.datasource.initialize:false"); this.context.register(JpaConfiguration.class, BaseConfiguration.class); this.context.refresh(); - assertNotNull(this.context.getBean(CityRepository.class)); + assertThat(this.context.getBean(CityRepository.class)).isNotNull(); } @Test @@ -97,7 +97,7 @@ public class MixedMongoRepositoriesAutoConfigurationTests { "spring.datasource.initialize:false"); this.context.register(OverlapConfiguration.class, BaseConfiguration.class); this.context.refresh(); - assertNotNull(this.context.getBean(CityRepository.class)); + assertThat(this.context.getBean(CityRepository.class)).isNotNull(); } @Test @@ -109,7 +109,7 @@ public class MixedMongoRepositoriesAutoConfigurationTests { "spring.data.mongodb.repositories.enabled:false"); this.context.register(OverlapConfiguration.class, BaseConfiguration.class); this.context.refresh(); - assertNotNull(this.context.getBean(CityRepository.class)); + assertThat(this.context.getBean(CityRepository.class)).isNotNull(); } @Configuration diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/mongo/MongoDataAutoConfigurationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/mongo/MongoDataAutoConfigurationTests.java index 6c37d2f7d2..e50fc573a4 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/mongo/MongoDataAutoConfigurationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/mongo/MongoDataAutoConfigurationTests.java @@ -20,7 +20,6 @@ import java.util.Arrays; import java.util.Set; import com.mongodb.Mongo; -import org.hamcrest.Matchers; import org.junit.After; import org.junit.Rule; import org.junit.Test; @@ -46,10 +45,7 @@ import org.springframework.data.mongodb.core.mapping.MongoMappingContext; import org.springframework.data.mongodb.gridfs.GridFsTemplate; import org.springframework.test.util.ReflectionTestUtils; -import static org.hamcrest.Matchers.hasSize; -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; import static org.junit.Assert.fail; /** @@ -77,7 +73,8 @@ public class MongoDataAutoConfigurationTests { this.context = new AnnotationConfigApplicationContext( PropertyPlaceholderAutoConfiguration.class, MongoAutoConfiguration.class, MongoDataAutoConfiguration.class); - assertEquals(1, this.context.getBeanNamesForType(MongoTemplate.class).length); + assertThat(this.context.getBeanNamesForType(MongoTemplate.class).length) + .isEqualTo(1); } @Test @@ -88,7 +85,8 @@ public class MongoDataAutoConfigurationTests { this.context.register(PropertyPlaceholderAutoConfiguration.class, MongoAutoConfiguration.class, MongoDataAutoConfiguration.class); this.context.refresh(); - assertEquals(1, this.context.getBeanNamesForType(GridFsTemplate.class).length); + assertThat(this.context.getBeanNamesForType(GridFsTemplate.class).length) + .isEqualTo(1); } @Test @@ -99,8 +97,8 @@ public class MongoDataAutoConfigurationTests { MongoAutoConfiguration.class, MongoDataAutoConfiguration.class); this.context.refresh(); MongoTemplate template = this.context.getBean(MongoTemplate.class); - assertTrue(template.getConverter().getConversionService().canConvert(Mongo.class, - Boolean.class)); + assertThat(template.getConverter().getConversionService().canConvert(Mongo.class, + Boolean.class)).isTrue(); } @Test @@ -155,7 +153,7 @@ public class MongoDataAutoConfigurationTests { .getBean(MongoMappingContext.class); FieldNamingStrategy fieldNamingStrategy = (FieldNamingStrategy) ReflectionTestUtils .getField(mappingContext, "fieldNamingStrategy"); - assertEquals(expectedType, fieldNamingStrategy.getClass()); + assertThat(fieldNamingStrategy.getClass()).isEqualTo(expectedType); } @SuppressWarnings({ "unchecked", "rawtypes" }) @@ -163,8 +161,7 @@ public class MongoDataAutoConfigurationTests { Class... types) { Set initialEntitySet = (Set) ReflectionTestUtils .getField(mappingContext, "initialEntitySet"); - assertThat(initialEntitySet, hasSize(types.length)); - assertThat(initialEntitySet, Matchers.hasItems(types)); + assertThat(initialEntitySet).containsOnly(types); } @Configuration diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/mongo/MongoRepositoriesAutoConfigurationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/mongo/MongoRepositoriesAutoConfigurationTests.java index e52db65921..c909f2f7ed 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/mongo/MongoRepositoriesAutoConfigurationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/mongo/MongoRepositoriesAutoConfigurationTests.java @@ -37,11 +37,7 @@ import org.springframework.data.mongodb.core.mapping.MongoMappingContext; import org.springframework.data.mongodb.repository.config.EnableMongoRepositories; import org.springframework.test.util.ReflectionTestUtils; -import static org.hamcrest.CoreMatchers.equalTo; -import static org.hamcrest.CoreMatchers.instanceOf; -import static org.hamcrest.CoreMatchers.is; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link MongoRepositoriesAutoConfiguration}. @@ -62,15 +58,15 @@ public class MongoRepositoriesAutoConfigurationTests { public void testDefaultRepositoryConfiguration() throws Exception { prepareApplicationContext(TestConfiguration.class); - assertNotNull(this.context.getBean(CityRepository.class)); + assertThat(this.context.getBean(CityRepository.class)).isNotNull(); Mongo mongo = this.context.getBean(Mongo.class); - assertThat(mongo, is(instanceOf(MongoClient.class))); + assertThat(mongo).isInstanceOf(MongoClient.class); MongoMappingContext mappingContext = this.context .getBean(MongoMappingContext.class); @SuppressWarnings("unchecked") Set> entities = (Set>) ReflectionTestUtils .getField(mappingContext, "initialEntitySet"); - assertThat(entities.size(), is(equalTo(1))); + assertThat(entities).hasSize(1); } @Test @@ -78,14 +74,14 @@ public class MongoRepositoriesAutoConfigurationTests { prepareApplicationContext(EmptyConfiguration.class); Mongo mongo = this.context.getBean(Mongo.class); - assertThat(mongo, is(instanceOf(MongoClient.class))); + assertThat(mongo).isInstanceOf(MongoClient.class); } @Test public void doesNotTriggerDefaultRepositoryDetectionIfCustomized() { prepareApplicationContext(CustomizedConfiguration.class); - assertNotNull(this.context.getBean(CityMongoDbRepository.class)); + assertThat(this.context.getBean(CityMongoDbRepository.class)).isNotNull(); } @Test(expected = NoSuchBeanDefinitionException.class) diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/redis/RedisAutoConfigurationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/redis/RedisAutoConfigurationTests.java index 77873afc3b..8249745256 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/redis/RedisAutoConfigurationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/redis/RedisAutoConfigurationTests.java @@ -32,9 +32,7 @@ import org.springframework.data.redis.core.RedisOperations; import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.util.StringUtils; -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; /** * Tests for {@link RedisAutoConfiguration}. @@ -63,34 +61,36 @@ public class RedisAutoConfigurationTests { @Test public void testDefaultRedisConfiguration() throws Exception { load(); - assertNotNull(this.context.getBean("redisTemplate", RedisOperations.class)); - assertNotNull(this.context.getBean(StringRedisTemplate.class)); + assertThat(this.context.getBean("redisTemplate", RedisOperations.class)) + .isNotNull(); + assertThat(this.context.getBean(StringRedisTemplate.class)).isNotNull(); } @Test public void testOverrideRedisConfiguration() throws Exception { load("spring.redis.host:foo", "spring.redis.database:1"); - assertEquals("foo", - this.context.getBean(JedisConnectionFactory.class).getHostName()); - assertEquals(1, this.context.getBean(JedisConnectionFactory.class).getDatabase()); + assertThat(this.context.getBean(JedisConnectionFactory.class).getHostName()) + .isEqualTo("foo"); + assertThat(this.context.getBean(JedisConnectionFactory.class).getDatabase()) + .isEqualTo(1); } @Test public void testRedisConfigurationWithPool() throws Exception { load("spring.redis.host:foo", "spring.redis.pool.max-idle:1"); - assertEquals("foo", - this.context.getBean(JedisConnectionFactory.class).getHostName()); - assertEquals(1, this.context.getBean(JedisConnectionFactory.class).getPoolConfig() - .getMaxIdle()); + assertThat(this.context.getBean(JedisConnectionFactory.class).getHostName()) + .isEqualTo("foo"); + assertThat(this.context.getBean(JedisConnectionFactory.class).getPoolConfig() + .getMaxIdle()).isEqualTo(1); } @Test public void testRedisConfigurationWithTimeout() throws Exception { load("spring.redis.host:foo", "spring.redis.timeout:100"); - assertEquals("foo", - this.context.getBean(JedisConnectionFactory.class).getHostName()); - assertEquals(100, - this.context.getBean(JedisConnectionFactory.class).getTimeout()); + assertThat(this.context.getBean(JedisConnectionFactory.class).getHostName()) + .isEqualTo("foo"); + assertThat(this.context.getBean(JedisConnectionFactory.class).getTimeout()) + .isEqualTo(100); } @Test @@ -99,9 +99,8 @@ public class RedisAutoConfigurationTests { if (isAtLeastOneSentinelAvailable(sentinels)) { load("spring.redis.sentinel.master:mymaster", "spring.redis.sentinel.nodes:" + StringUtils.collectionToCommaDelimitedString(sentinels)); - - assertTrue(this.context.getBean(JedisConnectionFactory.class) - .isRedisSentinelAware()); + assertThat(this.context.getBean(JedisConnectionFactory.class) + .isRedisSentinelAware()).isTrue(); } } diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/rest/RepositoryRestMvcAutoConfigurationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/rest/RepositoryRestMvcAutoConfigurationTests.java index 087ffc6349..17f538c830 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/rest/RepositoryRestMvcAutoConfigurationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/rest/RepositoryRestMvcAutoConfigurationTests.java @@ -46,11 +46,7 @@ import org.springframework.mock.web.MockServletContext; import org.springframework.web.context.support.AnnotationConfigWebApplicationContext; import org.springframework.web.servlet.config.annotation.EnableWebMvc; -import static org.hamcrest.Matchers.greaterThan; -import static org.hamcrest.Matchers.is; -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 RepositoryRestMvcAutoConfiguration}. @@ -72,20 +68,23 @@ public class RepositoryRestMvcAutoConfigurationTests { @Test public void testDefaultRepositoryConfiguration() throws Exception { load(TestConfiguration.class); - assertNotNull(this.context.getBean(RepositoryRestMvcConfiguration.class)); + assertThat(this.context.getBean(RepositoryRestMvcConfiguration.class)) + .isNotNull(); } @Test public void testWithCustomBasePath() throws Exception { load(TestConfiguration.class, "spring.data.rest.base-path:foo"); - assertNotNull(this.context.getBean(RepositoryRestMvcConfiguration.class)); + assertThat(this.context.getBean(RepositoryRestMvcConfiguration.class)) + .isNotNull(); RepositoryRestConfiguration bean = this.context .getBean(RepositoryRestConfiguration.class); URI expectedUri = URI.create("/foo"); - assertEquals("Custom basePath not set", expectedUri, bean.getBaseUri()); + assertThat(bean.getBaseUri()).as("Custom basePath not set") + .isEqualTo(expectedUri); BaseUri baseUri = this.context.getBean(BaseUri.class); - assertEquals("Custom basePath has not been applied to BaseUri bean", expectedUri, - baseUri.getUri()); + assertThat(expectedUri).as("Custom basePath has not been applied to BaseUri bean") + .isEqualTo(baseUri.getUri()); } @Test @@ -99,34 +98,30 @@ public class RepositoryRestMvcAutoConfigurationTests { "spring.data.rest.return-body-on-create:false", "spring.data.rest.return-body-on-update:false", "spring.data.rest.enable-enum-translation:true"); - assertNotNull(this.context.getBean(RepositoryRestMvcConfiguration.class)); + assertThat(this.context.getBean(RepositoryRestMvcConfiguration.class)) + .isNotNull(); RepositoryRestConfiguration bean = this.context .getBean(RepositoryRestConfiguration.class); - assertEquals("Custom default page size not set", 42, bean.getDefaultPageSize()); - assertEquals("Custom max page size not set", 78, bean.getMaxPageSize()); - assertEquals("Custom page param name not set", "_page", bean.getPageParamName()); - assertEquals("Custom limit param name not set", "_limit", - bean.getLimitParamName()); - assertEquals("Custom sort param name not set", "_sort", bean.getSortParamName()); - assertEquals("Custom default media type not set", - MediaType.parseMediaType("application/my-json"), - bean.getDefaultMediaType()); - assertEquals("Custom return body on create flag not set", false, - bean.returnBodyOnCreate(null)); - assertEquals("Custom return body on update flag not set", false, - bean.returnBodyOnUpdate(null)); - assertEquals("Custom enable enum translation flag not set", true, - bean.isEnableEnumTranslation()); + assertThat(bean.getDefaultPageSize()).isEqualTo(42); + assertThat(bean.getMaxPageSize()).isEqualTo(78); + assertThat(bean.getPageParamName()).isEqualTo("_page"); + assertThat(bean.getLimitParamName()).isEqualTo("_limit"); + assertThat(bean.getSortParamName()).isEqualTo("_sort"); + assertThat(bean.getDefaultMediaType()) + .isEqualTo(MediaType.parseMediaType("application/my-json")); + assertThat(bean.returnBodyOnCreate(null)).isFalse(); + assertThat(bean.returnBodyOnUpdate(null)).isFalse(); + assertThat(bean.isEnableEnumTranslation()).isTrue(); } @Test public void backOffWithCustomConfiguration() { load(TestConfigurationWithRestMvcConfig.class, "spring.data.rest.base-path:foo"); - assertNotNull(this.context.getBean(RepositoryRestMvcConfiguration.class)); + assertThat(this.context.getBean(RepositoryRestMvcConfiguration.class)) + .isNotNull(); RepositoryRestConfiguration bean = this.context .getBean(RepositoryRestConfiguration.class); - assertEquals("Custom base URI should not have been set", URI.create(""), - bean.getBaseUri()); + assertThat(bean.getBaseUri()).isEqualTo(URI.create("")); } @Test @@ -143,16 +138,15 @@ public class RepositoryRestMvcAutoConfigurationTests { load(TestConfiguration.class); Map objectMappers = this.context .getBeansOfType(ObjectMapper.class); - assertThat(objectMappers.size(), is(greaterThan(1))); + assertThat(objectMappers.size()).isGreaterThan(1); this.context.getBean(ObjectMapper.class); } public void assertThatDateIsFormattedCorrectly(String beanName) throws JsonProcessingException { ObjectMapper objectMapper = this.context.getBean(beanName, ObjectMapper.class); - - assertEquals("\"2014-10\"", - objectMapper.writeValueAsString(new Date(1413387983267L))); + assertThat(objectMapper.writeValueAsString(new Date(1413387983267L))) + .isEqualTo("\"2014-10\""); } private void load(Class config, String... environment) { diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/solr/SolrRepositoriesAutoConfigurationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/solr/SolrRepositoriesAutoConfigurationTests.java index 1d077c2dc0..8bf13321e8 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/solr/SolrRepositoriesAutoConfigurationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/solr/SolrRepositoriesAutoConfigurationTests.java @@ -33,9 +33,7 @@ import org.springframework.context.annotation.AnnotationConfigApplicationContext import org.springframework.context.annotation.Configuration; import org.springframework.data.solr.repository.config.EnableSolrRepositories; -import static org.hamcrest.Matchers.instanceOf; -import static org.hamcrest.Matchers.notNullValue; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link SolrRepositoriesAutoConfiguration}. @@ -55,23 +53,22 @@ public class SolrRepositoriesAutoConfigurationTests { @Test public void testDefaultRepositoryConfiguration() { initContext(TestConfiguration.class); - - assertThat(this.context.getBean(CityRepository.class), notNullValue()); - assertThat(this.context.getBean(SolrServer.class), - instanceOf(HttpSolrServer.class)); + assertThat(this.context.getBean(CityRepository.class)).isNotNull(); + assertThat(this.context.getBean(SolrServer.class)) + .isInstanceOf(HttpSolrServer.class); } @Test public void testNoRepositoryConfiguration() { initContext(EmptyConfiguration.class); - assertThat(this.context.getBean(SolrServer.class), - instanceOf(HttpSolrServer.class)); + assertThat(this.context.getBean(SolrServer.class)) + .isInstanceOf(HttpSolrServer.class); } @Test public void doesNotTriggerDefaultRepositoryDetectionIfCustomized() { initContext(CustomizedConfiguration.class); - assertThat(this.context.getBean(CitySolrRepository.class), notNullValue()); + assertThat(this.context.getBean(CitySolrRepository.class)).isNotNull(); } @Test(expected = NoSuchBeanDefinitionException.class) diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/web/SpringDataWebAutoConfigurationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/web/SpringDataWebAutoConfigurationTests.java index b20ec33931..e604eec23f 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/web/SpringDataWebAutoConfigurationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/web/SpringDataWebAutoConfigurationTests.java @@ -27,9 +27,7 @@ import org.springframework.data.web.PageableHandlerMethodArgumentResolver; import org.springframework.mock.web.MockServletContext; import org.springframework.web.context.support.AnnotationConfigWebApplicationContext; -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 SpringDataWebAutoConfiguration}. @@ -57,7 +55,7 @@ public class SpringDataWebAutoConfigurationTests { .setServletContext(new MockServletContext()); Map beans = this.context .getBeansOfType(PageableHandlerMethodArgumentResolver.class); - assertThat(beans.size(), is(equalTo(1))); + assertThat(beans).hasSize(1); } @Test @@ -68,7 +66,7 @@ public class SpringDataWebAutoConfigurationTests { this.context.refresh(); Map beans = this.context .getBeansOfType(PageableHandlerMethodArgumentResolver.class); - assertThat(beans.size(), is(equalTo(0))); + assertThat(beans).isEmpty(); } } diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/flyway/FlywayAutoConfigurationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/flyway/FlywayAutoConfigurationTests.java index 729af83a6a..85e4a1bf72 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/flyway/FlywayAutoConfigurationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/flyway/FlywayAutoConfigurationTests.java @@ -48,10 +48,7 @@ import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter; import org.springframework.stereotype.Component; -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 FlywayAutoConfiguration}. @@ -85,7 +82,7 @@ public class FlywayAutoConfigurationTests { public void noDataSource() throws Exception { registerAndRefresh(FlywayAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); - assertEquals(0, this.context.getBeanNamesForType(Flyway.class).length); + assertThat(this.context.getBeanNamesForType(Flyway.class).length).isEqualTo(0); } @Test @@ -96,7 +93,7 @@ public class FlywayAutoConfigurationTests { FlywayAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); Flyway flyway = this.context.getBean(Flyway.class); - assertNotNull(flyway.getDataSource()); + assertThat(flyway.getDataSource()).isNotNull(); } @Test @@ -105,7 +102,7 @@ public class FlywayAutoConfigurationTests { EmbeddedDataSourceConfiguration.class, FlywayAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); Flyway flyway = this.context.getBean(Flyway.class); - assertNotNull(flyway.getDataSource()); + assertThat(flyway.getDataSource()).isNotNull(); } @Test @@ -114,8 +111,7 @@ public class FlywayAutoConfigurationTests { FlywayAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); Flyway flyway = this.context.getBean(Flyway.class); - assertEquals("[classpath:db/migration]", - Arrays.asList(flyway.getLocations()).toString()); + assertThat(flyway.getLocations()).containsExactly("classpath:db/migration"); } @Test @@ -126,8 +122,8 @@ public class FlywayAutoConfigurationTests { FlywayAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); Flyway flyway = this.context.getBean(Flyway.class); - assertEquals("[classpath:db/changelog, classpath:db/migration]", - Arrays.asList(flyway.getLocations()).toString()); + assertThat(flyway.getLocations()).containsExactly("classpath:db/changelog", + "classpath:db/migration"); } @Test @@ -139,8 +135,8 @@ public class FlywayAutoConfigurationTests { FlywayAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); Flyway flyway = this.context.getBean(Flyway.class); - assertEquals("[classpath:db/changelog, classpath:db/migration]", - Arrays.asList(flyway.getLocations()).toString()); + assertThat(flyway.getLocations()).containsExactly("classpath:db/changelog", + "classpath:db/migration"); } @Test @@ -150,7 +146,7 @@ public class FlywayAutoConfigurationTests { FlywayAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); Flyway flyway = this.context.getBean(Flyway.class); - assertEquals("[public]", Arrays.asList(flyway.getSchemas()).toString()); + assertThat(Arrays.asList(flyway.getSchemas()).toString()).isEqualTo("[public]"); } @Test @@ -190,7 +186,7 @@ public class FlywayAutoConfigurationTests { registerAndRefresh(EmbeddedDataSourceConfiguration.class, FlywayAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class, MockFlywayMigrationStrategy.class); - assertNotNull(this.context.getBean(Flyway.class)); + assertThat(this.context.getBean(Flyway.class)).isNotNull(); this.context.getBean(MockFlywayMigrationStrategy.class).assertCalled(); } @@ -199,10 +195,10 @@ public class FlywayAutoConfigurationTests { registerAndRefresh(CustomFlywayMigrationInitializer.class, EmbeddedDataSourceConfiguration.class, FlywayAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); - assertNotNull(this.context.getBean(Flyway.class)); + assertThat(this.context.getBean(Flyway.class)).isNotNull(); FlywayMigrationInitializer initializer = this.context .getBean(FlywayMigrationInitializer.class); - assertThat(initializer.getOrder(), equalTo(Ordered.HIGHEST_PRECEDENCE)); + assertThat(initializer.getOrder()).isEqualTo(Ordered.HIGHEST_PRECEDENCE); } @Test @@ -219,8 +215,8 @@ public class FlywayAutoConfigurationTests { FlywayAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); Flyway flyway = this.context.getBean(Flyway.class); - assertThat(flyway.getBaselineVersion(), - equalTo(MigrationVersion.fromVersion("0"))); + assertThat(flyway.getBaselineVersion()) + .isEqualTo(MigrationVersion.fromVersion("0")); } @Test @@ -233,8 +229,8 @@ public class FlywayAutoConfigurationTests { FlywayAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); Flyway flyway = this.context.getBean(Flyway.class); - assertThat(flyway.getBaselineVersion(), - equalTo(MigrationVersion.fromVersion("1"))); + assertThat(flyway.getBaselineVersion()) + .isEqualTo(MigrationVersion.fromVersion("1")); } private void registerAndRefresh(Class... annotatedClasses) { @@ -301,7 +297,7 @@ public class FlywayAutoConfigurationTests { } public void assertCalled() { - assertThat(this.called, equalTo(true)); + assertThat(this.called).isTrue(); } } diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/freemarker/FreeMarkerAutoConfigurationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/freemarker/FreeMarkerAutoConfigurationTests.java index 798c1cd717..efda973961 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/freemarker/FreeMarkerAutoConfigurationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/freemarker/FreeMarkerAutoConfigurationTests.java @@ -41,11 +41,8 @@ import org.springframework.web.servlet.view.AbstractTemplateViewResolver; import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer; import org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver; +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.notNullValue; -import static org.junit.Assert.assertThat; /** * Tests for {@link FreeMarkerAutoConfiguration}. @@ -74,8 +71,8 @@ public class FreeMarkerAutoConfigurationTests { @Test public void defaultConfiguration() { registerAndRefreshContext(); - assertThat(this.context.getBean(FreeMarkerViewResolver.class), notNullValue()); - assertThat(this.context.getBean(FreeMarkerConfigurer.class), notNullValue()); + assertThat(this.context.getBean(FreeMarkerViewResolver.class)).isNotNull(); + assertThat(this.context.getBean(FreeMarkerConfigurer.class)).isNotNull(); } @Test @@ -104,8 +101,8 @@ public class FreeMarkerAutoConfigurationTests { registerAndRefreshContext(); MockHttpServletResponse response = render("home"); String result = response.getContentAsString(); - assertThat(result, containsString("home")); - assertThat(response.getContentType(), equalTo("text/html;charset=UTF-8")); + assertThat(result).contains("home"); + assertThat(response.getContentType()).isEqualTo("text/html;charset=UTF-8"); } @Test @@ -113,8 +110,8 @@ public class FreeMarkerAutoConfigurationTests { registerAndRefreshContext("spring.freemarker.contentType:application/json"); MockHttpServletResponse response = render("home"); String result = response.getContentAsString(); - assertThat(result, containsString("home")); - assertThat(response.getContentType(), equalTo("application/json;charset=UTF-8")); + assertThat(result).contains("home"); + assertThat(response.getContentType()).isEqualTo("application/json;charset=UTF-8"); } @Test @@ -122,7 +119,7 @@ public class FreeMarkerAutoConfigurationTests { registerAndRefreshContext("spring.freemarker.prefix:prefix/"); MockHttpServletResponse response = render("prefixed"); String result = response.getContentAsString(); - assertThat(result, containsString("prefixed")); + assertThat(result).contains("prefixed"); } @Test @@ -130,7 +127,7 @@ public class FreeMarkerAutoConfigurationTests { registerAndRefreshContext("spring.freemarker.suffix:.freemarker"); MockHttpServletResponse response = render("suffixed"); String result = response.getContentAsString(); - assertThat(result, containsString("suffixed")); + assertThat(result).contains("suffixed"); } @Test @@ -139,14 +136,14 @@ public class FreeMarkerAutoConfigurationTests { "spring.freemarker.templateLoaderPath:classpath:/custom-templates/"); MockHttpServletResponse response = render("custom"); String result = response.getContentAsString(); - assertThat(result, containsString("custom")); + assertThat(result).contains("custom"); } @Test public void disableCache() { registerAndRefreshContext("spring.freemarker.cache:false"); - assertThat(this.context.getBean(FreeMarkerViewResolver.class).getCacheLimit(), - equalTo(0)); + assertThat(this.context.getBean(FreeMarkerViewResolver.class).getCacheLimit()) + .isEqualTo(0); } @Test @@ -154,8 +151,8 @@ public class FreeMarkerAutoConfigurationTests { registerAndRefreshContext("spring.freemarker.allow-session-override:true"); AbstractTemplateViewResolver viewResolver = this.context .getBean(FreeMarkerViewResolver.class); - assertThat((Boolean) ReflectionTestUtils.getField(viewResolver, - "allowSessionOverride"), is(true)); + assertThat(ReflectionTestUtils.getField(viewResolver, "allowSessionOverride")) + .isEqualTo(true); } @SuppressWarnings("deprecation") @@ -163,7 +160,7 @@ public class FreeMarkerAutoConfigurationTests { public void customFreeMarkerSettings() { registerAndRefreshContext("spring.freemarker.settings.boolean_format:yup,nope"); assertThat(this.context.getBean(FreeMarkerConfigurer.class).getConfiguration() - .getSetting("boolean_format"), equalTo("yup,nope")); + .getSetting("boolean_format")).isEqualTo("yup,nope"); } @Test @@ -173,7 +170,7 @@ public class FreeMarkerAutoConfigurationTests { .getBean(FreeMarkerConfigurer.class); StringWriter writer = new StringWriter(); freemarker.getConfiguration().getTemplate("message.ftl").process(this, writer); - assertThat(writer.toString(), containsString("Hello World")); + assertThat(writer.toString()).contains("Hello World"); } @Test @@ -185,7 +182,7 @@ public class FreeMarkerAutoConfigurationTests { .getBean(freemarker.template.Configuration.class); StringWriter writer = new StringWriter(); freemarker.getTemplate("message.ftl").process(this, writer); - assertThat(writer.toString(), containsString("Hello World")); + assertThat(writer.toString()).contains("Hello World"); } finally { context.close(); @@ -206,7 +203,7 @@ public class FreeMarkerAutoConfigurationTests { FreeMarkerViewResolver resolver = this.context .getBean(FreeMarkerViewResolver.class); View view = resolver.resolveViewName(viewName, Locale.UK); - assertThat(view, notNullValue()); + assertThat(view).isNotNull(); HttpServletRequest request = new MockHttpServletRequest(); request.setAttribute(RequestContext.WEB_APPLICATION_CONTEXT_ATTRIBUTE, this.context); @@ -214,4 +211,5 @@ public class FreeMarkerAutoConfigurationTests { view.render(null, request, response); return response; } + } diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/freemarker/FreeMarkerTemplateAvailabilityProviderTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/freemarker/FreeMarkerTemplateAvailabilityProviderTests.java index d95ab8b862..46391b8cd3 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/freemarker/FreeMarkerTemplateAvailabilityProviderTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/freemarker/FreeMarkerTemplateAvailabilityProviderTests.java @@ -23,8 +23,7 @@ import org.springframework.core.io.DefaultResourceLoader; import org.springframework.core.io.ResourceLoader; import org.springframework.mock.env.MockEnvironment; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link FreeMarkerTemplateAvailabilityProvider}. @@ -41,35 +40,36 @@ public class FreeMarkerTemplateAvailabilityProviderTests { @Test public void availabilityOfTemplateInDefaultLocation() { - assertTrue(this.provider.isTemplateAvailable("home", this.environment, - getClass().getClassLoader(), this.resourceLoader)); + assertThat(this.provider.isTemplateAvailable("home", this.environment, + getClass().getClassLoader(), this.resourceLoader)).isTrue(); } @Test public void availabilityOfTemplateThatDoesNotExist() { - assertFalse(this.provider.isTemplateAvailable("whatever", this.environment, - getClass().getClassLoader(), this.resourceLoader)); + assertThat(this.provider.isTemplateAvailable("whatever", this.environment, + getClass().getClassLoader(), this.resourceLoader)).isFalse(); } @Test public void availabilityOfTemplateWithCustomLoaderPath() { this.environment.setProperty("spring.freemarker.template-loader-path", "classpath:/custom-templates/"); - assertTrue(this.provider.isTemplateAvailable("custom", this.environment, - getClass().getClassLoader(), this.resourceLoader)); + assertThat(this.provider.isTemplateAvailable("custom", this.environment, + getClass().getClassLoader(), this.resourceLoader)).isTrue(); } @Test public void availabilityOfTemplateWithCustomPrefix() { this.environment.setProperty("spring.freemarker.prefix", "prefix/"); - assertTrue(this.provider.isTemplateAvailable("prefixed", this.environment, - getClass().getClassLoader(), this.resourceLoader)); + assertThat(this.provider.isTemplateAvailable("prefixed", this.environment, + getClass().getClassLoader(), this.resourceLoader)).isTrue(); } @Test public void availabilityOfTemplateWithCustomSuffix() { this.environment.setProperty("spring.freemarker.suffix", ".freemarker"); - assertTrue(this.provider.isTemplateAvailable("suffixed", this.environment, - getClass().getClassLoader(), this.resourceLoader)); + assertThat(this.provider.isTemplateAvailable("suffixed", this.environment, + getClass().getClassLoader(), this.resourceLoader)).isTrue(); } + } diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/groovy/template/GroovyTemplateAutoConfigurationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/groovy/template/GroovyTemplateAutoConfigurationTests.java index 4edc8281e4..b9591c17d0 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/groovy/template/GroovyTemplateAutoConfigurationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/groovy/template/GroovyTemplateAutoConfigurationTests.java @@ -44,11 +44,7 @@ import org.springframework.web.servlet.view.groovy.GroovyMarkupConfig; import org.springframework.web.servlet.view.groovy.GroovyMarkupConfigurer; import org.springframework.web.servlet.view.groovy.GroovyMarkupViewResolver; -import static org.hamcrest.Matchers.containsString; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.notNullValue; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link GroovyTemplateAutoConfiguration}. @@ -75,7 +71,7 @@ public class GroovyTemplateAutoConfigurationTests { @Test public void defaultConfiguration() { registerAndRefreshContext(); - assertThat(this.context.getBean(GroovyMarkupViewResolver.class), notNullValue()); + assertThat(this.context.getBean(GroovyMarkupViewResolver.class)).isNotNull(); } @Test @@ -90,8 +86,8 @@ public class GroovyTemplateAutoConfigurationTests { registerAndRefreshContext(); MockHttpServletResponse response = render("home"); String result = response.getContentAsString(); - assertThat(result, containsString("home")); - assertThat(response.getContentType(), equalTo("text/html;charset=UTF-8")); + assertThat(result).contains("home"); + assertThat(response.getContentType()).isEqualTo("text/html;charset=UTF-8"); } @Test @@ -99,8 +95,8 @@ public class GroovyTemplateAutoConfigurationTests { registerAndRefreshContext(); MockHttpServletResponse response = render("includes"); String result = response.getContentAsString(); - assertThat(result, containsString("here")); - assertThat(response.getContentType(), equalTo("text/html;charset=UTF-8")); + assertThat(result).contains("here"); + assertThat(response.getContentType()).isEqualTo("text/html;charset=UTF-8"); } @Test @@ -108,8 +104,7 @@ public class GroovyTemplateAutoConfigurationTests { EnvironmentTestUtils.addEnvironment(this.context, "spring.groovy.template.enabled:false"); registerAndRefreshContext(); - assertThat(this.context.getBeanNamesForType(ViewResolver.class).length, - equalTo(0)); + assertThat(this.context.getBeanNamesForType(ViewResolver.class)).isEmpty(); } @Test @@ -117,8 +112,8 @@ public class GroovyTemplateAutoConfigurationTests { registerAndRefreshContext(); MockHttpServletResponse response = render("includes", Locale.FRENCH); String result = response.getContentAsString(); - assertThat(result, containsString("voila")); - assertThat(response.getContentType(), equalTo("text/html;charset=UTF-8")); + assertThat(result).contains("voila"); + assertThat(response.getContentType()).isEqualTo("text/html;charset=UTF-8"); } @Test @@ -126,8 +121,8 @@ public class GroovyTemplateAutoConfigurationTests { registerAndRefreshContext("spring.groovy.template.contentType:application/json"); MockHttpServletResponse response = render("home"); String result = response.getContentAsString(); - assertThat(result, containsString("home")); - assertThat(response.getContentType(), equalTo("application/json;charset=UTF-8")); + assertThat(result).contains("home"); + assertThat(response.getContentType()).isEqualTo("application/json;charset=UTF-8"); } @Test @@ -135,7 +130,7 @@ public class GroovyTemplateAutoConfigurationTests { registerAndRefreshContext("spring.groovy.template.prefix:prefix/"); MockHttpServletResponse response = render("prefixed"); String result = response.getContentAsString(); - assertThat(result, containsString("prefixed")); + assertThat(result).contains("prefixed"); } @Test @@ -143,7 +138,7 @@ public class GroovyTemplateAutoConfigurationTests { registerAndRefreshContext("spring.groovy.template.suffix:.groovytemplate"); MockHttpServletResponse response = render("suffixed"); String result = response.getContentAsString(); - assertThat(result, containsString("suffixed")); + assertThat(result).contains("suffixed"); } @Test @@ -152,14 +147,14 @@ public class GroovyTemplateAutoConfigurationTests { "spring.groovy.template.resource-loader-path:classpath:/custom-templates/"); MockHttpServletResponse response = render("custom"); String result = response.getContentAsString(); - assertThat(result, containsString("custom")); + assertThat(result).contains("custom"); } @Test public void disableCache() { registerAndRefreshContext("spring.groovy.template.cache:false"); - assertThat(this.context.getBean(GroovyMarkupViewResolver.class).getCacheLimit(), - equalTo(0)); + assertThat(this.context.getBean(GroovyMarkupViewResolver.class).getCacheLimit()) + .isEqualTo(0); } @Test @@ -172,15 +167,15 @@ public class GroovyTemplateAutoConfigurationTests { .make(new HashMap( Collections.singletonMap("greeting", "Hello World"))) .writeTo(writer); - assertThat(writer.toString(), containsString("Hello World")); + assertThat(writer.toString()).contains("Hello World"); } @Test public void customConfiguration() throws Exception { registerAndRefreshContext( "spring.groovy.template.configuration.auto-indent:true"); - assertThat(this.context.getBean(GroovyMarkupConfigurer.class).isAutoIndent(), - is(true)); + assertThat(this.context.getBean(GroovyMarkupConfigurer.class).isAutoIndent()) + .isEqualTo(true); } private void registerAndRefreshContext(String... env) { @@ -199,7 +194,7 @@ public class GroovyTemplateAutoConfigurationTests { GroovyMarkupViewResolver resolver = this.context .getBean(GroovyMarkupViewResolver.class); View view = resolver.resolveViewName(viewName, locale); - assertThat(view, notNullValue()); + assertThat(view).isNotNull(); HttpServletRequest request = new MockHttpServletRequest(); request.setAttribute(RequestContext.WEB_APPLICATION_CONTEXT_ATTRIBUTE, this.context); @@ -207,4 +202,5 @@ public class GroovyTemplateAutoConfigurationTests { view.render(null, request, response); return response; } + } diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/gson/GsonAutoConfigurationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/gson/GsonAutoConfigurationTests.java index 8f031c77b5..9e2c80ef52 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/gson/GsonAutoConfigurationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/gson/GsonAutoConfigurationTests.java @@ -23,7 +23,7 @@ import org.junit.Test; import org.springframework.context.annotation.AnnotationConfigApplicationContext; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link GsonAutoConfiguration}. @@ -51,7 +51,7 @@ public class GsonAutoConfigurationTests { this.context.register(GsonAutoConfiguration.class); this.context.refresh(); Gson gson = this.context.getBean(Gson.class); - assertEquals("{\"data\":\"hello\"}", gson.toJson(new DataObject())); + assertThat(gson.toJson(new DataObject())).isEqualTo("{\"data\":\"hello\"}"); } public class DataObject { diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/h2/H2ConsoleAutoConfigurationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/h2/H2ConsoleAutoConfigurationTests.java index 11cc4d5fd0..39e862a3e0 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/h2/H2ConsoleAutoConfigurationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/h2/H2ConsoleAutoConfigurationTests.java @@ -28,10 +28,7 @@ import org.springframework.boot.test.EnvironmentTestUtils; import org.springframework.mock.web.MockServletContext; import org.springframework.web.context.support.AnnotationConfigWebApplicationContext; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.hasItems; -import static org.hamcrest.Matchers.is; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link H2ConsoleAutoConfiguration} @@ -61,8 +58,7 @@ public class H2ConsoleAutoConfigurationTests { public void consoleIsDisabledByDefault() { this.context.register(H2ConsoleAutoConfiguration.class); this.context.refresh(); - assertThat(this.context.getBeansOfType(ServletRegistrationBean.class).size(), - is(equalTo(0))); + assertThat(this.context.getBeansOfType(ServletRegistrationBean.class)).isEmpty(); } @Test @@ -71,10 +67,9 @@ public class H2ConsoleAutoConfigurationTests { EnvironmentTestUtils.addEnvironment(this.context, "spring.h2.console.enabled:true"); this.context.refresh(); - assertThat(this.context.getBeansOfType(ServletRegistrationBean.class).size(), - is(equalTo(1))); - assertThat(this.context.getBean(ServletRegistrationBean.class).getUrlMappings(), - hasItems("/h2-console/*")); + assertThat(this.context.getBeansOfType(ServletRegistrationBean.class)).hasSize(1); + assertThat(this.context.getBean(ServletRegistrationBean.class).getUrlMappings()) + .contains("/h2-console/*"); } @Test @@ -93,10 +88,9 @@ public class H2ConsoleAutoConfigurationTests { EnvironmentTestUtils.addEnvironment(this.context, "spring.h2.console.enabled:true", "spring.h2.console.path:/custom/"); this.context.refresh(); - assertThat(this.context.getBeansOfType(ServletRegistrationBean.class).size(), - is(equalTo(1))); - assertThat(this.context.getBean(ServletRegistrationBean.class).getUrlMappings(), - hasItems("/custom/*")); + assertThat(this.context.getBeansOfType(ServletRegistrationBean.class)).hasSize(1); + assertThat(this.context.getBean(ServletRegistrationBean.class).getUrlMappings()) + .contains("/custom/*"); } @Test @@ -105,10 +99,9 @@ public class H2ConsoleAutoConfigurationTests { EnvironmentTestUtils.addEnvironment(this.context, "spring.h2.console.enabled:true", "spring.h2.console.path:/custom"); this.context.refresh(); - assertThat(this.context.getBeansOfType(ServletRegistrationBean.class).size(), - is(equalTo(1))); - assertThat(this.context.getBean(ServletRegistrationBean.class).getUrlMappings(), - hasItems("/custom/*")); + assertThat(this.context.getBeansOfType(ServletRegistrationBean.class)).hasSize(1); + assertThat(this.context.getBean(ServletRegistrationBean.class).getUrlMappings()) + .contains("/custom/*"); } } diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/hateoas/HypermediaAutoConfigurationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/hateoas/HypermediaAutoConfigurationTests.java index 99af6a3dbd..a1c030c752 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/hateoas/HypermediaAutoConfigurationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/hateoas/HypermediaAutoConfigurationTests.java @@ -41,12 +41,7 @@ import org.springframework.mock.web.MockServletContext; import org.springframework.web.context.support.AnnotationConfigWebApplicationContext; import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter; -import static org.hamcrest.Matchers.contains; -import static org.hamcrest.Matchers.containsInAnyOrder; -import static org.hamcrest.Matchers.is; -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; /** * Tests for {@link HypermediaAutoConfiguration}. @@ -73,9 +68,9 @@ public class HypermediaAutoConfigurationTests { this.context.register(BaseConfig.class); this.context.refresh(); LinkDiscoverers discoverers = this.context.getBean(LinkDiscoverers.class); - assertNotNull(discoverers); + assertThat(discoverers).isNotNull(); LinkDiscoverer discoverer = discoverers.getLinkDiscovererFor(MediaTypes.HAL_JSON); - assertTrue(HalLinkDiscoverer.class.isInstance(discoverer)); + assertThat(HalLinkDiscoverer.class.isInstance(discoverer)).isTrue(); } @Test @@ -85,7 +80,7 @@ public class HypermediaAutoConfigurationTests { this.context.register(BaseConfig.class); this.context.refresh(); EntityLinks discoverers = this.context.getBean(EntityLinks.class); - assertNotNull(discoverers); + assertThat(discoverers).isNotNull(); } @Test @@ -99,7 +94,7 @@ public class HypermediaAutoConfigurationTests { ObjectMapper objectMapper = this.context.getBean("_halObjectMapper", ObjectMapper.class); assertThat(objectMapper.getSerializationConfig() - .isEnabled(SerializationFeature.INDENT_OUTPUT), is(false)); + .isEnabled(SerializationFeature.INDENT_OUTPUT)).isFalse(); } @Test @@ -112,8 +107,8 @@ public class HypermediaAutoConfigurationTests { this.context.refresh(); ObjectMapper objectMapper = this.context.getBean("_halObjectMapper", ObjectMapper.class); - assertTrue(objectMapper.getSerializationConfig() - .isEnabled(SerializationFeature.INDENT_OUTPUT)); + assertThat(objectMapper.getSerializationConfig() + .isEnabled(SerializationFeature.INDENT_OUTPUT)).isTrue(); } @Test @@ -126,8 +121,8 @@ public class HypermediaAutoConfigurationTests { .getBean(RequestMappingHandlerAdapter.class); for (HttpMessageConverter converter : handlerAdapter.getMessageConverters()) { if (converter instanceof TypeConstrainedMappingJackson2HttpMessageConverter) { - assertThat(converter.getSupportedMediaTypes(), containsInAnyOrder( - MediaType.APPLICATION_JSON, MediaTypes.HAL_JSON)); + assertThat(converter.getSupportedMediaTypes()) + .contains(MediaType.APPLICATION_JSON, MediaTypes.HAL_JSON); } } } @@ -144,8 +139,8 @@ public class HypermediaAutoConfigurationTests { .getBean(RequestMappingHandlerAdapter.class); for (HttpMessageConverter converter : handlerAdapter.getMessageConverters()) { if (converter instanceof TypeConstrainedMappingJackson2HttpMessageConverter) { - assertThat(converter.getSupportedMediaTypes(), - contains(MediaTypes.HAL_JSON)); + assertThat(converter.getSupportedMediaTypes()) + .containsExactly(MediaTypes.HAL_JSON); } } } diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/hazelcast/HazelcastAutoConfigurationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/hazelcast/HazelcastAutoConfigurationTests.java index b63c52723d..4be20542cb 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/hazelcast/HazelcastAutoConfigurationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/hazelcast/HazelcastAutoConfigurationTests.java @@ -35,10 +35,7 @@ import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.io.ClassPathResource; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.hasKey; -import static org.hamcrest.Matchers.hasSize; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link HazelcastAutoConfiguration}. @@ -64,8 +61,8 @@ public class HazelcastAutoConfigurationTests { load(); // hazelcast.xml present in root classpath HazelcastInstance hazelcastInstance = this.context .getBean(HazelcastInstance.class); - assertThat(hazelcastInstance.getConfig().getConfigurationUrl(), - equalTo(new ClassPathResource("hazelcast.xml").getURL())); + assertThat(hazelcastInstance.getConfig().getConfigurationUrl()) + .isEqualTo(new ClassPathResource("hazelcast.xml").getURL()); } @Test @@ -78,8 +75,7 @@ public class HazelcastAutoConfigurationTests { .getBean(HazelcastInstance.class); Map queueConfigs = hazelcastInstance.getConfig() .getQueueConfigs(); - assertThat(queueConfigs.values(), hasSize(1)); - assertThat(queueConfigs, hasKey("foobar")); + assertThat(queueConfigs).hasSize(1).containsKey("foobar"); } finally { System.clearProperty(HazelcastConfigResourceCondition.CONFIG_SYSTEM_PROPERTY); @@ -92,10 +88,9 @@ public class HazelcastAutoConfigurationTests { + "hazelcast-specific.xml"); HazelcastInstance hazelcastInstance = this.context .getBean(HazelcastInstance.class); - assertThat(hazelcastInstance.getConfig().getConfigurationFile(), - equalTo(new ClassPathResource( - "org/springframework/boot/autoconfigure/hazelcast" - + "/hazelcast-specific.xml").getFile())); + assertThat(hazelcastInstance.getConfig().getConfigurationFile()).isEqualTo( + new ClassPathResource("org/springframework/boot/autoconfigure/hazelcast" + + "/hazelcast-specific.xml").getFile()); } @Test @@ -103,8 +98,8 @@ public class HazelcastAutoConfigurationTests { load("spring.hazelcast.config=hazelcast-default.xml"); HazelcastInstance hazelcastInstance = this.context .getBean(HazelcastInstance.class); - assertThat(hazelcastInstance.getConfig().getConfigurationUrl(), - equalTo(new ClassPathResource("hazelcast-default.xml").getURL())); + assertThat(hazelcastInstance.getConfig().getConfigurationUrl()) + .isEqualTo(new ClassPathResource("hazelcast-default.xml").getURL()); } @Test @@ -124,10 +119,10 @@ public class HazelcastAutoConfigurationTests { "spring.hazelcast.config=this-is-ignored.xml"); HazelcastInstance hazelcastInstance = this.context .getBean(HazelcastInstance.class); - assertThat(hazelcastInstance.getConfig().getInstanceName(), - equalTo("my-test-instance")); + assertThat(hazelcastInstance.getConfig().getInstanceName()) + .isEqualTo("my-test-instance"); // Should reuse any existing instance by default. - assertThat(hazelcastInstance, equalTo(existingHazelcastInstance)); + assertThat(hazelcastInstance).isEqualTo(existingHazelcastInstance); } finally { existingHazelcastInstance.shutdown(); @@ -141,8 +136,7 @@ public class HazelcastAutoConfigurationTests { .getBean(HazelcastInstance.class); Map queueConfigs = hazelcastInstance.getConfig() .getQueueConfigs(); - assertThat(queueConfigs.values(), hasSize(1)); - assertThat(queueConfigs, hasKey("another-queue")); + assertThat(queueConfigs).hasSize(1).containsKey("another-queue"); } private void load(String... environment) { diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/hazelcast/HazelcastJpaDependencyAutoConfigurationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/hazelcast/HazelcastJpaDependencyAutoConfigurationTests.java index 0ef71cb81a..d02dddd778 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/hazelcast/HazelcastJpaDependencyAutoConfigurationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/hazelcast/HazelcastJpaDependencyAutoConfigurationTests.java @@ -33,10 +33,7 @@ import org.springframework.context.annotation.AnnotationConfigApplicationContext import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; -import static org.hamcrest.CoreMatchers.not; -import static org.hamcrest.Matchers.hasItem; -import static org.hamcrest.Matchers.hasKey; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; /** @@ -58,27 +55,27 @@ public class HazelcastJpaDependencyAutoConfigurationTests { @Test public void registrationIfHazelcastInstanceHasRegularBeanName() { load(HazelcastConfiguration.class); - assertThat(getPostProcessor(), - hasKey("hazelcastInstanceJpaDependencyPostProcessor")); - assertThat(getEntityManagerFactoryDependencies(), hasItem("hazelcastInstance")); + assertThat(getPostProcessor()) + .containsKey("hazelcastInstanceJpaDependencyPostProcessor"); + assertThat(getEntityManagerFactoryDependencies()).contains("hazelcastInstance"); } @Test public void noRegistrationIfHazelcastInstanceHasCustomBeanName() { load(HazelcastCustomNameConfiguration.class); - assertThat(getEntityManagerFactoryDependencies(), - not(hasItem("hazelcastInstance"))); - assertThat(getPostProcessor(), - not(hasKey("hazelcastInstanceJpaDependencyPostProcessor"))); + assertThat(getEntityManagerFactoryDependencies()) + .doesNotContain("hazelcastInstance"); + assertThat(getPostProcessor()) + .doesNotContainKey("hazelcastInstanceJpaDependencyPostProcessor"); } @Test public void noRegistrationWithNoHazelcastInstance() { load(null); - assertThat(getEntityManagerFactoryDependencies(), - not(hasItem("hazelcastInstance"))); - assertThat(getPostProcessor(), - not(hasKey("hazelcastInstanceJpaDependencyPostProcessor"))); + assertThat(getEntityManagerFactoryDependencies()) + .doesNotContain("hazelcastInstance"); + assertThat(getPostProcessor()) + .doesNotContainKey("hazelcastInstanceJpaDependencyPostProcessor"); } @Test @@ -87,8 +84,8 @@ public class HazelcastJpaDependencyAutoConfigurationTests { this.context.register(HazelcastConfiguration.class, HazelcastJpaDependencyAutoConfiguration.class); this.context.refresh(); - assertThat(getPostProcessor(), - not(hasKey("hazelcastInstanceJpaDependencyPostProcessor"))); + assertThat(getPostProcessor()) + .doesNotContainKey("hazelcastInstanceJpaDependencyPostProcessor"); } private Map getPostProcessor() { diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/integration/IntegrationAutoConfigurationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/integration/IntegrationAutoConfigurationTests.java index 61ec8c668c..c1c1817d1e 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/integration/IntegrationAutoConfigurationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/integration/IntegrationAutoConfigurationTests.java @@ -23,7 +23,7 @@ import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.integration.support.channel.HeaderChannelRegistry; -import static org.junit.Assert.assertNotNull; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link IntegrationAutoConfiguration}. @@ -38,7 +38,7 @@ public class IntegrationAutoConfigurationTests { public void integrationIsAvailable() { this.context.register(IntegrationAutoConfiguration.class); this.context.refresh(); - assertNotNull(this.context.getBean(HeaderChannelRegistry.class)); + assertThat(this.context.getBean(HeaderChannelRegistry.class)).isNotNull(); this.context.close(); } @@ -47,7 +47,7 @@ public class IntegrationAutoConfigurationTests { this.context.register(JmxAutoConfiguration.class, IntegrationAutoConfiguration.class); this.context.refresh(); - assertNotNull(this.context.getBean(HeaderChannelRegistry.class)); + assertThat(this.context.getBean(HeaderChannelRegistry.class)).isNotNull(); this.context.close(); } @@ -60,7 +60,7 @@ public class IntegrationAutoConfigurationTests { this.context.setParent(parent); this.context.register(IntegrationAutoConfiguration.class); this.context.refresh(); - assertNotNull(this.context.getBean(HeaderChannelRegistry.class)); + assertThat(this.context.getBean(HeaderChannelRegistry.class)).isNotNull(); ((ConfigurableApplicationContext) this.context.getParent()).close(); this.context.close(); } diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jackson/JacksonAutoConfigurationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jackson/JacksonAutoConfigurationTests.java index cbbc69a45e..0c9a3cb440 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jackson/JacksonAutoConfigurationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jackson/JacksonAutoConfigurationTests.java @@ -57,15 +57,7 @@ import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Primary; import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder; -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.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.Mockito.mock; /** @@ -99,7 +91,7 @@ public class JacksonAutoConfigurationTests { this.context.register(JacksonAutoConfiguration.class); this.context.refresh(); ObjectMapper objectMapper = this.context.getBean(ObjectMapper.class); - assertThat(objectMapper.canSerialize(LocalDateTime.class), is(true)); + assertThat(objectMapper.canSerialize(LocalDateTime.class)).isTrue(); } @Test @@ -108,7 +100,7 @@ public class JacksonAutoConfigurationTests { HttpMessageConvertersAutoConfiguration.class); this.context.refresh(); ObjectMapper mapper = this.context.getBean(ObjectMapper.class); - assertEquals("{\"foo\":\"bar\"}", mapper.writeValueAsString(new Foo())); + assertThat(mapper.writeValueAsString(new Foo())).isEqualTo("{\"foo\":\"bar\"}"); } /* @@ -122,7 +114,7 @@ public class JacksonAutoConfigurationTests { this.context.register(JacksonAutoConfiguration.class); this.context.refresh(); ObjectMapper mapper = this.context.getBean(ObjectMapper.class); - assertThat(mapper.getDateFormat(), is(instanceOf(StdDateFormat.class))); + assertThat(mapper.getDateFormat()).isInstanceOf(StdDateFormat.class); } @Test @@ -133,9 +125,9 @@ public class JacksonAutoConfigurationTests { this.context.refresh(); ObjectMapper mapper = this.context.getBean(ObjectMapper.class); DateFormat dateFormat = mapper.getDateFormat(); - assertThat(dateFormat, is(instanceOf(SimpleDateFormat.class))); - assertThat(((SimpleDateFormat) dateFormat).toPattern(), - is(equalTo("yyyyMMddHHmmss"))); + assertThat(dateFormat).isInstanceOf(SimpleDateFormat.class); + assertThat(((SimpleDateFormat) dateFormat).toPattern()) + .isEqualTo("yyyyMMddHHmmss"); } @Test @@ -147,9 +139,10 @@ public class JacksonAutoConfigurationTests { this.context.refresh(); ObjectMapper mapper = this.context.getBean(ObjectMapper.class); DateTime dateTime = new DateTime(1988, 6, 25, 20, 30, DateTimeZone.UTC); - assertEquals("\"1988-06-25 20:30:00\"", mapper.writeValueAsString(dateTime)); + assertThat(mapper.writeValueAsString(dateTime)) + .isEqualTo("\"1988-06-25 20:30:00\""); Date date = dateTime.toDate(); - assertEquals("\"19880625203000\"", mapper.writeValueAsString(date)); + assertThat(mapper.writeValueAsString(date)).isEqualTo("\"19880625203000\""); } @Test @@ -159,7 +152,7 @@ public class JacksonAutoConfigurationTests { "spring.jackson.date-format:org.springframework.boot.autoconfigure.jackson.JacksonAutoConfigurationTests.MyDateFormat"); this.context.refresh(); ObjectMapper mapper = this.context.getBean(ObjectMapper.class); - assertThat(mapper.getDateFormat(), is(instanceOf(MyDateFormat.class))); + assertThat(mapper.getDateFormat()).isInstanceOf(MyDateFormat.class); } @Test @@ -167,7 +160,7 @@ public class JacksonAutoConfigurationTests { this.context.register(JacksonAutoConfiguration.class); this.context.refresh(); ObjectMapper mapper = this.context.getBean(ObjectMapper.class); - assertThat(mapper.getPropertyNamingStrategy(), is(nullValue())); + assertThat(mapper.getPropertyNamingStrategy()).isNull(); } @Test @@ -177,8 +170,8 @@ public class JacksonAutoConfigurationTests { "spring.jackson.property-naming-strategy:CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES"); this.context.refresh(); ObjectMapper mapper = this.context.getBean(ObjectMapper.class); - assertThat(mapper.getPropertyNamingStrategy(), - is(instanceOf(LowerCaseWithUnderscoresStrategy.class))); + assertThat(mapper.getPropertyNamingStrategy()) + .isInstanceOf(LowerCaseWithUnderscoresStrategy.class); } @Test @@ -188,8 +181,8 @@ public class JacksonAutoConfigurationTests { "spring.jackson.property-naming-strategy:com.fasterxml.jackson.databind.PropertyNamingStrategy.LowerCaseWithUnderscoresStrategy"); this.context.refresh(); ObjectMapper mapper = this.context.getBean(ObjectMapper.class); - assertThat(mapper.getPropertyNamingStrategy(), - is(instanceOf(LowerCaseWithUnderscoresStrategy.class))); + assertThat(mapper.getPropertyNamingStrategy()) + .isInstanceOf(LowerCaseWithUnderscoresStrategy.class); } @Test @@ -199,9 +192,10 @@ public class JacksonAutoConfigurationTests { "spring.jackson.serialization.indent_output:true"); this.context.refresh(); ObjectMapper mapper = this.context.getBean(ObjectMapper.class); - assertFalse(SerializationFeature.INDENT_OUTPUT.enabledByDefault()); - assertTrue(mapper.getSerializationConfig() - .hasSerializationFeatures(SerializationFeature.INDENT_OUTPUT.getMask())); + assertThat(SerializationFeature.INDENT_OUTPUT.enabledByDefault()).isFalse(); + assertThat(mapper.getSerializationConfig() + .hasSerializationFeatures(SerializationFeature.INDENT_OUTPUT.getMask())) + .isTrue(); } @Test @@ -211,9 +205,10 @@ public class JacksonAutoConfigurationTests { "spring.jackson.serialization.write_dates_as_timestamps:false"); this.context.refresh(); ObjectMapper mapper = this.context.getBean(ObjectMapper.class); - assertTrue(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS.enabledByDefault()); - assertFalse(mapper.getSerializationConfig().hasSerializationFeatures( - SerializationFeature.WRITE_DATES_AS_TIMESTAMPS.getMask())); + assertThat(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS.enabledByDefault()) + .isTrue(); + assertThat(mapper.getSerializationConfig().hasSerializationFeatures( + SerializationFeature.WRITE_DATES_AS_TIMESTAMPS.getMask())).isFalse(); } @Test @@ -223,9 +218,10 @@ public class JacksonAutoConfigurationTests { "spring.jackson.deserialization.use_big_decimal_for_floats:true"); this.context.refresh(); ObjectMapper mapper = this.context.getBean(ObjectMapper.class); - assertFalse(DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS.enabledByDefault()); - assertTrue(mapper.getDeserializationConfig().hasDeserializationFeatures( - DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS.getMask())); + assertThat(DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS.enabledByDefault()) + .isFalse(); + assertThat(mapper.getDeserializationConfig().hasDeserializationFeatures( + DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS.getMask())).isTrue(); } @Test @@ -235,9 +231,10 @@ public class JacksonAutoConfigurationTests { "spring.jackson.deserialization.fail-on-unknown-properties:false"); this.context.refresh(); ObjectMapper mapper = this.context.getBean(ObjectMapper.class); - assertTrue(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES.enabledByDefault()); - assertFalse(mapper.getDeserializationConfig().hasDeserializationFeatures( - DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES.getMask())); + assertThat(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES.enabledByDefault()) + .isTrue(); + assertThat(mapper.getDeserializationConfig().hasDeserializationFeatures( + DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES.getMask())).isFalse(); } @Test @@ -247,11 +244,14 @@ public class JacksonAutoConfigurationTests { "spring.jackson.mapper.require_setters_for_getters:true"); this.context.refresh(); ObjectMapper mapper = this.context.getBean(ObjectMapper.class); - assertFalse(MapperFeature.REQUIRE_SETTERS_FOR_GETTERS.enabledByDefault()); - assertTrue(mapper.getSerializationConfig() - .hasMapperFeatures(MapperFeature.REQUIRE_SETTERS_FOR_GETTERS.getMask())); - assertTrue(mapper.getDeserializationConfig() - .hasMapperFeatures(MapperFeature.REQUIRE_SETTERS_FOR_GETTERS.getMask())); + assertThat(MapperFeature.REQUIRE_SETTERS_FOR_GETTERS.enabledByDefault()) + .isFalse(); + assertThat(mapper.getSerializationConfig() + .hasMapperFeatures(MapperFeature.REQUIRE_SETTERS_FOR_GETTERS.getMask())) + .isTrue(); + assertThat(mapper.getDeserializationConfig() + .hasMapperFeatures(MapperFeature.REQUIRE_SETTERS_FOR_GETTERS.getMask())) + .isTrue(); } @Test @@ -261,11 +261,11 @@ public class JacksonAutoConfigurationTests { "spring.jackson.mapper.use_annotations:false"); this.context.refresh(); ObjectMapper mapper = this.context.getBean(ObjectMapper.class); - assertTrue(MapperFeature.USE_ANNOTATIONS.enabledByDefault()); - assertFalse(mapper.getDeserializationConfig() - .hasMapperFeatures(MapperFeature.USE_ANNOTATIONS.getMask())); - assertFalse(mapper.getSerializationConfig() - .hasMapperFeatures(MapperFeature.USE_ANNOTATIONS.getMask())); + assertThat(MapperFeature.USE_ANNOTATIONS.enabledByDefault()).isTrue(); + assertThat(mapper.getDeserializationConfig() + .hasMapperFeatures(MapperFeature.USE_ANNOTATIONS.getMask())).isFalse(); + assertThat(mapper.getSerializationConfig() + .hasMapperFeatures(MapperFeature.USE_ANNOTATIONS.getMask())).isFalse(); } @Test @@ -275,8 +275,9 @@ public class JacksonAutoConfigurationTests { "spring.jackson.parser.allow_single_quotes:true"); this.context.refresh(); ObjectMapper mapper = this.context.getBean(ObjectMapper.class); - assertFalse(JsonParser.Feature.ALLOW_SINGLE_QUOTES.enabledByDefault()); - assertTrue(mapper.getFactory().isEnabled(JsonParser.Feature.ALLOW_SINGLE_QUOTES)); + assertThat(JsonParser.Feature.ALLOW_SINGLE_QUOTES.enabledByDefault()).isFalse(); + assertThat(mapper.getFactory().isEnabled(JsonParser.Feature.ALLOW_SINGLE_QUOTES)) + .isTrue(); } @Test @@ -286,8 +287,9 @@ public class JacksonAutoConfigurationTests { "spring.jackson.parser.auto_close_source:false"); this.context.refresh(); ObjectMapper mapper = this.context.getBean(ObjectMapper.class); - assertTrue(JsonParser.Feature.AUTO_CLOSE_SOURCE.enabledByDefault()); - assertFalse(mapper.getFactory().isEnabled(JsonParser.Feature.AUTO_CLOSE_SOURCE)); + assertThat(JsonParser.Feature.AUTO_CLOSE_SOURCE.enabledByDefault()).isTrue(); + assertThat(mapper.getFactory().isEnabled(JsonParser.Feature.AUTO_CLOSE_SOURCE)) + .isFalse(); } @Test @@ -297,9 +299,10 @@ public class JacksonAutoConfigurationTests { "spring.jackson.generator.write_numbers_as_strings:true"); this.context.refresh(); ObjectMapper mapper = this.context.getBean(ObjectMapper.class); - assertFalse(JsonGenerator.Feature.WRITE_NUMBERS_AS_STRINGS.enabledByDefault()); - assertTrue(mapper.getFactory() - .isEnabled(JsonGenerator.Feature.WRITE_NUMBERS_AS_STRINGS)); + assertThat(JsonGenerator.Feature.WRITE_NUMBERS_AS_STRINGS.enabledByDefault()) + .isFalse(); + assertThat(mapper.getFactory() + .isEnabled(JsonGenerator.Feature.WRITE_NUMBERS_AS_STRINGS)).isTrue(); } @Test @@ -309,9 +312,9 @@ public class JacksonAutoConfigurationTests { "spring.jackson.generator.auto_close_target:false"); this.context.refresh(); ObjectMapper mapper = this.context.getBean(ObjectMapper.class); - assertTrue(JsonGenerator.Feature.AUTO_CLOSE_TARGET.enabledByDefault()); - assertFalse( - mapper.getFactory().isEnabled(JsonGenerator.Feature.AUTO_CLOSE_TARGET)); + assertThat(JsonGenerator.Feature.AUTO_CLOSE_TARGET.enabledByDefault()).isTrue(); + assertThat(mapper.getFactory().isEnabled(JsonGenerator.Feature.AUTO_CLOSE_TARGET)) + .isFalse(); } @Test @@ -321,17 +324,18 @@ public class JacksonAutoConfigurationTests { Jackson2ObjectMapperBuilder builder = this.context .getBean(Jackson2ObjectMapperBuilder.class); ObjectMapper mapper = builder.build(); - assertTrue(MapperFeature.DEFAULT_VIEW_INCLUSION.enabledByDefault()); - assertFalse(mapper.getDeserializationConfig() - .isEnabled(MapperFeature.DEFAULT_VIEW_INCLUSION)); - assertTrue(MapperFeature.DEFAULT_VIEW_INCLUSION.enabledByDefault()); - assertFalse(mapper.getDeserializationConfig() - .isEnabled(MapperFeature.DEFAULT_VIEW_INCLUSION)); - assertFalse(mapper.getSerializationConfig() - .isEnabled(MapperFeature.DEFAULT_VIEW_INCLUSION)); - assertTrue(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES.enabledByDefault()); - assertFalse(mapper.getDeserializationConfig() - .isEnabled(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)); + assertThat(MapperFeature.DEFAULT_VIEW_INCLUSION.enabledByDefault()).isTrue(); + assertThat(mapper.getDeserializationConfig() + .isEnabled(MapperFeature.DEFAULT_VIEW_INCLUSION)).isFalse(); + assertThat(MapperFeature.DEFAULT_VIEW_INCLUSION.enabledByDefault()).isTrue(); + assertThat(mapper.getDeserializationConfig() + .isEnabled(MapperFeature.DEFAULT_VIEW_INCLUSION)).isFalse(); + assertThat(mapper.getSerializationConfig() + .isEnabled(MapperFeature.DEFAULT_VIEW_INCLUSION)).isFalse(); + assertThat(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES.enabledByDefault()) + .isTrue(); + assertThat(mapper.getDeserializationConfig() + .isEnabled(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)).isFalse(); } @Test @@ -340,9 +344,9 @@ public class JacksonAutoConfigurationTests { this.context.refresh(); ObjectMapper objectMapper = this.context .getBean(Jackson2ObjectMapperBuilder.class).build(); - assertThat(this.context.getBean(CustomModule.class).getOwners(), - hasItem((ObjectCodec) objectMapper)); - assertThat(objectMapper.canSerialize(LocalDateTime.class), is(true)); + assertThat(this.context.getBean(CustomModule.class).getOwners()) + .contains((ObjectCodec) objectMapper); + assertThat(objectMapper.canSerialize(LocalDateTime.class)).isTrue(); } @Test @@ -351,8 +355,8 @@ public class JacksonAutoConfigurationTests { this.context.refresh(); ObjectMapper objectMapper = this.context .getBean(Jackson2ObjectMapperBuilder.class).build(); - assertThat(objectMapper.getSerializationConfig().getSerializationInclusion(), - is(JsonInclude.Include.ALWAYS)); + assertThat(objectMapper.getSerializationConfig().getSerializationInclusion()) + .isEqualTo(JsonInclude.Include.ALWAYS); } @Test @@ -363,8 +367,8 @@ public class JacksonAutoConfigurationTests { this.context.refresh(); ObjectMapper objectMapper = this.context .getBean(Jackson2ObjectMapperBuilder.class).build(); - assertThat(objectMapper.getSerializationConfig().getSerializationInclusion(), - is(JsonInclude.Include.NON_NULL)); + assertThat(objectMapper.getSerializationConfig().getSerializationInclusion()) + .isEqualTo(JsonInclude.Include.NON_NULL); } @Test @@ -379,8 +383,8 @@ public class JacksonAutoConfigurationTests { ObjectMapper objectMapper = this.context .getBean(Jackson2ObjectMapperBuilder.class).build(); DateTime dateTime = new DateTime(1436966242231L, DateTimeZone.UTC); - assertEquals("\"Pacific Daylight Time\"", - objectMapper.writeValueAsString(dateTime)); + assertThat(objectMapper.writeValueAsString(dateTime)) + .isEqualTo("\"Pacific Daylight Time\""); } @Test @@ -393,7 +397,7 @@ public class JacksonAutoConfigurationTests { ObjectMapper objectMapper = this.context .getBean(Jackson2ObjectMapperBuilder.class).build(); Date date = new Date(1436966242231L); - assertEquals("\"GMT+10:00\"", objectMapper.writeValueAsString(date)); + assertThat(objectMapper.writeValueAsString(date)).isEqualTo("\"GMT+10:00\""); } @Test @@ -407,8 +411,8 @@ public class JacksonAutoConfigurationTests { .getBean(Jackson2ObjectMapperBuilder.class).build(); DateTime dateTime = new DateTime(1436966242231L, DateTimeZone.UTC); - assertEquals("\"Koordinierte Universalzeit\"", - objectMapper.writeValueAsString(dateTime)); + assertThat(objectMapper.writeValueAsString(dateTime)) + .isEqualTo("\"Koordinierte Universalzeit\""); } @Test @@ -430,7 +434,7 @@ public class JacksonAutoConfigurationTests { Annotated annotated = mock(Annotated.class); Mode mode = this.context.getBean(ObjectMapper.class).getDeserializationConfig() .getAnnotationIntrospector().findCreatorBinding(annotated); - assertThat(mode, is(equalTo(expectedMode))); + assertThat(mode).isEqualTo(expectedMode); } public static class MyDateFormat extends SimpleDateFormat { diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/CommonsDbcpDataSourceConfigurationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/CommonsDbcpDataSourceConfigurationTests.java index 42b6631659..cf795cc1f7 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/CommonsDbcpDataSourceConfigurationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/CommonsDbcpDataSourceConfigurationTests.java @@ -29,9 +29,7 @@ import org.springframework.context.annotation.AnnotationConfigApplicationContext import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; -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; /** * Tests for {@link CommonsDbcpDataSourceConfiguration}. @@ -49,7 +47,7 @@ public class CommonsDbcpDataSourceConfigurationTests { public void testDataSourceExists() throws Exception { this.context.register(CommonsDbcpDataSourceConfiguration.class); this.context.refresh(); - assertNotNull(this.context.getBean(DataSource.class)); + assertThat(this.context.getBean(DataSource.class)).isNotNull(); this.context.close(); } @@ -68,13 +66,13 @@ public class CommonsDbcpDataSourceConfigurationTests { EnvironmentTestUtils.addEnvironment(this.context, PREFIX + "maxWait:1234"); this.context.refresh(); BasicDataSource ds = this.context.getBean(BasicDataSource.class); - assertEquals("jdbc:foo//bar/spam", ds.getUrl()); - assertTrue(ds.getTestWhileIdle()); - assertTrue(ds.getTestOnBorrow()); - assertTrue(ds.getTestOnReturn()); - assertEquals(10000, ds.getTimeBetweenEvictionRunsMillis()); - assertEquals(12345, ds.getMinEvictableIdleTimeMillis()); - assertEquals(1234, ds.getMaxWait()); + assertThat(ds.getUrl()).isEqualTo("jdbc:foo//bar/spam"); + assertThat(ds.getTestWhileIdle()).isTrue(); + assertThat(ds.getTestOnBorrow()).isTrue(); + assertThat(ds.getTestOnReturn()).isTrue(); + assertThat(ds.getTimeBetweenEvictionRunsMillis()).isEqualTo(10000); + assertThat(ds.getMinEvictableIdleTimeMillis()).isEqualTo(12345); + assertThat(ds.getMaxWait()).isEqualTo(1234); } @Test @@ -82,11 +80,11 @@ public class CommonsDbcpDataSourceConfigurationTests { this.context.register(CommonsDbcpDataSourceConfiguration.class); this.context.refresh(); BasicDataSource ds = this.context.getBean(BasicDataSource.class); - assertEquals(GenericObjectPool.DEFAULT_TIME_BETWEEN_EVICTION_RUNS_MILLIS, - ds.getTimeBetweenEvictionRunsMillis()); - assertEquals(GenericObjectPool.DEFAULT_MIN_EVICTABLE_IDLE_TIME_MILLIS, - ds.getMinEvictableIdleTimeMillis()); - assertEquals(GenericObjectPool.DEFAULT_MAX_WAIT, ds.getMaxWait()); + assertThat(ds.getTimeBetweenEvictionRunsMillis()) + .isEqualTo(GenericObjectPool.DEFAULT_TIME_BETWEEN_EVICTION_RUNS_MILLIS); + assertThat(ds.getMinEvictableIdleTimeMillis()) + .isEqualTo(GenericObjectPool.DEFAULT_MIN_EVICTABLE_IDLE_TIME_MILLIS); + assertThat(ds.getMaxWait()).isEqualTo(GenericObjectPool.DEFAULT_MAX_WAIT); } @Configuration diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/DataSourceAutoConfigurationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/DataSourceAutoConfigurationTests.java index dd263aebba..89ae3b75a9 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/DataSourceAutoConfigurationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/DataSourceAutoConfigurationTests.java @@ -44,12 +44,7 @@ import org.springframework.context.annotation.Configuration; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.namedparam.NamedParameterJdbcOperations; -import static org.hamcrest.Matchers.instanceOf; -import static org.junit.Assert.assertEquals; -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.mockito.Mockito.mock; /** @@ -81,7 +76,7 @@ public class DataSourceAutoConfigurationTests { this.context.register(DataSourceAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); this.context.refresh(); - assertNotNull(this.context.getBean(DataSource.class)); + assertThat(this.context.getBean(DataSource.class)).isNotNull(); } @Test @@ -91,8 +86,8 @@ public class DataSourceAutoConfigurationTests { this.context.refresh(); org.apache.tomcat.jdbc.pool.DataSource dataSource = this.context .getBean(org.apache.tomcat.jdbc.pool.DataSource.class); - assertNotNull(dataSource.getUrl()); - assertNotNull(dataSource.getDriverClassName()); + assertThat(dataSource.getUrl()).isNotNull(); + assertThat(dataSource.getDriverClassName()).isNotNull(); } @Test(expected = BeanCreationException.class) @@ -103,7 +98,7 @@ public class DataSourceAutoConfigurationTests { this.context.register(DataSourceAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); this.context.refresh(); - assertNotNull(this.context.getBean(DataSource.class)); + assertThat(this.context.getBean(DataSource.class)).isNotNull(); } @Test(expected = BeanCreationException.class) @@ -115,21 +110,21 @@ public class DataSourceAutoConfigurationTests { this.context.register(DataSourceAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); this.context.refresh(); - assertNotNull(this.context.getBean(DataSource.class)); + assertThat(this.context.getBean(DataSource.class)).isNotNull(); } @Test public void testHikariIsFallback() throws Exception { HikariDataSource pool = testDataSourceFallback(HikariDataSource.class, "org.apache.tomcat"); - assertEquals("jdbc:hsqldb:mem:testdb", pool.getJdbcUrl()); + assertThat(pool.getJdbcUrl()).isEqualTo("jdbc:hsqldb:mem:testdb"); } @Test public void commonsDbcpIsFallback() throws Exception { BasicDataSource dataSource = testDataSourceFallback(BasicDataSource.class, "org.apache.tomcat", "com.zaxxer.hikari"); - assertEquals("jdbc:hsqldb:mem:testdb", dataSource.getUrl()); + assertThat(dataSource.getUrl()).isEqualTo("jdbc:hsqldb:mem:testdb"); } @Test @@ -137,7 +132,7 @@ public class DataSourceAutoConfigurationTests { org.apache.commons.dbcp2.BasicDataSource dataSource = testDataSourceFallback( org.apache.commons.dbcp2.BasicDataSource.class, "org.apache.tomcat", "com.zaxxer.hikari", "org.apache.commons.dbcp."); - assertEquals("jdbc:hsqldb:mem:testdb", dataSource.getUrl()); + assertThat(dataSource.getUrl()).isEqualTo("jdbc:hsqldb:mem:testdb"); } @Test @@ -149,10 +144,10 @@ public class DataSourceAutoConfigurationTests { PropertyPlaceholderAutoConfiguration.class); this.context.refresh(); DataSource bean = this.context.getBean(DataSource.class); - assertNotNull(bean); + assertThat(bean).isNotNull(); org.apache.tomcat.jdbc.pool.DataSource pool = (org.apache.tomcat.jdbc.pool.DataSource) bean; - assertEquals("org.hsqldb.jdbcDriver", pool.getDriverClassName()); - assertEquals("sa", pool.getUsername()); + assertThat(pool.getDriverClassName()).isEqualTo("org.hsqldb.jdbcDriver"); + assertThat(pool.getUsername()).isEqualTo("sa"); } @Test @@ -165,25 +160,26 @@ public class DataSourceAutoConfigurationTests { PropertyPlaceholderAutoConfiguration.class); this.context.refresh(); DataSource bean = this.context.getBean(DataSource.class); - assertNotNull(bean); - assertEquals(HikariDataSource.class, bean.getClass()); + assertThat(bean).isNotNull(); + assertThat(bean.getClass()).isEqualTo(HikariDataSource.class); } @Test public void testExplicitDriverClassClearsUserName() throws Exception { EnvironmentTestUtils.addEnvironment(this.context, - "spring.datasource.driverClassName:org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfigurationTests$DatabaseDriver", + "spring.datasource.driverClassName:" + + "org.springframework.boot.autoconfigure.jdbc." + + "DataSourceAutoConfigurationTests$DatabaseDriver", "spring.datasource.url:jdbc:foo://localhost"); this.context.register(DataSourceAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); this.context.refresh(); DataSource bean = this.context.getBean(DataSource.class); - assertNotNull(bean); + assertThat(bean).isNotNull(); org.apache.tomcat.jdbc.pool.DataSource pool = (org.apache.tomcat.jdbc.pool.DataSource) bean; - assertEquals( - "org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfigurationTests$DatabaseDriver", - pool.getDriverClassName()); - assertNull(pool.getUsername()); + assertThat(pool.getDriverClassName()).isEqualTo( + "org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfigurationTests$DatabaseDriver"); + assertThat(pool.getUsername()).isNull(); } @Test @@ -193,8 +189,7 @@ public class DataSourceAutoConfigurationTests { PropertyPlaceholderAutoConfiguration.class); this.context.refresh(); DataSource dataSource = this.context.getBean(DataSource.class); - assertTrue("DataSource is wrong type: " + dataSource, - dataSource instanceof BasicDataSource); + assertThat(dataSource).isInstanceOf(BasicDataSource.class); } @Test @@ -203,8 +198,8 @@ public class DataSourceAutoConfigurationTests { PropertyPlaceholderAutoConfiguration.class); this.context.refresh(); JdbcTemplate jdbcTemplate = this.context.getBean(JdbcTemplate.class); - assertNotNull(jdbcTemplate); - assertNotNull(jdbcTemplate.getDataSource()); + assertThat(jdbcTemplate).isNotNull(); + assertThat(jdbcTemplate.getDataSource()).isNotNull(); } @Test @@ -214,8 +209,8 @@ public class DataSourceAutoConfigurationTests { PropertyPlaceholderAutoConfiguration.class); this.context.refresh(); JdbcTemplate jdbcTemplate = this.context.getBean(JdbcTemplate.class); - assertNotNull(jdbcTemplate); - assertTrue(jdbcTemplate.getDataSource() instanceof BasicDataSource); + assertThat(jdbcTemplate).isNotNull(); + assertThat(jdbcTemplate.getDataSource() instanceof BasicDataSource).isTrue(); } @Test @@ -223,7 +218,7 @@ public class DataSourceAutoConfigurationTests { this.context.register(DataSourceAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); this.context.refresh(); - assertNotNull(this.context.getBean(NamedParameterJdbcOperations.class)); + assertThat(this.context.getBean(NamedParameterJdbcOperations.class)).isNotNull(); } @SuppressWarnings("unchecked") @@ -234,6 +229,7 @@ public class DataSourceAutoConfigurationTests { "spring.datasource.url:jdbc:hsqldb:mem:testdb"); this.context.setClassLoader( new URLClassLoader(new URL[0], getClass().getClassLoader()) { + @Override protected Class loadClass(String name, boolean resolve) throws ClassNotFoundException { @@ -244,13 +240,13 @@ public class DataSourceAutoConfigurationTests { } return super.loadClass(name, resolve); } + }); this.context.register(DataSourceAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); this.context.refresh(); DataSource bean = this.context.getBean(DataSource.class); - - assertThat(bean, instanceOf(expectedType)); + assertThat(bean).isInstanceOf(expectedType); return (T) bean; } diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/DataSourceInitializerTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/DataSourceInitializerTests.java index cbf7ac033d..18ee4f00c6 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/DataSourceInitializerTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/DataSourceInitializerTests.java @@ -38,9 +38,7 @@ import org.springframework.jdbc.core.JdbcOperations; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.util.ClassUtils; -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; import static org.junit.Assert.fail; /** @@ -73,7 +71,8 @@ public class DataSourceInitializerTests { this.context.register(DataSourceInitializer.class, PropertyPlaceholderAutoConfiguration.class, DataSourceProperties.class); this.context.refresh(); - assertEquals(0, this.context.getBeanNamesForType(DataSource.class).length); + assertThat(this.context.getBeanNamesForType(DataSource.class).length) + .isEqualTo(0); } @Test @@ -86,7 +85,8 @@ public class DataSourceInitializerTests { this.context.register(TwoDataSources.class, DataSourceInitializer.class, PropertyPlaceholderAutoConfiguration.class, DataSourceProperties.class); this.context.refresh(); - assertEquals(2, this.context.getBeanNamesForType(DataSource.class).length); + assertThat(this.context.getBeanNamesForType(DataSource.class).length) + .isEqualTo(2); } @Test @@ -97,11 +97,11 @@ public class DataSourceInitializerTests { PropertyPlaceholderAutoConfiguration.class); this.context.refresh(); DataSource dataSource = this.context.getBean(DataSource.class); - assertTrue(dataSource instanceof org.apache.tomcat.jdbc.pool.DataSource); - assertNotNull(dataSource); + assertThat(dataSource instanceof org.apache.tomcat.jdbc.pool.DataSource).isTrue(); + assertThat(dataSource).isNotNull(); JdbcOperations template = new JdbcTemplate(dataSource); - assertEquals(Integer.valueOf(1), - template.queryForObject("SELECT COUNT(*) from BAR", Integer.class)); + assertThat(template.queryForObject("SELECT COUNT(*) from BAR", Integer.class)) + .isEqualTo(1); } @Test @@ -116,11 +116,11 @@ public class DataSourceInitializerTests { .addResourcePathToPackagePath(getClass(), "data.sql")); this.context.refresh(); DataSource dataSource = this.context.getBean(DataSource.class); - assertTrue(dataSource instanceof org.apache.tomcat.jdbc.pool.DataSource); - assertNotNull(dataSource); + assertThat(dataSource instanceof org.apache.tomcat.jdbc.pool.DataSource).isTrue(); + assertThat(dataSource).isNotNull(); JdbcOperations template = new JdbcTemplate(dataSource); - assertEquals(Integer.valueOf(1), - template.queryForObject("SELECT COUNT(*) from FOO", Integer.class)); + assertThat(template.queryForObject("SELECT COUNT(*) from FOO", Integer.class)) + .isEqualTo(1); } @Test @@ -139,13 +139,13 @@ public class DataSourceInitializerTests { PropertyPlaceholderAutoConfiguration.class); this.context.refresh(); DataSource dataSource = this.context.getBean(DataSource.class); - assertTrue(dataSource instanceof org.apache.tomcat.jdbc.pool.DataSource); - assertNotNull(dataSource); + assertThat(dataSource instanceof org.apache.tomcat.jdbc.pool.DataSource).isTrue(); + assertThat(dataSource).isNotNull(); JdbcOperations template = new JdbcTemplate(dataSource); - assertEquals(Integer.valueOf(1), - template.queryForObject("SELECT COUNT(*) from FOO", Integer.class)); - assertEquals(Integer.valueOf(0), - template.queryForObject("SELECT COUNT(*) from SPAM", Integer.class)); + assertThat(template.queryForObject("SELECT COUNT(*) from FOO", Integer.class)) + .isEqualTo(1); + assertThat(template.queryForObject("SELECT COUNT(*) from SPAM", Integer.class)) + .isEqualTo(0); } @Test @@ -162,15 +162,17 @@ public class DataSourceInitializerTests { .addResourcePathToPackagePath(getClass(), "encoding-data.sql")); this.context.refresh(); DataSource dataSource = this.context.getBean(DataSource.class); - assertTrue(dataSource instanceof org.apache.tomcat.jdbc.pool.DataSource); - assertNotNull(dataSource); + assertThat(dataSource instanceof org.apache.tomcat.jdbc.pool.DataSource).isTrue(); + assertThat(dataSource).isNotNull(); JdbcOperations template = new JdbcTemplate(dataSource); - assertEquals(Integer.valueOf(2), - template.queryForObject("SELECT COUNT(*) from BAR", Integer.class)); - assertEquals("bar", - template.queryForObject("SELECT name from BAR WHERE id=1", String.class)); - assertEquals("ばー", - template.queryForObject("SELECT name from BAR WHERE id=2", String.class)); + assertThat(template.queryForObject("SELECT COUNT(*) from BAR", Integer.class)) + .isEqualTo(2); + assertThat( + template.queryForObject("SELECT name from BAR WHERE id=1", String.class)) + .isEqualTo("bar"); + assertThat( + template.queryForObject("SELECT name from BAR WHERE id=2", String.class)) + .isEqualTo("ばー"); } @Test @@ -183,8 +185,8 @@ public class DataSourceInitializerTests { this.context.publishEvent(new DataSourceInitializedEvent(dataSource)); - assertTrue(dataSource instanceof org.apache.tomcat.jdbc.pool.DataSource); - assertNotNull(dataSource); + assertThat(dataSource instanceof org.apache.tomcat.jdbc.pool.DataSource).isTrue(); + assertThat(dataSource).isNotNull(); JdbcOperations template = new JdbcTemplate(dataSource); try { @@ -194,7 +196,7 @@ public class DataSourceInitializerTests { catch (BadSqlGrammarException ex) { SQLException sqlException = ex.getSQLException(); int expectedCode = -5501; // user lacks privilege or object not found - assertEquals(expectedCode, sqlException.getErrorCode()); + assertThat(sqlException.getErrorCode()).isEqualTo(expectedCode); } } diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/DataSourceJsonSerializationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/DataSourceJsonSerializationTests.java index 341de73e09..03cbec7180 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/DataSourceJsonSerializationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/DataSourceJsonSerializationTests.java @@ -44,8 +44,7 @@ import org.springframework.core.convert.support.DefaultConversionService; import org.springframework.util.ReflectionUtils; import org.springframework.util.StringUtils; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * Test that a {@link DataSource} can be exposed as JSON for actuator endpoints. @@ -62,7 +61,7 @@ public class DataSourceJsonSerializationTests { ObjectMapper mapper = new ObjectMapper(); mapper.setSerializerFactory(factory); String value = mapper.writeValueAsString(dataSource); - assertTrue(value.contains("\"url\":")); + assertThat(value.contains("\"url\":")).isTrue(); } @Test @@ -71,8 +70,8 @@ public class DataSourceJsonSerializationTests { ObjectMapper mapper = new ObjectMapper(); mapper.addMixIn(DataSource.class, DataSourceJson.class); String value = mapper.writeValueAsString(dataSource); - assertTrue(value.contains("\"url\":")); - assertEquals(1, StringUtils.countOccurrencesOf(value, "\"url\"")); + assertThat(value.contains("\"url\":")).isTrue(); + assertThat(StringUtils.countOccurrencesOf(value, "\"url\"")).isEqualTo(1); } @JsonSerialize(using = TomcatDataSourceSerializer.class) diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/DataSourcePropertiesTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/DataSourcePropertiesTests.java index 62a9c65f45..32f339a45a 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/DataSourcePropertiesTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/DataSourcePropertiesTests.java @@ -18,8 +18,7 @@ package org.springframework.boot.autoconfigure.jdbc; import org.junit.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link DataSourceProperties}. @@ -33,8 +32,9 @@ public class DataSourcePropertiesTests { public void determineDriver() { DataSourceProperties properties = new DataSourceProperties(); properties.setUrl("jdbc:mysql://mydb"); - assertNull(properties.getDriverClassName()); - assertEquals("com.mysql.jdbc.Driver", properties.determineDriverClassName()); + assertThat(properties.getDriverClassName()).isNull(); + assertThat(properties.determineDriverClassName()) + .isEqualTo("com.mysql.jdbc.Driver"); } @Test @@ -42,16 +42,18 @@ public class DataSourcePropertiesTests { DataSourceProperties properties = new DataSourceProperties(); properties.setUrl("jdbc:mysql://mydb"); properties.setDriverClassName("org.hsqldb.jdbcDriver"); - assertEquals("org.hsqldb.jdbcDriver", properties.getDriverClassName()); - assertEquals("org.hsqldb.jdbcDriver", properties.determineDriverClassName()); + assertThat(properties.getDriverClassName()).isEqualTo("org.hsqldb.jdbcDriver"); + assertThat(properties.determineDriverClassName()) + .isEqualTo("org.hsqldb.jdbcDriver"); } @Test public void determineUrl() throws Exception { DataSourceProperties properties = new DataSourceProperties(); properties.afterPropertiesSet(); - assertNull(properties.getUrl()); - assertEquals(EmbeddedDatabaseConnection.H2.getUrl(), properties.determineUrl()); + assertThat(properties.getUrl()).isNull(); + assertThat(properties.determineUrl()) + .isEqualTo(EmbeddedDatabaseConnection.H2.getUrl()); } @Test @@ -59,16 +61,16 @@ public class DataSourcePropertiesTests { DataSourceProperties properties = new DataSourceProperties(); properties.setUrl("jdbc:mysql://mydb"); properties.afterPropertiesSet(); - assertEquals("jdbc:mysql://mydb", properties.getUrl()); - assertEquals("jdbc:mysql://mydb", properties.determineUrl()); + assertThat(properties.getUrl()).isEqualTo("jdbc:mysql://mydb"); + assertThat(properties.determineUrl()).isEqualTo("jdbc:mysql://mydb"); } @Test public void determineUsername() throws Exception { DataSourceProperties properties = new DataSourceProperties(); properties.afterPropertiesSet(); - assertNull(properties.getUsername()); - assertEquals("sa", properties.determineUsername()); + assertThat(properties.getUsername()).isNull(); + assertThat(properties.determineUsername()).isEqualTo("sa"); } @Test @@ -76,16 +78,16 @@ public class DataSourcePropertiesTests { DataSourceProperties properties = new DataSourceProperties(); properties.setUsername("foo"); properties.afterPropertiesSet(); - assertEquals("foo", properties.getUsername()); - assertEquals("foo", properties.determineUsername()); + assertThat(properties.getUsername()).isEqualTo("foo"); + assertThat(properties.determineUsername()).isEqualTo("foo"); } @Test public void determinePassword() throws Exception { DataSourceProperties properties = new DataSourceProperties(); properties.afterPropertiesSet(); - assertNull(properties.getPassword()); - assertEquals("", properties.determinePassword()); + assertThat(properties.getPassword()).isNull(); + assertThat(properties.determinePassword()).isEqualTo(""); } @Test @@ -93,8 +95,8 @@ public class DataSourcePropertiesTests { DataSourceProperties properties = new DataSourceProperties(); properties.setPassword("bar"); properties.afterPropertiesSet(); - assertEquals("bar", properties.getPassword()); - assertEquals("bar", properties.determinePassword()); + assertThat(properties.getPassword()).isEqualTo("bar"); + assertThat(properties.determinePassword()).isEqualTo("bar"); } } diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/DataSourceTransactionManagerAutoConfigurationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/DataSourceTransactionManagerAutoConfigurationTests.java index 837f3d0b5f..4f584b71ea 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/DataSourceTransactionManagerAutoConfigurationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/DataSourceTransactionManagerAutoConfigurationTests.java @@ -28,8 +28,7 @@ import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.annotation.AbstractTransactionManagementConfiguration; import org.springframework.transaction.annotation.EnableTransactionManagement; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; /** @@ -47,19 +46,19 @@ public class DataSourceTransactionManagerAutoConfigurationTests { this.context.register(EmbeddedDataSourceConfiguration.class, DataSourceTransactionManagerAutoConfiguration.class); this.context.refresh(); - assertNotNull(this.context.getBean(DataSource.class)); - assertNotNull(this.context.getBean(DataSourceTransactionManager.class)); - assertNotNull( - this.context.getBean(AbstractTransactionManagementConfiguration.class)); + assertThat(this.context.getBean(DataSource.class)).isNotNull(); + assertThat(this.context.getBean(DataSourceTransactionManager.class)).isNotNull(); + assertThat(this.context.getBean(AbstractTransactionManagementConfiguration.class)) + .isNotNull(); } @Test public void testNoDataSourceExists() throws Exception { this.context.register(DataSourceTransactionManagerAutoConfiguration.class); this.context.refresh(); - assertEquals(0, this.context.getBeanNamesForType(DataSource.class).length); - assertEquals(0, this.context - .getBeanNamesForType(DataSourceTransactionManager.class).length); + assertThat(this.context.getBeanNamesForType(DataSource.class)).isEmpty(); + assertThat(this.context.getBeanNamesForType(DataSourceTransactionManager.class)) + .isEmpty(); } @Test @@ -68,8 +67,8 @@ public class DataSourceTransactionManagerAutoConfigurationTests { EmbeddedDataSourceConfiguration.class, DataSourceTransactionManagerAutoConfiguration.class); this.context.refresh(); - assertNotNull(this.context.getBean(DataSource.class)); - assertNotNull(this.context.getBean(DataSourceTransactionManager.class)); + assertThat(this.context.getBean(DataSource.class)).isNotNull(); + assertThat(this.context.getBean(DataSourceTransactionManager.class)).isNotNull(); } @Test @@ -79,11 +78,10 @@ public class DataSourceTransactionManagerAutoConfigurationTests { EmbeddedDataSourceConfiguration.class, DataSourceTransactionManagerAutoConfiguration.class); this.context.refresh(); - assertEquals("No transaction manager should be been created", 1, - this.context.getBeansOfType(PlatformTransactionManager.class).size()); - assertEquals("Wrong transaction manager", - this.context.getBean("myTransactionManager"), - this.context.getBean(PlatformTransactionManager.class)); + assertThat(this.context.getBeansOfType(PlatformTransactionManager.class)) + .hasSize(1); + assertThat(this.context.getBean(PlatformTransactionManager.class)) + .isEqualTo(this.context.getBean("myTransactionManager")); } @EnableTransactionManagement diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/DatabaseDriverTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/DatabaseDriverTests.java index 748167b843..9f7ac2d2ec 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/DatabaseDriverTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/DatabaseDriverTests.java @@ -20,10 +20,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.assertEquals; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link DatabaseDriver}. @@ -40,19 +37,19 @@ public class DatabaseDriverTests { public void classNameForKnownDatabase() { String driverClassName = DatabaseDriver .fromJdbcUrl("jdbc:postgresql://hostname/dbname").getDriverClassName(); - assertEquals("org.postgresql.Driver", driverClassName); + assertThat(driverClassName).isEqualTo("org.postgresql.Driver"); } @Test public void nullClassNameForUnknownDatabase() { String driverClassName = DatabaseDriver .fromJdbcUrl("jdbc:unknowndb://hostname/dbname").getDriverClassName(); - assertNull(driverClassName); + assertThat(driverClassName).isNull(); } @Test public void unknownOnNullJdbcUrl() { - assertThat(DatabaseDriver.fromJdbcUrl(null), equalTo(DatabaseDriver.UNKNOWN)); + assertThat(DatabaseDriver.fromJdbcUrl(null)).isEqualTo(DatabaseDriver.UNKNOWN); } @Test diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/EmbeddedDataSourceConfigurationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/EmbeddedDataSourceConfigurationTests.java index 6cdf829162..636f353a09 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/EmbeddedDataSourceConfigurationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/EmbeddedDataSourceConfigurationTests.java @@ -22,7 +22,7 @@ import org.junit.Test; import org.springframework.context.annotation.AnnotationConfigApplicationContext; -import static org.junit.Assert.assertNotNull; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link EmbeddedDataSourceConfiguration}. @@ -38,7 +38,7 @@ public class EmbeddedDataSourceConfigurationTests { this.context = new AnnotationConfigApplicationContext(); this.context.register(EmbeddedDataSourceConfiguration.class); this.context.refresh(); - assertNotNull(this.context.getBean(DataSource.class)); + assertThat(this.context.getBean(DataSource.class)).isNotNull(); this.context.close(); } diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/EmbeddedDatabaseConnectionTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/EmbeddedDatabaseConnectionTests.java index 22654ddd53..1fd8699d3c 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/EmbeddedDatabaseConnectionTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/EmbeddedDatabaseConnectionTests.java @@ -20,8 +20,7 @@ import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; -import static org.hamcrest.CoreMatchers.is; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link EmbeddedDatabaseConnection}. @@ -35,20 +34,20 @@ public class EmbeddedDatabaseConnectionTests { @Test public void h2CustomDatabaseName() { - assertThat(EmbeddedDatabaseConnection.H2.getUrl("mydb"), - is("jdbc:h2:mem:mydb;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE")); + assertThat(EmbeddedDatabaseConnection.H2.getUrl("mydb")) + .isEqualTo("jdbc:h2:mem:mydb;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE"); } @Test public void derbyCustomDatabaseName() { - assertThat(EmbeddedDatabaseConnection.DERBY.getUrl("myderbydb"), - is("jdbc:derby:memory:myderbydb;create=true")); + assertThat(EmbeddedDatabaseConnection.DERBY.getUrl("myderbydb")) + .isEqualTo("jdbc:derby:memory:myderbydb;create=true"); } @Test public void hsqlCustomDatabaseName() { - assertThat(EmbeddedDatabaseConnection.HSQL.getUrl("myhsql"), - is("jdbc:hsqldb:mem:myhsql")); + assertThat(EmbeddedDatabaseConnection.HSQL.getUrl("myhsql")) + .isEqualTo("jdbc:hsqldb:mem:myhsql"); } @Test diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/HikariDataSourceConfigurationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/HikariDataSourceConfigurationTests.java index d18d69c059..caf0ef4f7a 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/HikariDataSourceConfigurationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/HikariDataSourceConfigurationTests.java @@ -32,8 +32,7 @@ import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.util.ReflectionUtils; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link HikariDataSourceConfiguration}. @@ -55,8 +54,8 @@ public class HikariDataSourceConfigurationTests { public void testDataSourceExists() throws Exception { this.context.register(HikariDataSourceConfiguration.class); this.context.refresh(); - assertNotNull(this.context.getBean(DataSource.class)); - assertNotNull(this.context.getBean(HikariDataSource.class)); + assertThat(this.context.getBean(DataSource.class)).isNotNull(); + assertThat(this.context.getBean(HikariDataSource.class)).isNotNull(); } @Test @@ -67,8 +66,8 @@ public class HikariDataSourceConfigurationTests { EnvironmentTestUtils.addEnvironment(this.context, PREFIX + "maxLifetime:1234"); this.context.refresh(); HikariDataSource ds = this.context.getBean(HikariDataSource.class); - assertEquals("jdbc:foo//bar/spam", ds.getJdbcUrl()); - assertEquals(1234, ds.getMaxLifetime()); + assertThat(ds.getJdbcUrl()).isEqualTo("jdbc:foo//bar/spam"); + assertThat(ds.getMaxLifetime()).isEqualTo(1234); // TODO: test JDBC4 isValid() } @@ -79,8 +78,8 @@ public class HikariDataSourceConfigurationTests { + "dataSourceProperties.dataSourceClassName:org.h2.JDBCDataSource"); this.context.refresh(); HikariDataSource ds = this.context.getBean(HikariDataSource.class); - assertEquals("org.h2.JDBCDataSource", - ds.getDataSourceProperties().getProperty("dataSourceClassName")); + assertThat(ds.getDataSourceProperties().getProperty("dataSourceClassName")) + .isEqualTo("org.h2.JDBCDataSource"); } @Test @@ -88,7 +87,7 @@ public class HikariDataSourceConfigurationTests { this.context.register(HikariDataSourceConfiguration.class); this.context.refresh(); HikariDataSource ds = this.context.getBean(HikariDataSource.class); - assertEquals(1800000, ds.getMaxLifetime()); + assertThat(ds.getMaxLifetime()).isEqualTo(1800000); } @SuppressWarnings("unchecked") diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/JndiDataSourceAutoConfigurationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/JndiDataSourceAutoConfigurationTests.java index 589392c122..bc7ee0d192 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/JndiDataSourceAutoConfigurationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/JndiDataSourceAutoConfigurationTests.java @@ -35,10 +35,7 @@ import org.springframework.context.annotation.AnnotationConfigApplicationContext import org.springframework.context.annotation.Bean; import org.springframework.jmx.export.MBeanExporter; -import static org.hamcrest.Matchers.contains; -import static org.hamcrest.Matchers.hasSize; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link JndiDataSourceAutoConfiguration} @@ -95,7 +92,7 @@ public class JndiDataSourceAutoConfigurationTests { this.context.register(JndiDataSourceAutoConfiguration.class); this.context.refresh(); - assertEquals(dataSource, this.context.getBean(DataSource.class)); + assertThat(this.context.getBean(DataSource.class)).isEqualTo(dataSource); } @SuppressWarnings("unchecked") @@ -112,11 +109,11 @@ public class JndiDataSourceAutoConfigurationTests { MBeanExporterConfiguration.class); this.context.refresh(); - assertEquals(dataSource, this.context.getBean(DataSource.class)); + assertThat(this.context.getBean(DataSource.class)).isEqualTo(dataSource); MBeanExporter exporter = this.context.getBean(MBeanExporter.class); Set excludedBeans = (Set) new DirectFieldAccessor(exporter) .getPropertyValue("excludedBeans"); - assertThat(excludedBeans, contains("dataSource")); + assertThat(excludedBeans).containsExactly("dataSource"); } @SuppressWarnings("unchecked") @@ -133,11 +130,11 @@ public class JndiDataSourceAutoConfigurationTests { MBeanExporterConfiguration.class); this.context.refresh(); - assertEquals(dataSource, this.context.getBean(DataSource.class)); + assertThat(this.context.getBean(DataSource.class)).isEqualTo(dataSource); MBeanExporter exporter = this.context.getBean(MBeanExporter.class); Set excludedBeans = (Set) new DirectFieldAccessor(exporter) .getPropertyValue("excludedBeans"); - assertThat(excludedBeans, hasSize(0)); + assertThat(excludedBeans).isEmpty(); } private void configureJndi(String name, DataSource dataSource) diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/TomcatDataSourceConfigurationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/TomcatDataSourceConfigurationTests.java index 5f3ffcda0d..5cdbcfbae1 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/TomcatDataSourceConfigurationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/TomcatDataSourceConfigurationTests.java @@ -36,9 +36,7 @@ import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.EnableMBeanExport; import org.springframework.util.ReflectionUtils; -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; import static org.junit.Assert.fail; /** @@ -69,8 +67,9 @@ public class TomcatDataSourceConfigurationTests { EnvironmentTestUtils.addEnvironment(this.context, PREFIX + "url:jdbc:h2:mem:testdb"); this.context.refresh(); - assertNotNull(this.context.getBean(DataSource.class)); - assertNotNull(this.context.getBean(org.apache.tomcat.jdbc.pool.DataSource.class)); + assertThat(this.context.getBean(DataSource.class)).isNotNull(); + assertThat(this.context.getBean(org.apache.tomcat.jdbc.pool.DataSource.class)) + .isNotNull(); } @Test @@ -93,14 +92,14 @@ public class TomcatDataSourceConfigurationTests { this.context.refresh(); org.apache.tomcat.jdbc.pool.DataSource ds = this.context .getBean(org.apache.tomcat.jdbc.pool.DataSource.class); - assertEquals("jdbc:h2:mem:testdb", ds.getUrl()); - assertTrue(ds.isTestWhileIdle()); - assertTrue(ds.isTestOnBorrow()); - assertTrue(ds.isTestOnReturn()); - assertEquals(10000, ds.getTimeBetweenEvictionRunsMillis()); - assertEquals(12345, ds.getMinEvictableIdleTimeMillis()); - assertEquals(1234, ds.getMaxWait()); - assertEquals(9999L, ds.getValidationInterval()); + assertThat(ds.getUrl()).isEqualTo("jdbc:h2:mem:testdb"); + assertThat(ds.isTestWhileIdle()).isTrue(); + assertThat(ds.isTestOnBorrow()).isTrue(); + assertThat(ds.isTestOnReturn()).isTrue(); + assertThat(ds.getTimeBetweenEvictionRunsMillis()).isEqualTo(10000); + assertThat(ds.getMinEvictableIdleTimeMillis()).isEqualTo(12345); + assertThat(ds.getMaxWait()).isEqualTo(1234); + assertThat(ds.getValidationInterval()).isEqualTo(9999L); assertDataSourceHasInterceptors(ds); } @@ -124,10 +123,10 @@ public class TomcatDataSourceConfigurationTests { this.context.refresh(); org.apache.tomcat.jdbc.pool.DataSource ds = this.context .getBean(org.apache.tomcat.jdbc.pool.DataSource.class); - assertEquals(5000, ds.getTimeBetweenEvictionRunsMillis()); - assertEquals(60000, ds.getMinEvictableIdleTimeMillis()); - assertEquals(30000, ds.getMaxWait()); - assertEquals(30000L, ds.getValidationInterval()); + assertThat(ds.getTimeBetweenEvictionRunsMillis()).isEqualTo(5000); + assertThat(ds.getMinEvictableIdleTimeMillis()).isEqualTo(60000); + assertThat(ds.getMaxWait()).isEqualTo(30000); + assertThat(ds.getValidationInterval()).isEqualTo(30000L); } @SuppressWarnings("unchecked") diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/XADataSourceAutoConfigurationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/XADataSourceAutoConfigurationTests.java index 9807dff79b..d3cb6da698 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/XADataSourceAutoConfigurationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/XADataSourceAutoConfigurationTests.java @@ -29,9 +29,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.assertNotNull; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; /** @@ -47,7 +45,7 @@ public class XADataSourceAutoConfigurationTests { context.getBean(DataSource.class); XADataSource source = context.getBean(XADataSource.class); MockXADataSourceWrapper wrapper = context.getBean(MockXADataSourceWrapper.class); - assertThat(wrapper.getXaDataSource(), equalTo(source)); + assertThat(wrapper.getXaDataSource()).isEqualTo(source); } @Test @@ -58,9 +56,9 @@ public class XADataSourceAutoConfigurationTests { context.getBean(DataSource.class); MockXADataSourceWrapper wrapper = context.getBean(MockXADataSourceWrapper.class); JDBCXADataSource dataSource = (JDBCXADataSource) wrapper.getXaDataSource(); - assertNotNull(dataSource); - assertThat(dataSource.getUrl(), equalTo("jdbc:hsqldb:mem:test")); - assertThat(dataSource.getUser(), equalTo("un")); + assertThat(dataSource).isNotNull(); + assertThat(dataSource.getUrl()).isEqualTo("jdbc:hsqldb:mem:test"); + assertThat(dataSource.getUser()).isEqualTo("un"); } @Test @@ -71,8 +69,8 @@ public class XADataSourceAutoConfigurationTests { context.getBean(DataSource.class); MockXADataSourceWrapper wrapper = context.getBean(MockXADataSourceWrapper.class); JDBCXADataSource dataSource = (JDBCXADataSource) wrapper.getXaDataSource(); - assertNotNull(dataSource); - assertThat(dataSource.getDatabaseName(), equalTo("test")); + assertThat(dataSource).isNotNull(); + assertThat(dataSource.getDatabaseName()).isEqualTo("test"); } diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/metadata/AbstractDataSourcePoolMetadataTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/metadata/AbstractDataSourcePoolMetadataTests.java index d59e07cd86..b53517e636 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/metadata/AbstractDataSourcePoolMetadataTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/metadata/AbstractDataSourcePoolMetadataTests.java @@ -26,7 +26,7 @@ import org.springframework.dao.DataAccessException; import org.springframework.jdbc.core.ConnectionCallback; import org.springframework.jdbc.core.JdbcTemplate; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * Abstract base class for {@link DataSourcePoolMetadata} tests. @@ -44,12 +44,12 @@ public abstract class AbstractDataSourcePoolMetadataTests() { + @Override public Void doInConnection(Connection connection) throws SQLException, DataAccessException { jdbcTemplate.execute(new ConnectionCallback() { + @Override public Void doInConnection(Connection connection) throws SQLException, DataAccessException { - assertEquals(Integer.valueOf(2), - getDataSourceMetadata().getActive()); - assertEquals(Float.valueOf(1F), - getDataSourceMetadata().getUsage()); + assertThat(getDataSourceMetadata().getActive()).isEqualTo(2); + assertThat(getDataSourceMetadata().getUsage()).isEqualTo(1.0f); return null; } + }); return null; } + }); } diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/metadata/CommonsDbcp2DataSourcePoolMetadataTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/metadata/CommonsDbcp2DataSourcePoolMetadataTests.java index 59913cfbbc..7dea8b32b7 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/metadata/CommonsDbcp2DataSourcePoolMetadataTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/metadata/CommonsDbcp2DataSourcePoolMetadataTests.java @@ -20,8 +20,7 @@ import org.apache.commons.dbcp2.BasicDataSource; import org.junit.Before; import org.junit.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link CommonsDbcp2DataSourcePoolMetadata}. @@ -52,7 +51,7 @@ public class CommonsDbcp2DataSourcePoolMetadataTests return null; } }; - assertNull(dsm.getUsage()); + assertThat(dsm.getUsage()).isNull(); } @Test @@ -64,21 +63,22 @@ public class CommonsDbcp2DataSourcePoolMetadataTests return null; } }; - assertNull(dsm.getUsage()); + assertThat(dsm.getUsage()).isNull(); } @Test public void getPoolUsageWithUnlimitedPool() { DataSourcePoolMetadata unlimitedDataSource = createDataSourceMetadata(0, -1); - assertEquals(Float.valueOf(-1F), unlimitedDataSource.getUsage()); + assertThat(unlimitedDataSource.getUsage()).isEqualTo(Float.valueOf(-1F)); } @Override public void getValidationQuery() { BasicDataSource dataSource = createDataSource(); dataSource.setValidationQuery("SELECT FROM FOO"); - assertEquals("SELECT FROM FOO", - new CommonsDbcp2DataSourcePoolMetadata(dataSource).getValidationQuery()); + assertThat( + new CommonsDbcp2DataSourcePoolMetadata(dataSource).getValidationQuery()) + .isEqualTo("SELECT FROM FOO"); } private CommonsDbcp2DataSourcePoolMetadata createDataSourceMetadata(int minSize, diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/metadata/CommonsDbcpDataSourcePoolMetadataTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/metadata/CommonsDbcpDataSourcePoolMetadataTests.java index 8a62ecccf5..595196482b 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/metadata/CommonsDbcpDataSourcePoolMetadataTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/metadata/CommonsDbcpDataSourcePoolMetadataTests.java @@ -20,8 +20,7 @@ import org.apache.commons.dbcp.BasicDataSource; import org.junit.Before; import org.junit.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link CommonsDbcpDataSourcePoolMetadata}. @@ -52,7 +51,7 @@ public class CommonsDbcpDataSourcePoolMetadataTests return null; } }; - assertNull(dsm.getUsage()); + assertThat(dsm.getUsage()).isNull(); } @Test @@ -64,21 +63,21 @@ public class CommonsDbcpDataSourcePoolMetadataTests return null; } }; - assertNull(dsm.getUsage()); + assertThat(dsm.getUsage()).isNull(); } @Test public void getPoolUsageWithUnlimitedPool() { DataSourcePoolMetadata unlimitedDataSource = createDataSourceMetadata(0, -1); - assertEquals(Float.valueOf(-1F), unlimitedDataSource.getUsage()); + assertThat(unlimitedDataSource.getUsage()).isEqualTo(Float.valueOf(-1F)); } @Override public void getValidationQuery() { BasicDataSource dataSource = createDataSource(); dataSource.setValidationQuery("SELECT FROM FOO"); - assertEquals("SELECT FROM FOO", - new CommonsDbcpDataSourcePoolMetadata(dataSource).getValidationQuery()); + assertThat(new CommonsDbcpDataSourcePoolMetadata(dataSource).getValidationQuery()) + .isEqualTo("SELECT FROM FOO"); } private CommonsDbcpDataSourcePoolMetadata createDataSourceMetadata(int minSize, diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/metadata/DataSourcePoolMetadataProvidersTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/metadata/DataSourcePoolMetadataProvidersTests.java index b9dbd9c4dc..eed68e630a 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/metadata/DataSourcePoolMetadataProvidersTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/metadata/DataSourcePoolMetadataProvidersTests.java @@ -25,8 +25,7 @@ import org.junit.Test; import org.mockito.Mock; import org.mockito.MockitoAnnotations; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertSame; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.BDDMockito.given; /** @@ -70,10 +69,11 @@ public class DataSourcePoolMetadataProvidersTests { public void createWithProviders() { DataSourcePoolMetadataProviders provider = new DataSourcePoolMetadataProviders( Arrays.asList(this.firstProvider, this.secondProvider)); - assertSame(this.first, provider.getDataSourcePoolMetadata(this.firstDataSource)); - assertSame(this.second, - provider.getDataSourcePoolMetadata(this.secondDataSource)); - assertNull(provider.getDataSourcePoolMetadata(this.unknownDataSource)); + assertThat(provider.getDataSourcePoolMetadata(this.firstDataSource)) + .isSameAs(this.first); + assertThat(provider.getDataSourcePoolMetadata(this.secondDataSource)) + .isSameAs(this.second); + assertThat(provider.getDataSourcePoolMetadata(this.unknownDataSource)).isNull(); } } diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/metadata/HikariDataSourcePoolMetadataTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/metadata/HikariDataSourcePoolMetadataTests.java index 76e43dbf8d..36270671ae 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/metadata/HikariDataSourcePoolMetadataTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/metadata/HikariDataSourcePoolMetadataTests.java @@ -19,7 +19,7 @@ package org.springframework.boot.autoconfigure.jdbc.metadata; import com.zaxxer.hikari.HikariDataSource; import org.junit.Before; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link HikariDataSourcePoolMetadata}. @@ -46,8 +46,8 @@ public class HikariDataSourcePoolMetadataTests public void getValidationQuery() { HikariDataSource dataSource = createDataSource(0, 4); dataSource.setConnectionTestQuery("SELECT FROM FOO"); - assertEquals("SELECT FROM FOO", - new HikariDataSourcePoolMetadata(dataSource).getValidationQuery()); + assertThat(new HikariDataSourcePoolMetadata(dataSource).getValidationQuery()) + .isEqualTo("SELECT FROM FOO"); } private HikariDataSource createDataSource(int minSize, int maxSize) { diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/metadata/TomcatDataSourcePoolMetadataTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/metadata/TomcatDataSourcePoolMetadataTests.java index 367d1e9ac4..82cd6d9250 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/metadata/TomcatDataSourcePoolMetadataTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/metadata/TomcatDataSourcePoolMetadataTests.java @@ -19,7 +19,7 @@ package org.springframework.boot.autoconfigure.jdbc.metadata; import org.apache.tomcat.jdbc.pool.DataSource; import org.junit.Before; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link TomcatDataSourcePoolMetadata}. @@ -46,8 +46,8 @@ public class TomcatDataSourcePoolMetadataTests public void getValidationQuery() { DataSource dataSource = createDataSource(0, 4); dataSource.setValidationQuery("SELECT FROM FOO"); - assertEquals("SELECT FROM FOO", - new TomcatDataSourcePoolMetadata(dataSource).getValidationQuery()); + assertThat(new TomcatDataSourcePoolMetadata(dataSource).getValidationQuery()) + .isEqualTo("SELECT FROM FOO"); } private DataSource createDataSource(int minSize, int maxSize) { diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationCustomFilterContextPathTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationCustomFilterContextPathTests.java index 296f924663..712964098b 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationCustomFilterContextPathTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationCustomFilterContextPathTests.java @@ -46,7 +46,7 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.WebAppConfiguration; import org.springframework.web.client.RestTemplate; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link JerseyAutoConfiguration} when using custom servlet paths. @@ -69,7 +69,7 @@ public class JerseyAutoConfigurationCustomFilterContextPathTests { public void contextLoads() { ResponseEntity entity = this.restTemplate.getForEntity( "http://localhost:" + this.port + "/app/rest/hello", String.class); - assertEquals(HttpStatus.OK, entity.getStatusCode()); + assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); } @MinimalWebConfiguration diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationCustomFilterPathTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationCustomFilterPathTests.java index 10fc69e321..dee8ecb2f0 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationCustomFilterPathTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationCustomFilterPathTests.java @@ -46,7 +46,7 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.WebAppConfiguration; import org.springframework.web.client.RestTemplate; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link JerseyAutoConfiguration} when using custom servlet paths. @@ -68,7 +68,7 @@ public class JerseyAutoConfigurationCustomFilterPathTests { public void contextLoads() { ResponseEntity entity = this.restTemplate.getForEntity( "http://localhost:" + this.port + "/rest/hello", String.class); - assertEquals(HttpStatus.OK, entity.getStatusCode()); + assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); } @MinimalWebConfiguration diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationCustomServletContextPathTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationCustomServletContextPathTests.java index ee0001ece8..c72ead15b1 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationCustomServletContextPathTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationCustomServletContextPathTests.java @@ -46,7 +46,7 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.WebAppConfiguration; import org.springframework.web.client.RestTemplate; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link JerseyAutoConfiguration} when using custom servlet paths. @@ -68,7 +68,7 @@ public class JerseyAutoConfigurationCustomServletContextPathTests { public void contextLoads() { ResponseEntity entity = this.restTemplate.getForEntity( "http://localhost:" + this.port + "/app/rest/hello", String.class); - assertEquals(HttpStatus.OK, entity.getStatusCode()); + assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); } @MinimalWebConfiguration diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationCustomServletPathTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationCustomServletPathTests.java index 8c0c388144..107224288b 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationCustomServletPathTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationCustomServletPathTests.java @@ -46,7 +46,7 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.WebAppConfiguration; import org.springframework.web.client.RestTemplate; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link JerseyAutoConfiguration} when using custom servlet paths. @@ -68,7 +68,7 @@ public class JerseyAutoConfigurationCustomServletPathTests { public void contextLoads() { ResponseEntity entity = this.restTemplate.getForEntity( "http://localhost:" + this.port + "/rest/hello", String.class); - assertEquals(HttpStatus.OK, entity.getStatusCode()); + assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); } @MinimalWebConfiguration diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationDefaultFilterPathTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationDefaultFilterPathTests.java index ab5296dfd4..65e8fa6dd5 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationDefaultFilterPathTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationDefaultFilterPathTests.java @@ -45,7 +45,7 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.WebAppConfiguration; import org.springframework.web.client.RestTemplate; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link JerseyAutoConfiguration} when using custom servlet paths. @@ -67,7 +67,7 @@ public class JerseyAutoConfigurationDefaultFilterPathTests { public void contextLoads() { ResponseEntity entity = this.restTemplate .getForEntity("http://localhost:" + this.port + "/hello", String.class); - assertEquals(HttpStatus.OK, entity.getStatusCode()); + assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); } @MinimalWebConfiguration diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationDefaultServletPathTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationDefaultServletPathTests.java index a45da8793c..7bd638f5b1 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationDefaultServletPathTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationDefaultServletPathTests.java @@ -45,7 +45,7 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.WebAppConfiguration; import org.springframework.web.client.RestTemplate; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link JerseyAutoConfiguration} when using default servlet paths. @@ -67,7 +67,7 @@ public class JerseyAutoConfigurationDefaultServletPathTests { public void contextLoads() { ResponseEntity entity = this.restTemplate .getForEntity("http://localhost:" + this.port + "/hello", String.class); - assertEquals(HttpStatus.OK, entity.getStatusCode()); + assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); } @MinimalWebConfiguration diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationServletContainerTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationServletContainerTests.java index 2dbc32c38b..0a029b1252 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationServletContainerTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationServletContainerTests.java @@ -43,8 +43,7 @@ import org.springframework.context.annotation.Import; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.WebAppConfiguration; -import static org.hamcrest.Matchers.containsString; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests that verify the behavior when deployed to a Servlet container where Jersey may @@ -66,10 +65,10 @@ public class JerseyAutoConfigurationServletContainerTests { @Test public void existingJerseyServletIsAmended() { - assertThat(output.toString(), - containsString("Configuring existing registration for Jersey servlet")); - assertThat(output.toString(), containsString( - "Servlet " + Application.class.getName() + " was not registered")); + assertThat(output.toString()) + .contains("Configuring existing registration for Jersey servlet"); + assertThat(output.toString()).contains( + "Servlet " + Application.class.getName() + " was not registered"); } @ImportAutoConfiguration({ EmbeddedServletContainerAutoConfiguration.class, diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationWithoutApplicationPathTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationWithoutApplicationPathTests.java index f28645ba34..f5556542d1 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationWithoutApplicationPathTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationWithoutApplicationPathTests.java @@ -45,7 +45,7 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.WebAppConfiguration; import org.springframework.web.client.RestTemplate; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link JerseyAutoConfiguration} when using custom application path. @@ -67,7 +67,7 @@ public class JerseyAutoConfigurationWithoutApplicationPathTests { public void contextLoads() { ResponseEntity entity = this.restTemplate.getForEntity( "http://localhost:" + this.port + "/api/hello", String.class); - assertEquals(HttpStatus.OK, entity.getStatusCode()); + assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); } @MinimalWebConfiguration diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jms/JmsAutoConfigurationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jms/JmsAutoConfigurationTests.java index 27d1360a5f..425efab1cf 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jms/JmsAutoConfigurationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jms/JmsAutoConfigurationTests.java @@ -44,12 +44,7 @@ import org.springframework.jms.core.JmsTemplate; import org.springframework.jms.listener.DefaultMessageListenerContainer; import org.springframework.transaction.jta.JtaTransactionManager; -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.assertSame; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; /** @@ -81,27 +76,25 @@ public class JmsAutoConfigurationTests { JmsTemplate jmsTemplate = this.context.getBean(JmsTemplate.class); JmsMessagingTemplate messagingTemplate = this.context .getBean(JmsMessagingTemplate.class); - assertEquals(jmsTemplate.getConnectionFactory(), connectionFactory); - assertEquals(jmsTemplate, messagingTemplate.getJmsTemplate()); - assertEquals(ACTIVEMQ_EMBEDDED_URL, - ((ActiveMQConnectionFactory) jmsTemplate.getConnectionFactory()) - .getBrokerURL()); - assertTrue("listener container factory should be created by default", - this.context.containsBean("jmsListenerContainerFactory")); + assertThat(connectionFactory).isEqualTo(jmsTemplate.getConnectionFactory()); + assertThat(messagingTemplate.getJmsTemplate()).isEqualTo(jmsTemplate); + assertThat(((ActiveMQConnectionFactory) jmsTemplate.getConnectionFactory()) + .getBrokerURL()).isEqualTo(ACTIVEMQ_EMBEDDED_URL); + assertThat(this.context.containsBean("jmsListenerContainerFactory")).isTrue(); } @Test public void testConnectionFactoryBackOff() { load(TestConfiguration2.class); - assertEquals("foobar", - this.context.getBean(ActiveMQConnectionFactory.class).getBrokerURL()); + assertThat(this.context.getBean(ActiveMQConnectionFactory.class).getBrokerURL()) + .isEqualTo("foobar"); } @Test public void testJmsTemplateBackOff() { load(TestConfiguration3.class); JmsTemplate jmsTemplate = this.context.getBean(JmsTemplate.class); - assertEquals(999, jmsTemplate.getPriority()); + assertThat(jmsTemplate.getPriority()).isEqualTo(999); } @Test @@ -109,7 +102,7 @@ public class JmsAutoConfigurationTests { load(TestConfiguration5.class); JmsMessagingTemplate messagingTemplate = this.context .getBean(JmsMessagingTemplate.class); - assertEquals("fooBar", messagingTemplate.getDefaultDestinationName()); + assertThat(messagingTemplate.getDefaultDestinationName()).isEqualTo("fooBar"); } @Test @@ -117,13 +110,13 @@ public class JmsAutoConfigurationTests { this.context = createContext(TestConfiguration2.class, TestConfiguration3.class, TestConfiguration5.class); JmsTemplate jmsTemplate = this.context.getBean(JmsTemplate.class); - assertEquals(999, jmsTemplate.getPriority()); - assertEquals("foobar", - this.context.getBean(ActiveMQConnectionFactory.class).getBrokerURL()); + assertThat(jmsTemplate.getPriority()).isEqualTo(999); + assertThat(this.context.getBean(ActiveMQConnectionFactory.class).getBrokerURL()) + .isEqualTo("foobar"); JmsMessagingTemplate messagingTemplate = this.context .getBean(JmsMessagingTemplate.class); - assertEquals("fooBar", messagingTemplate.getDefaultDestinationName()); - assertEquals(jmsTemplate, messagingTemplate.getJmsTemplate()); + assertThat(messagingTemplate.getDefaultDestinationName()).isEqualTo("fooBar"); + assertThat(messagingTemplate.getJmsTemplate()).isEqualTo(jmsTemplate); } @Test @@ -131,8 +124,8 @@ public class JmsAutoConfigurationTests { load(EnableJmsConfiguration.class); JmsListenerContainerFactory jmsListenerContainerFactory = this.context.getBean( "jmsListenerContainerFactory", JmsListenerContainerFactory.class); - assertEquals(DefaultJmsListenerContainerFactory.class, - jmsListenerContainerFactory.getClass()); + assertThat(jmsListenerContainerFactory.getClass()) + .isEqualTo(DefaultJmsListenerContainerFactory.class); } @Test @@ -141,8 +134,8 @@ public class JmsAutoConfigurationTests { EnableJmsConfiguration.class); JmsListenerContainerFactory jmsListenerContainerFactory = this.context.getBean( "jmsListenerContainerFactory", JmsListenerContainerFactory.class); - assertEquals(SimpleJmsListenerContainerFactory.class, - jmsListenerContainerFactory.getClass()); + assertThat(jmsListenerContainerFactory.getClass()) + .isEqualTo(SimpleJmsListenerContainerFactory.class); } @Test @@ -153,15 +146,15 @@ public class JmsAutoConfigurationTests { "spring.jms.listener.maxConcurrency=10"); JmsListenerContainerFactory jmsListenerContainerFactory = this.context.getBean( "jmsListenerContainerFactory", JmsListenerContainerFactory.class); - assertEquals(DefaultJmsListenerContainerFactory.class, - jmsListenerContainerFactory.getClass()); + assertThat(jmsListenerContainerFactory.getClass()) + .isEqualTo(DefaultJmsListenerContainerFactory.class); DefaultMessageListenerContainer listenerContainer = ((DefaultJmsListenerContainerFactory) jmsListenerContainerFactory) .createListenerContainer(mock(JmsListenerEndpoint.class)); - assertEquals(false, listenerContainer.isAutoStartup()); - assertEquals(Session.CLIENT_ACKNOWLEDGE, - listenerContainer.getSessionAcknowledgeMode()); - assertEquals(2, listenerContainer.getConcurrentConsumers()); - assertEquals(10, listenerContainer.getMaxConcurrentConsumers()); + assertThat(listenerContainer.isAutoStartup()).isFalse(); + assertThat(listenerContainer.getSessionAcknowledgeMode()) + .isEqualTo(Session.CLIENT_ACKNOWLEDGE); + assertThat(listenerContainer.getConcurrentConsumers()).isEqualTo(2); + assertThat(listenerContainer.getMaxConcurrentConsumers()).isEqualTo(10); } @Test @@ -170,15 +163,14 @@ public class JmsAutoConfigurationTests { EnableJmsConfiguration.class); JmsListenerContainerFactory jmsListenerContainerFactory = this.context.getBean( "jmsListenerContainerFactory", JmsListenerContainerFactory.class); - assertEquals(DefaultJmsListenerContainerFactory.class, - jmsListenerContainerFactory.getClass()); + assertThat(jmsListenerContainerFactory.getClass()) + .isEqualTo(DefaultJmsListenerContainerFactory.class); DefaultMessageListenerContainer listenerContainer = ((DefaultJmsListenerContainerFactory) jmsListenerContainerFactory) .createListenerContainer(mock(JmsListenerEndpoint.class)); - assertFalse("wrong session transacted flag with JTA transactions", - listenerContainer.isSessionTransacted()); - assertSame(this.context.getBean(JtaTransactionManager.class), - new DirectFieldAccessor(listenerContainer) - .getPropertyValue("transactionManager")); + assertThat(listenerContainer.isSessionTransacted()).isFalse(); + assertThat(new DirectFieldAccessor(listenerContainer) + .getPropertyValue("transactionManager")) + .isSameAs(this.context.getBean(JtaTransactionManager.class)); } @Test @@ -187,14 +179,13 @@ public class JmsAutoConfigurationTests { EnableJmsConfiguration.class); JmsListenerContainerFactory jmsListenerContainerFactory = this.context.getBean( "jmsListenerContainerFactory", JmsListenerContainerFactory.class); - assertEquals(DefaultJmsListenerContainerFactory.class, - jmsListenerContainerFactory.getClass()); + assertThat(jmsListenerContainerFactory.getClass()) + .isEqualTo(DefaultJmsListenerContainerFactory.class); DefaultMessageListenerContainer listenerContainer = ((DefaultJmsListenerContainerFactory) jmsListenerContainerFactory) .createListenerContainer(mock(JmsListenerEndpoint.class)); - assertTrue("wrong session transacted flag with no tx manager", - listenerContainer.isSessionTransacted()); - assertNull(new DirectFieldAccessor(listenerContainer) - .getPropertyValue("transactionManager")); + assertThat(listenerContainer.isSessionTransacted()).isTrue(); + assertThat(new DirectFieldAccessor(listenerContainer) + .getPropertyValue("transactionManager")).isNull(); } @Test @@ -202,28 +193,27 @@ public class JmsAutoConfigurationTests { this.context = createContext(EnableJmsConfiguration.class); JmsListenerContainerFactory jmsListenerContainerFactory = this.context.getBean( "jmsListenerContainerFactory", JmsListenerContainerFactory.class); - assertEquals(DefaultJmsListenerContainerFactory.class, - jmsListenerContainerFactory.getClass()); + assertThat(jmsListenerContainerFactory.getClass()) + .isEqualTo(DefaultJmsListenerContainerFactory.class); DefaultMessageListenerContainer listenerContainer = ((DefaultJmsListenerContainerFactory) jmsListenerContainerFactory) .createListenerContainer(mock(JmsListenerEndpoint.class)); - assertTrue("wrong session transacted flag with no tx manager", - listenerContainer.isSessionTransacted()); - assertNull(new DirectFieldAccessor(listenerContainer) - .getPropertyValue("transactionManager")); + assertThat(listenerContainer.isSessionTransacted()).isTrue(); + assertThat(new DirectFieldAccessor(listenerContainer) + .getPropertyValue("transactionManager")).isNull(); } @Test public void testPubSubDisabledByDefault() { load(TestConfiguration.class); JmsTemplate jmsTemplate = this.context.getBean(JmsTemplate.class); - assertFalse(jmsTemplate.isPubSubDomain()); + assertThat(jmsTemplate.isPubSubDomain()).isFalse(); } @Test public void testJmsTemplatePostProcessedSoThatPubSubIsTrue() { load(TestConfiguration4.class); JmsTemplate jmsTemplate = this.context.getBean(JmsTemplate.class); - assertTrue(jmsTemplate.isPubSubDomain()); + assertThat(jmsTemplate.isPubSubDomain()).isTrue(); } @Test @@ -233,8 +223,8 @@ public class JmsAutoConfigurationTests { DefaultMessageListenerContainer defaultMessageListenerContainer = this.context .getBean(DefaultJmsListenerContainerFactory.class) .createListenerContainer(mock(JmsListenerEndpoint.class)); - assertTrue(jmsTemplate.isPubSubDomain()); - assertTrue(defaultMessageListenerContainer.isPubSubDomain()); + assertThat(jmsTemplate.isPubSubDomain()).isTrue(); + assertThat(defaultMessageListenerContainer.isPubSubDomain()).isTrue(); } @Test @@ -243,10 +233,10 @@ public class JmsAutoConfigurationTests { JmsTemplate jmsTemplate = this.context.getBean(JmsTemplate.class); ActiveMQConnectionFactory connectionFactory = this.context .getBean(ActiveMQConnectionFactory.class); - assertNotNull(jmsTemplate); - assertFalse(jmsTemplate.isPubSubDomain()); - assertNotNull(connectionFactory); - assertEquals(jmsTemplate.getConnectionFactory(), connectionFactory); + assertThat(jmsTemplate).isNotNull(); + assertThat(jmsTemplate.isPubSubDomain()).isFalse(); + assertThat(connectionFactory).isNotNull(); + assertThat(connectionFactory).isEqualTo(jmsTemplate.getConnectionFactory()); } @Test @@ -255,12 +245,11 @@ public class JmsAutoConfigurationTests { JmsTemplate jmsTemplate = this.context.getBean(JmsTemplate.class); ActiveMQConnectionFactory connectionFactory = this.context .getBean(ActiveMQConnectionFactory.class); - assertNotNull(jmsTemplate); - assertNotNull(connectionFactory); - assertEquals(jmsTemplate.getConnectionFactory(), connectionFactory); - assertEquals(ACTIVEMQ_NETWORK_URL, - ((ActiveMQConnectionFactory) jmsTemplate.getConnectionFactory()) - .getBrokerURL()); + assertThat(jmsTemplate).isNotNull(); + assertThat(connectionFactory).isNotNull(); + assertThat(connectionFactory).isEqualTo(jmsTemplate.getConnectionFactory()); + assertThat(((ActiveMQConnectionFactory) jmsTemplate.getConnectionFactory()) + .getBrokerURL()).isEqualTo(ACTIVEMQ_NETWORK_URL); } @Test @@ -270,12 +259,11 @@ public class JmsAutoConfigurationTests { JmsTemplate jmsTemplate = this.context.getBean(JmsTemplate.class); ActiveMQConnectionFactory connectionFactory = this.context .getBean(ActiveMQConnectionFactory.class); - assertNotNull(jmsTemplate); - assertNotNull(connectionFactory); - assertEquals(jmsTemplate.getConnectionFactory(), connectionFactory); - assertEquals("tcp://remote-host:10000", - ((ActiveMQConnectionFactory) jmsTemplate.getConnectionFactory()) - .getBrokerURL()); + assertThat(jmsTemplate).isNotNull(); + assertThat(connectionFactory).isNotNull(); + assertThat(connectionFactory).isEqualTo(jmsTemplate.getConnectionFactory()); + assertThat(((ActiveMQConnectionFactory) jmsTemplate.getConnectionFactory()) + .getBrokerURL()).isEqualTo("tcp://remote-host:10000"); } @Test @@ -284,12 +272,12 @@ public class JmsAutoConfigurationTests { JmsTemplate jmsTemplate = this.context.getBean(JmsTemplate.class); PooledConnectionFactory pool = this.context .getBean(PooledConnectionFactory.class); - assertNotNull(jmsTemplate); - assertNotNull(pool); - assertEquals(jmsTemplate.getConnectionFactory(), pool); + assertThat(jmsTemplate).isNotNull(); + assertThat(pool).isNotNull(); + assertThat(pool).isEqualTo(jmsTemplate.getConnectionFactory()); ActiveMQConnectionFactory factory = (ActiveMQConnectionFactory) pool .getConnectionFactory(); - assertEquals(ACTIVEMQ_EMBEDDED_URL, factory.getBrokerURL()); + assertThat(factory.getBrokerURL()).isEqualTo(ACTIVEMQ_EMBEDDED_URL); } @Test @@ -299,12 +287,12 @@ public class JmsAutoConfigurationTests { JmsTemplate jmsTemplate = this.context.getBean(JmsTemplate.class); PooledConnectionFactory pool = this.context .getBean(PooledConnectionFactory.class); - assertNotNull(jmsTemplate); - assertNotNull(pool); - assertEquals(jmsTemplate.getConnectionFactory(), pool); + assertThat(jmsTemplate).isNotNull(); + assertThat(pool).isNotNull(); + assertThat(pool).isEqualTo(jmsTemplate.getConnectionFactory()); ActiveMQConnectionFactory factory = (ActiveMQConnectionFactory) pool .getConnectionFactory(); - assertEquals(ACTIVEMQ_NETWORK_URL, factory.getBrokerURL()); + assertThat(factory.getBrokerURL()).isEqualTo(ACTIVEMQ_NETWORK_URL); } @Test @@ -314,12 +302,12 @@ public class JmsAutoConfigurationTests { JmsTemplate jmsTemplate = this.context.getBean(JmsTemplate.class); PooledConnectionFactory pool = this.context .getBean(PooledConnectionFactory.class); - assertNotNull(jmsTemplate); - assertNotNull(pool); - assertEquals(jmsTemplate.getConnectionFactory(), pool); + assertThat(jmsTemplate).isNotNull(); + assertThat(pool).isNotNull(); + assertThat(pool).isEqualTo(jmsTemplate.getConnectionFactory()); ActiveMQConnectionFactory factory = (ActiveMQConnectionFactory) pool .getConnectionFactory(); - assertEquals("tcp://remote-host:10000", factory.getBrokerURL()); + assertThat(factory.getBrokerURL()).isEqualTo("tcp://remote-host:10000"); } @Test @@ -450,10 +438,12 @@ public class JmsAutoConfigurationTests { @Configuration @EnableJms protected static class EnableJmsConfiguration { + } @Configuration protected static class NoEnableJmsConfiguration { + } } diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jms/JmsPropertiesTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jms/JmsPropertiesTests.java index 888110d346..d38e38d867 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jms/JmsPropertiesTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jms/JmsPropertiesTests.java @@ -18,8 +18,7 @@ package org.springframework.boot.autoconfigure.jms; import org.junit.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link JmsProperties}. @@ -31,21 +30,21 @@ public class JmsPropertiesTests { @Test public void formatConcurrencyNull() { JmsProperties properties = new JmsProperties(); - assertNull(properties.getListener().formatConcurrency()); + assertThat(properties.getListener().formatConcurrency()).isNull(); } @Test public void formatConcurrencyOnlyLowerBound() { JmsProperties properties = new JmsProperties(); properties.getListener().setConcurrency(2); - assertEquals("2", properties.getListener().formatConcurrency()); + assertThat(properties.getListener().formatConcurrency()).isEqualTo("2"); } @Test public void formatConcurrencyOnlyHigherBound() { JmsProperties properties = new JmsProperties(); properties.getListener().setMaxConcurrency(5); - assertEquals("1-5", properties.getListener().formatConcurrency()); + assertThat(properties.getListener().formatConcurrency()).isEqualTo("1-5"); } @Test @@ -53,7 +52,7 @@ public class JmsPropertiesTests { JmsProperties properties = new JmsProperties(); properties.getListener().setConcurrency(2); properties.getListener().setMaxConcurrency(10); - assertEquals("2-10", properties.getListener().formatConcurrency()); + assertThat(properties.getListener().formatConcurrency()).isEqualTo("2-10"); } } diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jms/activemq/ActiveMQAutoConfigurationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jms/activemq/ActiveMQAutoConfigurationTests.java index d103c45657..cf4f6010a8 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jms/activemq/ActiveMQAutoConfigurationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jms/activemq/ActiveMQAutoConfigurationTests.java @@ -29,12 +29,7 @@ import org.springframework.context.annotation.AnnotationConfigApplicationContext import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; -import static org.hamcrest.Matchers.instanceOf; -import static org.hamcrest.Matchers.is; -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; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mockingDetails; @@ -52,16 +47,16 @@ public class ActiveMQAutoConfigurationTests { load(EmptyConfiguration.class); ConnectionFactory connectionFactory = this.context .getBean(ConnectionFactory.class); - assertThat(connectionFactory, instanceOf(ActiveMQConnectionFactory.class)); + assertThat(connectionFactory).isInstanceOf(ActiveMQConnectionFactory.class); String brokerUrl = ((ActiveMQConnectionFactory) connectionFactory).getBrokerURL(); - assertEquals("vm://localhost?broker.persistent=false", brokerUrl); + assertThat(brokerUrl).isEqualTo("vm://localhost?broker.persistent=false"); } @Test public void configurationBacksOffWhenCustomConnectionFactoryExists() { load(CustomConnectionFactoryConfiguration.class); - assertTrue( - mockingDetails(this.context.getBean(ConnectionFactory.class)).isMock()); + assertThat(mockingDetails(this.context.getBean(ConnectionFactory.class)).isMock()) + .isTrue(); } @Test @@ -69,10 +64,10 @@ public class ActiveMQAutoConfigurationTests { load(EmptyConfiguration.class, "spring.activemq.pooled:true"); ConnectionFactory connectionFactory = this.context .getBean(ConnectionFactory.class); - assertThat(connectionFactory, instanceOf(PooledConnectionFactory.class)); + assertThat(connectionFactory).isInstanceOf(PooledConnectionFactory.class); this.context.close(); - assertThat(((PooledConnectionFactory) connectionFactory).createConnection(), - is(nullValue())); + assertThat(((PooledConnectionFactory) connectionFactory).createConnection()) + .isNull(); } private void load(Class config, String... environment) { @@ -103,4 +98,5 @@ public class ActiveMQAutoConfigurationTests { return mock(ConnectionFactory.class); } } + } diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jms/activemq/ActiveMQPropertiesTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jms/activemq/ActiveMQPropertiesTests.java index c2d7bf5e3a..c097ccfde7 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jms/activemq/ActiveMQPropertiesTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jms/activemq/ActiveMQPropertiesTests.java @@ -18,7 +18,7 @@ package org.springframework.boot.autoconfigure.jms.activemq; import org.junit.Test; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link ActiveMQProperties} and ActiveMQConnectionFactoryFactory. @@ -35,32 +35,30 @@ public class ActiveMQPropertiesTests { @Test public void getBrokerUrlIsInMemoryByDefault() { - assertEquals(DEFAULT_EMBEDDED_BROKER_URL, - new ActiveMQConnectionFactoryFactory(this.properties) - .determineBrokerUrl()); + assertThat(new ActiveMQConnectionFactoryFactory(this.properties) + .determineBrokerUrl()).isEqualTo(DEFAULT_EMBEDDED_BROKER_URL); } @Test public void getBrokerUrlUseExplicitBrokerUrl() { this.properties.setBrokerUrl("vm://foo-bar"); - assertEquals("vm://foo-bar", new ActiveMQConnectionFactoryFactory(this.properties) - .determineBrokerUrl()); + assertThat(new ActiveMQConnectionFactoryFactory(this.properties) + .determineBrokerUrl()).isEqualTo("vm://foo-bar"); } @Test public void getBrokerUrlWithInMemorySetToFalse() { this.properties.setInMemory(false); - assertEquals(DEFAULT_NETWORK_BROKER_URL, - new ActiveMQConnectionFactoryFactory(this.properties) - .determineBrokerUrl()); + assertThat(new ActiveMQConnectionFactoryFactory(this.properties) + .determineBrokerUrl()).isEqualTo(DEFAULT_NETWORK_BROKER_URL); } @Test public void getExplicitBrokerUrlAlwaysWins() { this.properties.setBrokerUrl("vm://foo-bar"); this.properties.setInMemory(false); - assertEquals("vm://foo-bar", new ActiveMQConnectionFactoryFactory(this.properties) - .determineBrokerUrl()); + assertThat(new ActiveMQConnectionFactoryFactory(this.properties) + .determineBrokerUrl()).isEqualTo("vm://foo-bar"); } } diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jms/artemis/ArtemisAutoConfigurationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jms/artemis/ArtemisAutoConfigurationTests.java index 1f82090eab..02fd227931 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jms/artemis/ArtemisAutoConfigurationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jms/artemis/ArtemisAutoConfigurationTests.java @@ -54,10 +54,7 @@ import org.springframework.jms.core.SessionCallback; import org.springframework.jms.support.destination.DestinationResolver; import org.springframework.jms.support.destination.DynamicDestinationResolver; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link ArtemisAutoConfiguration}. @@ -85,7 +82,7 @@ public class ArtemisAutoConfigurationTests { JmsTemplate jmsTemplate = this.context.getBean(JmsTemplate.class); ActiveMQConnectionFactory connectionFactory = this.context .getBean(ActiveMQConnectionFactory.class); - assertEquals(jmsTemplate.getConnectionFactory(), connectionFactory); + assertThat(connectionFactory).isEqualTo(jmsTemplate.getConnectionFactory()); assertNettyConnectionFactory(connectionFactory, "localhost", 61616); } @@ -102,14 +99,12 @@ public class ArtemisAutoConfigurationTests { public void embeddedConnectionFactory() { load(EmptyConfiguration.class, "spring.artemis.mode:embedded"); ArtemisProperties properties = this.context.getBean(ArtemisProperties.class); - assertEquals(ArtemisMode.EMBEDDED, properties.getMode()); - assertEquals(1, this.context.getBeansOfType(EmbeddedJMS.class).size()); + assertThat(properties.getMode()).isEqualTo(ArtemisMode.EMBEDDED); + assertThat(this.context.getBeansOfType(EmbeddedJMS.class)).hasSize(1); org.apache.activemq.artemis.core.config.Configuration configuration = this.context .getBean(org.apache.activemq.artemis.core.config.Configuration.class); - assertFalse("Persistence disabled by default", - configuration.isPersistenceEnabled()); - assertFalse("Security disabled by default", configuration.isSecurityEnabled()); - + assertThat(configuration.isPersistenceEnabled()).isFalse(); + assertThat(configuration.isSecurityEnabled()).isFalse(); ActiveMQConnectionFactory connectionFactory = this.context .getBean(ActiveMQConnectionFactory.class); assertInVmConnectionFactory(connectionFactory); @@ -119,12 +114,11 @@ public class ArtemisAutoConfigurationTests { public void embeddedConnectionFactoryByDefault() { // No mode is specified load(EmptyConfiguration.class); - assertEquals(1, this.context.getBeansOfType(EmbeddedJMS.class).size()); + assertThat(this.context.getBeansOfType(EmbeddedJMS.class)).hasSize(1); org.apache.activemq.artemis.core.config.Configuration configuration = this.context .getBean(org.apache.activemq.artemis.core.config.Configuration.class); - assertFalse("Persistence disabled by default", - configuration.isPersistenceEnabled()); - assertFalse("Security disabled by default", configuration.isSecurityEnabled()); + assertThat(configuration.isPersistenceEnabled()).isFalse(); + assertThat(configuration.isSecurityEnabled()).isFalse(); ActiveMQConnectionFactory connectionFactory = this.context .getBean(ActiveMQConnectionFactory.class); @@ -135,7 +129,7 @@ public class ArtemisAutoConfigurationTests { public void nativeConnectionFactoryIfEmbeddedServiceDisabledExplicitly() { // No mode is specified load(EmptyConfiguration.class, "spring.artemis.embedded.enabled:false"); - assertEquals(0, this.context.getBeansOfType(EmbeddedJMS.class).size()); + assertThat(this.context.getBeansOfType(EmbeddedJMS.class)).isEmpty(); ActiveMQConnectionFactory connectionFactory = this.context .getBean(ActiveMQConnectionFactory.class); assertNettyConnectionFactory(connectionFactory, "localhost", 61616); @@ -146,7 +140,7 @@ public class ArtemisAutoConfigurationTests { // No mode is specified load(EmptyConfiguration.class, "spring.artemis.mode:embedded", "spring.artemis.embedded.enabled:false"); - assertEquals(0, this.context.getBeansOfType(EmbeddedJMS.class).size()); + assertThat(this.context.getBeansOfType(EmbeddedJMS.class)).isEmpty(); ActiveMQConnectionFactory connectionFactory = this.context .getBean(ActiveMQConnectionFactory.class); assertInVmConnectionFactory(connectionFactory); @@ -188,7 +182,7 @@ public class ArtemisAutoConfigurationTests { load(CustomArtemisConfiguration.class); org.apache.activemq.artemis.core.config.Configuration configuration = this.context .getBean(org.apache.activemq.artemis.core.config.Configuration.class); - assertEquals("customFooBar", configuration.getName()); + assertThat(configuration.getName()).isEqualTo("customFooBar"); } @Test @@ -218,9 +212,8 @@ public class ArtemisAutoConfigurationTests { JmsTemplate jmsTemplate2 = this.context.getBean(JmsTemplate.class); jmsTemplate2.setReceiveTimeout(1000L); Message message = jmsTemplate2.receive("TestQueue"); - assertNotNull("No message on persistent queue", message); - assertEquals("Invalid message received on queue", msgId, - ((TextMessage) message).getText()); + assertThat(message).isNotNull(); + assertThat(((TextMessage) message).getText()).isEqualTo(msgId); } @Test @@ -232,13 +225,11 @@ public class ArtemisAutoConfigurationTests { ArtemisProperties properties = this.context.getBean(ArtemisProperties.class); ArtemisProperties anotherProperties = anotherContext .getBean(ArtemisProperties.class); - assertTrue("ServerId should not match", properties.getEmbedded() - .getServerId() < anotherProperties.getEmbedded().getServerId()); - + assertThat(properties.getEmbedded().getServerId() < anotherProperties + .getEmbedded().getServerId()).isTrue(); DestinationChecker checker = new DestinationChecker(this.context); checker.checkQueue("Queue1", true); checker.checkQueue("Queue2", true); - DestinationChecker anotherChecker = new DestinationChecker(anotherContext); anotherChecker.checkQueue("Queue2", true); anotherChecker.checkQueue("Queue1", true); @@ -272,8 +263,8 @@ public class ArtemisAutoConfigurationTests { ActiveMQConnectionFactory connectionFactory) { TransportConfiguration transportConfig = getSingleTransportConfiguration( connectionFactory); - assertEquals(InVMConnectorFactory.class.getName(), - transportConfig.getFactoryClassName()); + assertThat(transportConfig.getFactoryClassName()) + .isEqualTo(InVMConnectorFactory.class.getName()); return transportConfig; } @@ -281,10 +272,10 @@ public class ArtemisAutoConfigurationTests { ActiveMQConnectionFactory connectionFactory, String host, int port) { TransportConfiguration transportConfig = getSingleTransportConfiguration( connectionFactory); - assertEquals(NettyConnectorFactory.class.getName(), - transportConfig.getFactoryClassName()); - assertEquals(host, transportConfig.getParams().get("host")); - assertEquals(port, transportConfig.getParams().get("port")); + assertThat(transportConfig.getFactoryClassName()) + .isEqualTo(NettyConnectorFactory.class.getName()); + assertThat(transportConfig.getParams().get("host")).isEqualTo(host); + assertThat(transportConfig.getParams().get("port")).isEqualTo(port); return transportConfig; } @@ -292,7 +283,7 @@ public class ArtemisAutoConfigurationTests { ActiveMQConnectionFactory connectionFactory) { TransportConfiguration[] transportConfigurations = connectionFactory .getServerLocator().getStaticTransportConfigurations(); - assertEquals(1, transportConfigurations.length); + assertThat(transportConfigurations.length).isEqualTo(1); return transportConfigurations[0]; } @@ -357,6 +348,7 @@ public class ArtemisAutoConfigurationTests { @Configuration protected static class EmptyConfiguration { + } @Configuration diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jms/artemis/ArtemisEmbeddedConfigurationFactoryTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jms/artemis/ArtemisEmbeddedConfigurationFactoryTests.java index c4d5cd170f..90fa0ab258 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jms/artemis/ArtemisEmbeddedConfigurationFactoryTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jms/artemis/ArtemisEmbeddedConfigurationFactoryTests.java @@ -20,10 +20,7 @@ import org.apache.activemq.artemis.core.config.Configuration; import org.apache.activemq.artemis.core.server.JournalType; 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 ArtemisEmbeddedConfigurationFactory} @@ -40,9 +37,8 @@ public class ArtemisEmbeddedConfigurationFactoryTests { properties.getEmbedded().setPersistent(true); Configuration configuration = new ArtemisEmbeddedConfigurationFactory(properties) .createConfiguration(); - assertThat(configuration.getJournalDirectory(), - startsWith(System.getProperty("java.io.tmpdir"))); - assertThat(configuration.getJournalDirectory(), endsWith("/journal")); + assertThat(configuration.getJournalDirectory()) + .startsWith(System.getProperty("java.io.tmpdir")).endsWith("/journal"); } @Test @@ -51,8 +47,8 @@ public class ArtemisEmbeddedConfigurationFactoryTests { properties.getEmbedded().setPersistent(true); Configuration configuration = new ArtemisEmbeddedConfigurationFactory(properties) .createConfiguration(); - assertThat(configuration.isPersistenceEnabled(), equalTo(true)); - assertThat(configuration.getJournalType(), equalTo(JournalType.NIO)); + assertThat(configuration.isPersistenceEnabled()).isTrue(); + assertThat(configuration.getJournalType()).isEqualTo(JournalType.NIO); } @Test @@ -60,7 +56,7 @@ public class ArtemisEmbeddedConfigurationFactoryTests { ArtemisProperties properties = new ArtemisProperties(); Configuration configuration = new ArtemisEmbeddedConfigurationFactory(properties) .createConfiguration(); - assertThat(configuration.getClusterPassword().length(), equalTo(36)); + assertThat(configuration.getClusterPassword().length()).isEqualTo(36); } @Test @@ -69,7 +65,7 @@ public class ArtemisEmbeddedConfigurationFactoryTests { properties.getEmbedded().setClusterPassword("password"); Configuration configuration = new ArtemisEmbeddedConfigurationFactory(properties) .createConfiguration(); - assertThat(configuration.getClusterPassword(), equalTo("password")); + assertThat(configuration.getClusterPassword()).isEqualTo("password"); } } diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jms/hornetq/HornetQAutoConfigurationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jms/hornetq/HornetQAutoConfigurationTests.java index cb39d3540c..c13a952f06 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jms/hornetq/HornetQAutoConfigurationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jms/hornetq/HornetQAutoConfigurationTests.java @@ -54,10 +54,7 @@ import org.springframework.jms.core.SessionCallback; import org.springframework.jms.support.destination.DestinationResolver; import org.springframework.jms.support.destination.DynamicDestinationResolver; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link HornetQAutoConfiguration}. @@ -84,7 +81,7 @@ public class HornetQAutoConfigurationTests { JmsTemplate jmsTemplate = this.context.getBean(JmsTemplate.class); HornetQConnectionFactory connectionFactory = this.context .getBean(HornetQConnectionFactory.class); - assertEquals(jmsTemplate.getConnectionFactory(), connectionFactory); + assertThat(connectionFactory).isEqualTo(jmsTemplate.getConnectionFactory()); assertNettyConnectionFactory(connectionFactory, "localhost", 5445); } @@ -102,14 +99,13 @@ public class HornetQAutoConfigurationTests { load(EmptyConfiguration.class, "spring.hornetq.mode:embedded"); HornetQProperties properties = this.context.getBean(HornetQProperties.class); - assertEquals(HornetQMode.EMBEDDED, properties.getMode()); + assertThat(properties.getMode()).isEqualTo(HornetQMode.EMBEDDED); - assertEquals(1, this.context.getBeansOfType(EmbeddedJMS.class).size()); + assertThat(this.context.getBeansOfType(EmbeddedJMS.class)).hasSize(1); org.hornetq.core.config.Configuration configuration = this.context .getBean(org.hornetq.core.config.Configuration.class); - assertFalse("Persistence disabled by default", - configuration.isPersistenceEnabled()); - assertFalse("Security disabled by default", configuration.isSecurityEnabled()); + assertThat(configuration.isPersistenceEnabled()).isFalse(); + assertThat(configuration.isSecurityEnabled()).isFalse(); HornetQConnectionFactory connectionFactory = this.context .getBean(HornetQConnectionFactory.class); @@ -121,12 +117,11 @@ public class HornetQAutoConfigurationTests { // No mode is specified load(EmptyConfiguration.class); - assertEquals(1, this.context.getBeansOfType(EmbeddedJMS.class).size()); + assertThat(this.context.getBeansOfType(EmbeddedJMS.class)).hasSize(1); org.hornetq.core.config.Configuration configuration = this.context .getBean(org.hornetq.core.config.Configuration.class); - assertFalse("Persistence disabled by default", - configuration.isPersistenceEnabled()); - assertFalse("Security disabled by default", configuration.isSecurityEnabled()); + assertThat(configuration.isPersistenceEnabled()).isFalse(); + assertThat(configuration.isSecurityEnabled()).isFalse(); HornetQConnectionFactory connectionFactory = this.context .getBean(HornetQConnectionFactory.class); @@ -138,7 +133,7 @@ public class HornetQAutoConfigurationTests { // No mode is specified load(EmptyConfiguration.class, "spring.hornetq.embedded.enabled:false"); - assertEquals(0, this.context.getBeansOfType(EmbeddedJMS.class).size()); + assertThat(this.context.getBeansOfType(EmbeddedJMS.class)).isEmpty(); HornetQConnectionFactory connectionFactory = this.context .getBean(HornetQConnectionFactory.class); @@ -151,7 +146,7 @@ public class HornetQAutoConfigurationTests { load(EmptyConfiguration.class, "spring.hornetq.mode:embedded", "spring.hornetq.embedded.enabled:false"); - assertEquals(0, this.context.getBeansOfType(EmbeddedJMS.class).size()); + assertThat(this.context.getBeansOfType(EmbeddedJMS.class)).isEmpty(); HornetQConnectionFactory connectionFactory = this.context .getBean(HornetQConnectionFactory.class); @@ -198,7 +193,7 @@ public class HornetQAutoConfigurationTests { load(CustomHornetQConfiguration.class); org.hornetq.core.config.Configuration configuration = this.context .getBean(org.hornetq.core.config.Configuration.class); - assertEquals("customFooBar", configuration.getName()); + assertThat(configuration.getName()).isEqualTo("customFooBar"); } @Test @@ -228,9 +223,8 @@ public class HornetQAutoConfigurationTests { JmsTemplate jmsTemplate2 = this.context.getBean(JmsTemplate.class); jmsTemplate2.setReceiveTimeout(1000L); Message message = jmsTemplate2.receive("TestQueue"); - assertNotNull("No message on persistent queue", message); - assertEquals("Invalid message received on queue", msgId, - ((TextMessage) message).getText()); + assertThat(message).isNotNull(); + assertThat(((TextMessage) message).getText()).isEqualTo(msgId); } @Test @@ -244,8 +238,8 @@ public class HornetQAutoConfigurationTests { HornetQProperties properties = this.context.getBean(HornetQProperties.class); HornetQProperties anotherProperties = anotherContext .getBean(HornetQProperties.class); - assertTrue("ServerId should not match", properties.getEmbedded() - .getServerId() < anotherProperties.getEmbedded().getServerId()); + assertThat(properties.getEmbedded().getServerId() < anotherProperties + .getEmbedded().getServerId()).isTrue(); DestinationChecker checker = new DestinationChecker(this.context); checker.checkQueue("Queue1", true); @@ -286,8 +280,8 @@ public class HornetQAutoConfigurationTests { HornetQConnectionFactory connectionFactory) { TransportConfiguration transportConfig = getSingleTransportConfiguration( connectionFactory); - assertEquals(InVMConnectorFactory.class.getName(), - transportConfig.getFactoryClassName()); + assertThat(transportConfig.getFactoryClassName()) + .isEqualTo(InVMConnectorFactory.class.getName()); return transportConfig; } @@ -295,10 +289,10 @@ public class HornetQAutoConfigurationTests { HornetQConnectionFactory connectionFactory, String host, int port) { TransportConfiguration transportConfig = getSingleTransportConfiguration( connectionFactory); - assertEquals(NettyConnectorFactory.class.getName(), - transportConfig.getFactoryClassName()); - assertEquals(host, transportConfig.getParams().get("host")); - assertEquals(port, transportConfig.getParams().get("port")); + assertThat(transportConfig.getFactoryClassName()) + .isEqualTo(NettyConnectorFactory.class.getName()); + assertThat(transportConfig.getParams().get("host")).isEqualTo(host); + assertThat(transportConfig.getParams().get("port")).isEqualTo(port); return transportConfig; } @@ -306,7 +300,7 @@ public class HornetQAutoConfigurationTests { HornetQConnectionFactory connectionFactory) { TransportConfiguration[] transportConfigurations = connectionFactory .getServerLocator().getStaticTransportConfigurations(); - assertEquals(1, transportConfigurations.length); + assertThat(transportConfigurations.length).isEqualTo(1); return transportConfigurations[0]; } diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jms/hornetq/HornetQEmbeddedConfigurationFactoryTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jms/hornetq/HornetQEmbeddedConfigurationFactoryTests.java index bf3913af55..e0525db606 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jms/hornetq/HornetQEmbeddedConfigurationFactoryTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jms/hornetq/HornetQEmbeddedConfigurationFactoryTests.java @@ -20,10 +20,7 @@ import org.hornetq.core.config.Configuration; import org.hornetq.core.server.JournalType; 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 HornetQEmbeddedConfigurationFactory}. @@ -39,9 +36,8 @@ public class HornetQEmbeddedConfigurationFactoryTests { properties.getEmbedded().setPersistent(true); Configuration configuration = new HornetQEmbeddedConfigurationFactory(properties) .createConfiguration(); - assertThat(configuration.getJournalDirectory(), - startsWith(System.getProperty("java.io.tmpdir"))); - assertThat(configuration.getJournalDirectory(), endsWith("/journal")); + assertThat(configuration.getJournalDirectory()) + .startsWith(System.getProperty("java.io.tmpdir")).endsWith("/journal"); } @Test @@ -50,8 +46,8 @@ public class HornetQEmbeddedConfigurationFactoryTests { properties.getEmbedded().setPersistent(true); Configuration configuration = new HornetQEmbeddedConfigurationFactory(properties) .createConfiguration(); - assertThat(configuration.isPersistenceEnabled(), equalTo(true)); - assertThat(configuration.getJournalType(), equalTo(JournalType.NIO)); + assertThat(configuration.isPersistenceEnabled()).isTrue(); + assertThat(configuration.getJournalType()).isEqualTo(JournalType.NIO); } @Test @@ -59,7 +55,7 @@ public class HornetQEmbeddedConfigurationFactoryTests { HornetQProperties properties = new HornetQProperties(); Configuration configuration = new HornetQEmbeddedConfigurationFactory(properties) .createConfiguration(); - assertThat(configuration.getClusterPassword().length(), equalTo(36)); + assertThat(configuration.getClusterPassword().length()).isEqualTo(36); } @Test @@ -68,7 +64,7 @@ public class HornetQEmbeddedConfigurationFactoryTests { properties.getEmbedded().setClusterPassword("password"); Configuration configuration = new HornetQEmbeddedConfigurationFactory(properties) .createConfiguration(); - assertThat(configuration.getClusterPassword(), equalTo("password")); + assertThat(configuration.getClusterPassword()).isEqualTo("password"); } } diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jmx/JmxAutoConfigurationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jmx/JmxAutoConfigurationTests.java index 1313db084c..370c03a29f 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jmx/JmxAutoConfigurationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jmx/JmxAutoConfigurationTests.java @@ -38,8 +38,7 @@ import org.springframework.jmx.export.naming.MetadataNamingStrategy; import org.springframework.mock.env.MockEnvironment; import org.springframework.test.util.ReflectionTestUtils; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link JmxAutoConfiguration} @@ -68,7 +67,7 @@ public class JmxAutoConfigurationTests { this.context = new AnnotationConfigApplicationContext(); this.context.register(JmxAutoConfiguration.class); this.context.refresh(); - assertNotNull(this.context.getBean(MBeanExporter.class)); + assertThat(this.context.getBean(MBeanExporter.class)).isNotNull(); } @Test @@ -79,7 +78,7 @@ public class JmxAutoConfigurationTests { this.context.setEnvironment(env); this.context.register(JmxAutoConfiguration.class); this.context.refresh(); - assertNotNull(this.context.getBean(MBeanExporter.class)); + assertThat(this.context.getBean(MBeanExporter.class)).isNotNull(); } @Test(expected = NoSuchBeanDefinitionException.class) @@ -103,11 +102,11 @@ public class JmxAutoConfigurationTests { this.context.register(TestConfiguration.class, JmxAutoConfiguration.class); this.context.refresh(); MBeanExporter mBeanExporter = this.context.getBean(MBeanExporter.class); - assertNotNull(mBeanExporter); + assertThat(mBeanExporter).isNotNull(); MetadataNamingStrategy naming = (MetadataNamingStrategy) ReflectionTestUtils .getField(mBeanExporter, "namingStrategy"); - assertEquals("my-test-domain", - ReflectionTestUtils.getField(naming, "defaultDomain")); + assertThat(ReflectionTestUtils.getField(naming, "defaultDomain")) + .isEqualTo("my-test-domain"); } @Test @@ -143,7 +142,7 @@ public class JmxAutoConfigurationTests { IntegrationMBeanExporter mbeanExporter = this.context .getBean(IntegrationMBeanExporter.class); DirectFieldAccessor dfa = new DirectFieldAccessor(mbeanExporter); - assertEquals("foo.my", dfa.getPropertyValue("domain")); + assertThat(dfa.getPropertyValue("domain")).isEqualTo("foo.my"); } @Configuration diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jooq/JooqAutoConfigurationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jooq/JooqAutoConfigurationTests.java index 56452852a9..3118b0cd82 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jooq/JooqAutoConfigurationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jooq/JooqAutoConfigurationTests.java @@ -18,7 +18,6 @@ package org.springframework.boot.autoconfigure.jooq; import javax.sql.DataSource; -import org.hamcrest.Matcher; import org.jooq.DSLContext; import org.jooq.ExecuteListener; import org.jooq.ExecuteListenerProvider; @@ -48,10 +47,7 @@ import org.springframework.dao.DataIntegrityViolationException; import org.springframework.jdbc.datasource.DataSourceTransactionManager; import org.springframework.transaction.PlatformTransactionManager; -import static org.hamcrest.Matchers.equalTo; -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.junit.Assert.fail; /** @@ -88,23 +84,24 @@ public class JooqAutoConfigurationTests { public void noDataSource() throws Exception { registerAndRefresh(JooqAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); - assertEquals(0, this.context.getBeanNamesForType(DSLContext.class).length); + assertThat(this.context.getBeanNamesForType(DSLContext.class).length) + .isEqualTo(0); } @Test public void jooqWithoutTx() throws Exception { registerAndRefresh(JooqDataSourceConfiguration.class, JooqAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); - assertThat(getBeanNames(PlatformTransactionManager.class), equalTo(NO_BEANS)); - assertThat(getBeanNames(SpringTransactionProvider.class), equalTo(NO_BEANS)); + assertThat(getBeanNames(PlatformTransactionManager.class)).isEqualTo(NO_BEANS); + assertThat(getBeanNames(SpringTransactionProvider.class)).isEqualTo(NO_BEANS); DSLContext dsl = this.context.getBean(DSLContext.class); dsl.execute("create table jooqtest (name varchar(255) primary key);"); - dsl.transaction(new AssertFetch(dsl, "select count(*) as total from jooqtest;", - equalTo("0"))); + dsl.transaction( + new AssertFetch(dsl, "select count(*) as total from jooqtest;", "0")); dsl.transaction( new ExecuteSql(dsl, "insert into jooqtest (name) values ('foo');")); - dsl.transaction(new AssertFetch(dsl, "select count(*) as total from jooqtest;", - equalTo("1"))); + dsl.transaction( + new AssertFetch(dsl, "select count(*) as total from jooqtest;", "1")); try { dsl.transaction( new ExecuteSql(dsl, "insert into jooqtest (name) values ('bar');", @@ -114,8 +111,8 @@ public class JooqAutoConfigurationTests { catch (DataIntegrityViolationException ex) { // Ignore } - dsl.transaction(new AssertFetch(dsl, "select count(*) as total from jooqtest;", - equalTo("2"))); + dsl.transaction( + new AssertFetch(dsl, "select count(*) as total from jooqtest;", "2")); } @Test @@ -125,14 +122,14 @@ public class JooqAutoConfigurationTests { JooqAutoConfiguration.class); this.context.getBean(PlatformTransactionManager.class); DSLContext dsl = this.context.getBean(DSLContext.class); - assertEquals(SQLDialect.H2, dsl.configuration().dialect()); + assertThat(dsl.configuration().dialect()).isEqualTo(SQLDialect.H2); dsl.execute("create table jooqtest_tx (name varchar(255) primary key);"); - dsl.transaction(new AssertFetch(dsl, "select count(*) as total from jooqtest_tx;", - equalTo("0"))); + dsl.transaction( + new AssertFetch(dsl, "select count(*) as total from jooqtest_tx;", "0")); dsl.transaction( new ExecuteSql(dsl, "insert into jooqtest_tx (name) values ('foo');")); - dsl.transaction(new AssertFetch(dsl, "select count(*) as total from jooqtest_tx;", - equalTo("1"))); + dsl.transaction( + new AssertFetch(dsl, "select count(*) as total from jooqtest_tx;", "1")); try { dsl.transaction( new ExecuteSql(dsl, "insert into jooqtest (name) values ('bar');", @@ -142,8 +139,8 @@ public class JooqAutoConfigurationTests { catch (DataIntegrityViolationException ex) { // Ignore } - dsl.transaction(new AssertFetch(dsl, "select count(*) as total from jooqtest_tx;", - equalTo("1"))); + dsl.transaction( + new AssertFetch(dsl, "select count(*) as total from jooqtest_tx;", "1")); } @Test @@ -154,11 +151,11 @@ public class JooqAutoConfigurationTests { TestExecuteListenerProvider.class, TestVisitListenerProvider.class, JooqAutoConfiguration.class); DSLContext dsl = this.context.getBean(DSLContext.class); - assertEquals(TestRecordMapperProvider.class, - dsl.configuration().recordMapperProvider().getClass()); - assertThat(dsl.configuration().recordListenerProviders().length, equalTo(1)); - assertThat(dsl.configuration().executeListenerProviders().length, equalTo(2)); - assertThat(dsl.configuration().visitListenerProviders().length, equalTo(1)); + assertThat(dsl.configuration().recordMapperProvider().getClass()) + .isEqualTo(TestRecordMapperProvider.class); + assertThat(dsl.configuration().recordListenerProviders().length).isEqualTo(1); + assertThat(dsl.configuration().executeListenerProviders().length).isEqualTo(2); + assertThat(dsl.configuration().visitListenerProviders().length).isEqualTo(1); } @Test @@ -167,8 +164,8 @@ public class JooqAutoConfigurationTests { "spring.jooq.sql-dialect:PoSTGrES"); registerAndRefresh(JooqDataSourceConfiguration.class, JooqAutoConfiguration.class); - assertThat(this.context.getBean(org.jooq.Configuration.class).dialect(), - is(equalTo(SQLDialect.POSTGRES))); + assertThat(this.context.getBean(org.jooq.Configuration.class).dialect()) + .isEqualTo(SQLDialect.POSTGRES); } private void registerAndRefresh(Class... annotatedClasses) { @@ -186,17 +183,18 @@ public class JooqAutoConfigurationTests { private final String sql; - private final Matcher matcher; + private final String expected; - AssertFetch(DSLContext dsl, String sql, Matcher matcher) { + AssertFetch(DSLContext dsl, String sql, String expected) { this.dsl = dsl; this.sql = sql; - this.matcher = matcher; + this.expected = expected; } @Override public void run(org.jooq.Configuration configuration) throws Exception { - assertThat(this.dsl.fetch(this.sql).getValue(0, 0).toString(), this.matcher); + assertThat(this.dsl.fetch(this.sql).getValue(0, 0).toString()) + .isEqualTo(this.expected); } } diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/liquibase/LiquibaseAutoConfigurationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/liquibase/LiquibaseAutoConfigurationTests.java index eb7a9655c1..27e39e71e1 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/liquibase/LiquibaseAutoConfigurationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/liquibase/LiquibaseAutoConfigurationTests.java @@ -33,12 +33,7 @@ import org.springframework.boot.test.EnvironmentTestUtils; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.test.util.ReflectionTestUtils; -import static org.hamcrest.Matchers.instanceOf; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -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; /** * Tests for {@link LiquibaseAutoConfiguration}. @@ -70,7 +65,8 @@ public class LiquibaseAutoConfigurationTests { this.context.register(LiquibaseAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); this.context.refresh(); - assertEquals(0, this.context.getBeanNamesForType(SpringLiquibase.class).length); + assertThat(this.context.getBeanNamesForType(SpringLiquibase.class).length) + .isEqualTo(0); } @Test @@ -80,11 +76,11 @@ public class LiquibaseAutoConfigurationTests { PropertyPlaceholderAutoConfiguration.class); this.context.refresh(); SpringLiquibase liquibase = this.context.getBean(SpringLiquibase.class); - assertEquals("classpath:/db/changelog/db.changelog-master.yaml", - liquibase.getChangeLog()); - assertNull(liquibase.getContexts()); - assertNull(liquibase.getDefaultSchema()); - assertFalse(liquibase.isDropFirst()); + assertThat(liquibase.getChangeLog()) + .isEqualTo("classpath:/db/changelog/db.changelog-master.yaml"); + assertThat(liquibase.getContexts()).isNull(); + assertThat(liquibase.getDefaultSchema()).isNull(); + assertThat(liquibase.isDropFirst()).isFalse(); } @Test @@ -96,8 +92,8 @@ public class LiquibaseAutoConfigurationTests { PropertyPlaceholderAutoConfiguration.class); this.context.refresh(); SpringLiquibase liquibase = this.context.getBean(SpringLiquibase.class); - assertEquals("classpath:/db/changelog/db.changelog-override.xml", - liquibase.getChangeLog()); + assertThat(liquibase.getChangeLog()) + .isEqualTo("classpath:/db/changelog/db.changelog-override.xml"); } @Test @@ -109,7 +105,7 @@ public class LiquibaseAutoConfigurationTests { PropertyPlaceholderAutoConfiguration.class); this.context.refresh(); SpringLiquibase liquibase = this.context.getBean(SpringLiquibase.class); - assertEquals("test, production", liquibase.getContexts()); + assertThat(liquibase.getContexts()).isEqualTo("test, production"); } @Test @@ -121,7 +117,7 @@ public class LiquibaseAutoConfigurationTests { PropertyPlaceholderAutoConfiguration.class); this.context.refresh(); SpringLiquibase liquibase = this.context.getBean(SpringLiquibase.class); - assertEquals("public", liquibase.getDefaultSchema()); + assertThat(liquibase.getDefaultSchema()).isEqualTo("public"); } @Test @@ -132,7 +128,7 @@ public class LiquibaseAutoConfigurationTests { PropertyPlaceholderAutoConfiguration.class); this.context.refresh(); SpringLiquibase liquibase = this.context.getBean(SpringLiquibase.class); - assertTrue(liquibase.isDropFirst()); + assertThat(liquibase.isDropFirst()).isTrue(); } @Test @@ -144,8 +140,8 @@ public class LiquibaseAutoConfigurationTests { PropertyPlaceholderAutoConfiguration.class); this.context.refresh(); SpringLiquibase liquibase = this.context.getBean(SpringLiquibase.class); - assertEquals("jdbc:hsqldb:mem:liquibase", - liquibase.getDataSource().getConnection().getMetaData().getURL()); + assertThat(liquibase.getDataSource().getConnection().getMetaData().getURL()) + .isEqualTo("jdbc:hsqldb:mem:liquibase"); } @Test(expected = BeanCreationException.class) @@ -166,7 +162,7 @@ public class LiquibaseAutoConfigurationTests { this.context.refresh(); SpringLiquibase liquibase = this.context.getBean(SpringLiquibase.class); Object log = ReflectionTestUtils.getField(liquibase, "log"); - assertThat(log, instanceOf(CommonsLoggingLiquibaseLogger.class)); + assertThat(log).isInstanceOf(CommonsLoggingLiquibaseLogger.class); } @Test @@ -178,7 +174,7 @@ public class LiquibaseAutoConfigurationTests { PropertyPlaceholderAutoConfiguration.class); this.context.refresh(); SpringLiquibase liquibase = this.context.getBean(SpringLiquibase.class); - assertEquals("test, production", liquibase.getLabels()); + assertThat(liquibase.getLabels()).isEqualTo("test, production"); } @Test @@ -192,8 +188,8 @@ public class LiquibaseAutoConfigurationTests { SpringLiquibase liquibase = this.context.getBean(SpringLiquibase.class); Map parameters = (Map) ReflectionTestUtils .getField(liquibase, "parameters"); - assertTrue(parameters.containsKey("foo")); - assertEquals("bar", parameters.get("foo")); + assertThat(parameters.containsKey("foo")).isTrue(); + assertThat(parameters.get("foo")).isEqualTo("bar"); } } diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/logging/AutoConfigurationReportLoggingInitializerTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/logging/AutoConfigurationReportLoggingInitializerTests.java index e4675f7388..63258b1ad9 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/logging/AutoConfigurationReportLoggingInitializerTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/logging/AutoConfigurationReportLoggingInitializerTests.java @@ -45,11 +45,7 @@ import org.springframework.context.event.ContextRefreshedEvent; import org.springframework.mock.web.MockServletContext; import org.springframework.web.context.support.AnnotationConfigWebApplicationContext; -import static org.hamcrest.Matchers.containsString; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.not; -import static org.junit.Assert.assertNotNull; -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.BDDMockito.willAnswer; @@ -119,7 +115,7 @@ public class AutoConfigurationReportLoggingInitializerTests { context.register(Config.class); context.refresh(); this.initializer.onApplicationEvent(new ContextRefreshedEvent(context)); - assertThat(this.debugLog.size(), not(equalTo(0))); + assertThat(this.debugLog.size()).isNotEqualTo(0); } @Test @@ -135,9 +131,8 @@ public class AutoConfigurationReportLoggingInitializerTests { this.initializer.onApplicationEvent(new ApplicationFailedEvent( new SpringApplication(), new String[0], context, ex)); } - - assertThat(this.debugLog.size(), not(equalTo(0))); - assertThat(this.infoLog.size(), equalTo(0)); + assertThat(this.debugLog.size()).isNotEqualTo(0); + assertThat(this.infoLog.size()).isEqualTo(0); } @Test @@ -154,9 +149,8 @@ public class AutoConfigurationReportLoggingInitializerTests { this.initializer.onApplicationEvent(new ApplicationFailedEvent( new SpringApplication(), new String[0], context, ex)); } - - assertThat(this.debugLog.size(), equalTo(0)); - assertThat(this.infoLog.size(), not(equalTo(0))); + assertThat(this.debugLog.size()).isEqualTo(0); + assertThat(this.infoLog.size()).isNotEqualTo(0); } @Test @@ -173,8 +167,7 @@ public class AutoConfigurationReportLoggingInitializerTests { } // Just basic sanity check, test is for visual inspection String l = this.debugLog.get(0); - assertThat(l, - containsString("not a web application (OnWebApplicationCondition)")); + assertThat(l).contains("not a web application (OnWebApplicationCondition)"); } @Test @@ -183,7 +176,7 @@ public class AutoConfigurationReportLoggingInitializerTests { context.register(Config.class); new AutoConfigurationReportLoggingInitializer().initialize(context); context.refresh(); - assertNotNull(context.getBean(ConditionEvaluationReport.class)); + assertThat(context.getBean(ConditionEvaluationReport.class)).isNotNull(); } @Test @@ -193,7 +186,7 @@ public class AutoConfigurationReportLoggingInitializerTests { context.register(Config.class); new AutoConfigurationReportLoggingInitializer().initialize(context); context.refresh(); - assertNotNull(context.getBean(ConditionEvaluationReport.class)); + assertThat(context.getBean(ConditionEvaluationReport.class)).isNotNull(); } @Test @@ -201,8 +194,8 @@ public class AutoConfigurationReportLoggingInitializerTests { this.initializer .onApplicationEvent(new ApplicationFailedEvent(new SpringApplication(), new String[0], null, new RuntimeException("Planned"))); - assertThat(this.infoLog.get(0), - containsString("Unable to provide auto-configuration report")); + assertThat(this.infoLog.get(0)) + .contains("Unable to provide auto-configuration report"); } public static class MockLogFactory extends LogFactoryImpl { diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mail/MailSenderAutoConfigurationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mail/MailSenderAutoConfigurationTests.java index 0f27da4c71..72793d2df7 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mail/MailSenderAutoConfigurationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mail/MailSenderAutoConfigurationTests.java @@ -39,9 +39,7 @@ import org.springframework.context.annotation.Configuration; import org.springframework.mail.javamail.JavaMailSender; import org.springframework.mail.javamail.JavaMailSenderImpl; -import static org.junit.Assert.assertEquals; -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.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.times; @@ -100,9 +98,9 @@ public class MailSenderAutoConfigurationTests { load(EmptyConfig.class, "spring.mail.host:" + host); JavaMailSenderImpl bean = (JavaMailSenderImpl) this.context .getBean(JavaMailSender.class); - assertEquals(host, bean.getHost()); - assertEquals(JavaMailSenderImpl.DEFAULT_PORT, bean.getPort()); - assertEquals(JavaMailSenderImpl.DEFAULT_PROTOCOL, bean.getProtocol()); + assertThat(bean.getHost()).isEqualTo(host); + assertThat(bean.getPort()).isEqualTo(JavaMailSenderImpl.DEFAULT_PORT); + assertThat(bean.getProtocol()).isEqualTo(JavaMailSenderImpl.DEFAULT_PROTOCOL); } @Test @@ -113,12 +111,12 @@ public class MailSenderAutoConfigurationTests { "spring.mail.default-encoding:US-ASCII", "spring.mail.protocol:smtps"); JavaMailSenderImpl bean = (JavaMailSenderImpl) this.context .getBean(JavaMailSender.class); - assertEquals(host, bean.getHost()); - assertEquals(42, bean.getPort()); - assertEquals("john", bean.getUsername()); - assertEquals("secret", bean.getPassword()); - assertEquals("US-ASCII", bean.getDefaultEncoding()); - assertEquals("smtps", bean.getProtocol()); + assertThat(bean.getHost()).isEqualTo(host); + assertThat(bean.getPort()).isEqualTo(42); + assertThat(bean.getUsername()).isEqualTo("john"); + assertThat(bean.getPassword()).isEqualTo("secret"); + assertThat(bean.getDefaultEncoding()).isEqualTo("US-ASCII"); + assertThat(bean.getProtocol()).isEqualTo("smtps"); } @Test @@ -127,13 +125,13 @@ public class MailSenderAutoConfigurationTests { "spring.mail.properties.mail.smtp.auth:true"); JavaMailSenderImpl bean = (JavaMailSenderImpl) this.context .getBean(JavaMailSender.class); - assertEquals("true", bean.getJavaMailProperties().get("mail.smtp.auth")); + assertThat(bean.getJavaMailProperties().get("mail.smtp.auth")).isEqualTo("true"); } @Test public void smtpHostNotSet() { load(EmptyConfig.class); - assertEquals(0, this.context.getBeansOfType(JavaMailSender.class).size()); + assertThat(this.context.getBeansOfType(JavaMailSender.class)).isEmpty(); } @Test @@ -142,8 +140,8 @@ public class MailSenderAutoConfigurationTests { "spring.mail.user:user", "spring.mail.password:secret"); JavaMailSenderImpl bean = (JavaMailSenderImpl) this.context .getBean(JavaMailSender.class); - assertNull(bean.getUsername()); - assertNull(bean.getPassword()); + assertThat(bean.getUsername()).isNull(); + assertThat(bean.getPassword()).isNull(); } @Test @@ -151,25 +149,26 @@ public class MailSenderAutoConfigurationTests { Session session = configureJndiSession("foo"); load(EmptyConfig.class, "spring.mail.jndi-name:foo"); Session sessionBean = this.context.getBean(Session.class); - assertEquals(session, sessionBean); - assertEquals(sessionBean, - this.context.getBean(JavaMailSenderImpl.class).getSession()); + assertThat(sessionBean).isEqualTo(session); + assertThat(this.context.getBean(JavaMailSenderImpl.class).getSession()) + .isEqualTo(sessionBean); } @Test public void jndiSessionIgnoredIfJndiNameNotSet() throws NamingException { configureJndiSession("foo"); load(EmptyConfig.class, "spring.mail.host:smtp.acme.org"); - assertEquals(0, this.context.getBeanNamesForType(Session.class).length); - assertNotNull(this.context.getBean(JavaMailSender.class)); + assertThat(this.context.getBeanNamesForType(Session.class).length).isEqualTo(0); + assertThat(this.context.getBean(JavaMailSender.class)).isNotNull(); } @Test public void jndiSessionNotUsedIfJndiNameNotSet() throws NamingException { configureJndiSession("foo"); load(EmptyConfig.class); - assertEquals(0, this.context.getBeanNamesForType(Session.class).length); - assertEquals(0, this.context.getBeanNamesForType(JavaMailSender.class).length); + assertThat(this.context.getBeanNamesForType(Session.class).length).isEqualTo(0); + assertThat(this.context.getBeanNamesForType(JavaMailSender.class).length) + .isEqualTo(0); } @Test diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mobile/DeviceDelegatingViewResolverAutoConfigurationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mobile/DeviceDelegatingViewResolverAutoConfigurationTests.java index 6af2ccb04c..90206c2c31 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mobile/DeviceDelegatingViewResolverAutoConfigurationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mobile/DeviceDelegatingViewResolverAutoConfigurationTests.java @@ -39,9 +39,7 @@ import org.springframework.mobile.device.view.AbstractDeviceDelegatingViewResolv import org.springframework.mobile.device.view.LiteDeviceDelegatingViewResolver; import org.springframework.web.servlet.view.InternalResourceViewResolver; -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; /** * Tests for {@link DeviceDelegatingViewResolverAutoConfiguration}. @@ -87,18 +85,18 @@ public class DeviceDelegatingViewResolverAutoConfigurationTests { AbstractDeviceDelegatingViewResolver deviceDelegatingViewResolver = this.context .getBean("deviceDelegatingViewResolver", AbstractDeviceDelegatingViewResolver.class); - assertNotNull(internalResourceViewResolver); - assertNotNull(deviceDelegatingViewResolver); - assertTrue(deviceDelegatingViewResolver - .getViewResolver() instanceof InternalResourceViewResolver); + assertThat(internalResourceViewResolver).isNotNull(); + assertThat(deviceDelegatingViewResolver).isNotNull(); + assertThat(deviceDelegatingViewResolver.getViewResolver()) + .isInstanceOf(InternalResourceViewResolver.class); try { this.context.getBean(ThymeleafViewResolver.class); } catch (NoSuchBeanDefinitionException ex) { // expected. ThymeleafViewResolver shouldn't be defined. } - assertTrue(deviceDelegatingViewResolver - .getOrder() == internalResourceViewResolver.getOrder() - 1); + assertThat(deviceDelegatingViewResolver.getOrder()) + .isEqualTo(internalResourceViewResolver.getOrder() - 1); } @Test(expected = NoSuchBeanDefinitionException.class) @@ -111,7 +109,7 @@ public class DeviceDelegatingViewResolverAutoConfigurationTests { PropertyPlaceholderAutoConfiguration.class, DeviceDelegatingViewResolverConfiguration.class); this.context.refresh(); - assertNotNull(this.context.getBean(InternalResourceViewResolver.class)); + assertThat(this.context.getBean(InternalResourceViewResolver.class)).isNotNull(); try { this.context.getBean(ThymeleafViewResolver.class); } @@ -138,14 +136,14 @@ public class DeviceDelegatingViewResolverAutoConfigurationTests { AbstractDeviceDelegatingViewResolver deviceDelegatingViewResolver = this.context .getBean("deviceDelegatingViewResolver", AbstractDeviceDelegatingViewResolver.class); - assertNotNull(thymeleafViewResolver); - assertNotNull(deviceDelegatingViewResolver); - assertTrue(deviceDelegatingViewResolver - .getViewResolver() instanceof ThymeleafViewResolver); - assertNotNull(this.context.getBean(InternalResourceViewResolver.class)); - assertNotNull(this.context.getBean(ThymeleafViewResolver.class)); - assertTrue(deviceDelegatingViewResolver - .getOrder() == thymeleafViewResolver.getOrder() - 1); + assertThat(thymeleafViewResolver).isNotNull(); + assertThat(deviceDelegatingViewResolver).isNotNull(); + assertThat(deviceDelegatingViewResolver.getViewResolver()) + .isInstanceOf(ThymeleafViewResolver.class); + assertThat(this.context.getBean(InternalResourceViewResolver.class)).isNotNull(); + assertThat(this.context.getBean(ThymeleafViewResolver.class)).isNotNull(); + assertThat(deviceDelegatingViewResolver.getOrder()) + .isEqualTo(thymeleafViewResolver.getOrder() - 1); } @Test(expected = NoSuchBeanDefinitionException.class) @@ -159,8 +157,8 @@ public class DeviceDelegatingViewResolverAutoConfigurationTests { PropertyPlaceholderAutoConfiguration.class, DeviceDelegatingViewResolverConfiguration.class); this.context.refresh(); - assertNotNull(this.context.getBean(InternalResourceViewResolver.class)); - assertNotNull(this.context.getBean(ThymeleafViewResolver.class)); + assertThat(this.context.getBean(InternalResourceViewResolver.class)).isNotNull(); + assertThat(this.context.getBean(ThymeleafViewResolver.class)).isNotNull(); this.context.getBean("deviceDelegatingViewResolver", AbstractDeviceDelegatingViewResolver.class); } @@ -181,13 +179,13 @@ public class DeviceDelegatingViewResolverAutoConfigurationTests { DirectFieldAccessor accessor = new DirectFieldAccessor( liteDeviceDelegatingViewResolver); - assertEquals(false, accessor.getPropertyValue("enableFallback")); - assertEquals("", accessor.getPropertyValue("normalPrefix")); - assertEquals("mobile/", accessor.getPropertyValue("mobilePrefix")); - assertEquals("tablet/", accessor.getPropertyValue("tabletPrefix")); - assertEquals("", accessor.getPropertyValue("normalSuffix")); - assertEquals("", accessor.getPropertyValue("mobileSuffix")); - assertEquals("", accessor.getPropertyValue("tabletSuffix")); + assertThat(accessor.getPropertyValue("enableFallback")).isEqualTo(Boolean.FALSE); + assertThat(accessor.getPropertyValue("normalPrefix")).isEqualTo(""); + assertThat(accessor.getPropertyValue("mobilePrefix")).isEqualTo("mobile/"); + assertThat(accessor.getPropertyValue("tabletPrefix")).isEqualTo("tablet/"); + assertThat(accessor.getPropertyValue("normalSuffix")).isEqualTo(""); + assertThat(accessor.getPropertyValue("mobileSuffix")).isEqualTo(""); + assertThat(accessor.getPropertyValue("tabletSuffix")).isEqualTo(""); } @Test @@ -195,7 +193,7 @@ public class DeviceDelegatingViewResolverAutoConfigurationTests { PropertyAccessor accessor = getLiteDeviceDelegatingViewResolverAccessor( "spring.mobile.devicedelegatingviewresolver.enabled:true", "spring.mobile.devicedelegatingviewresolver.enableFallback:true"); - assertEquals(true, accessor.getPropertyValue("enableFallback")); + assertThat(accessor.getPropertyValue("enableFallback")).isEqualTo(Boolean.TRUE); } @Test @@ -203,7 +201,7 @@ public class DeviceDelegatingViewResolverAutoConfigurationTests { PropertyAccessor accessor = getLiteDeviceDelegatingViewResolverAccessor( "spring.mobile.devicedelegatingviewresolver.enabled:true", "spring.mobile.devicedelegatingviewresolver.normalPrefix:normal/"); - assertEquals("normal/", accessor.getPropertyValue("normalPrefix")); + assertThat(accessor.getPropertyValue("normalPrefix")).isEqualTo("normal/"); } @Test @@ -211,7 +209,7 @@ public class DeviceDelegatingViewResolverAutoConfigurationTests { PropertyAccessor accessor = getLiteDeviceDelegatingViewResolverAccessor( "spring.mobile.devicedelegatingviewresolver.enabled:true", "spring.mobile.devicedelegatingviewresolver.mobilePrefix:mob/"); - assertEquals("mob/", accessor.getPropertyValue("mobilePrefix")); + assertThat(accessor.getPropertyValue("mobilePrefix")).isEqualTo("mob/"); } @Test @@ -219,7 +217,7 @@ public class DeviceDelegatingViewResolverAutoConfigurationTests { PropertyAccessor accessor = getLiteDeviceDelegatingViewResolverAccessor( "spring.mobile.devicedelegatingviewresolver.enabled:true", "spring.mobile.devicedelegatingviewresolver.tabletPrefix:tab/"); - assertEquals("tab/", accessor.getPropertyValue("tabletPrefix")); + assertThat(accessor.getPropertyValue("tabletPrefix")).isEqualTo("tab/"); } @Test @@ -227,7 +225,7 @@ public class DeviceDelegatingViewResolverAutoConfigurationTests { PropertyAccessor accessor = getLiteDeviceDelegatingViewResolverAccessor( "spring.mobile.devicedelegatingviewresolver.enabled:true", "spring.mobile.devicedelegatingviewresolver.normalSuffix:.nor"); - assertEquals(".nor", accessor.getPropertyValue("normalSuffix")); + assertThat(accessor.getPropertyValue("normalSuffix")).isEqualTo(".nor"); } @Test @@ -235,7 +233,7 @@ public class DeviceDelegatingViewResolverAutoConfigurationTests { PropertyAccessor accessor = getLiteDeviceDelegatingViewResolverAccessor( "spring.mobile.devicedelegatingviewresolver.enabled:true", "spring.mobile.devicedelegatingviewresolver.mobileSuffix:.mob"); - assertEquals(".mob", accessor.getPropertyValue("mobileSuffix")); + assertThat(accessor.getPropertyValue("mobileSuffix")).isEqualTo(".mob"); } @Test @@ -243,7 +241,7 @@ public class DeviceDelegatingViewResolverAutoConfigurationTests { PropertyAccessor accessor = getLiteDeviceDelegatingViewResolverAccessor( "spring.mobile.devicedelegatingviewresolver.enabled:true", "spring.mobile.devicedelegatingviewresolver.tabletSuffix:.tab"); - assertEquals(".tab", accessor.getPropertyValue("tabletSuffix")); + assertThat(accessor.getPropertyValue("tabletSuffix")).isEqualTo(".tab"); } private PropertyAccessor getLiteDeviceDelegatingViewResolverAccessor( diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mobile/DeviceResolverAutoConfigurationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mobile/DeviceResolverAutoConfigurationTests.java index 06e2d49bca..722e84b7c8 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mobile/DeviceResolverAutoConfigurationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mobile/DeviceResolverAutoConfigurationTests.java @@ -42,10 +42,7 @@ import org.springframework.web.context.support.AnnotationConfigWebApplicationCon import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping; -import static org.hamcrest.Matchers.hasItemInArray; -import static org.hamcrest.Matchers.instanceOf; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertThat; +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.status; @@ -71,7 +68,8 @@ public class DeviceResolverAutoConfigurationTests { this.context = new AnnotationConfigWebApplicationContext(); this.context.register(DeviceResolverAutoConfiguration.class); this.context.refresh(); - assertNotNull(this.context.getBean(DeviceResolverHandlerInterceptor.class)); + assertThat(this.context.getBean(DeviceResolverHandlerInterceptor.class)) + .isNotNull(); } @Test @@ -79,7 +77,8 @@ public class DeviceResolverAutoConfigurationTests { this.context = new AnnotationConfigWebApplicationContext(); this.context.register(DeviceResolverAutoConfiguration.class); this.context.refresh(); - assertNotNull(this.context.getBean(DeviceHandlerMethodArgumentResolver.class)); + assertThat(this.context.getBean(DeviceHandlerMethodArgumentResolver.class)) + .isNotNull(); } @Test @@ -92,8 +91,8 @@ public class DeviceResolverAutoConfigurationTests { .getBean(RequestMappingHandlerMapping.class); HandlerInterceptor[] interceptors = mapping .getHandler(new MockHttpServletRequest()).getInterceptors(); - assertThat(interceptors, - hasItemInArray(instanceOf(DeviceResolverHandlerInterceptor.class))); + assertThat(interceptors) + .hasAtLeastOneElementOfType(DeviceResolverHandlerInterceptor.class); } @Test diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mobile/SitePreferenceAutoConfigurationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mobile/SitePreferenceAutoConfigurationTests.java index edd64fbf5e..4769e51438 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mobile/SitePreferenceAutoConfigurationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mobile/SitePreferenceAutoConfigurationTests.java @@ -36,10 +36,7 @@ import org.springframework.web.context.support.AnnotationConfigWebApplicationCon import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping; -import static org.hamcrest.Matchers.hasItemInArray; -import static org.hamcrest.Matchers.instanceOf; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link SitePreferenceAutoConfiguration}. @@ -63,7 +60,8 @@ public class SitePreferenceAutoConfigurationTests { this.context = new AnnotationConfigWebApplicationContext(); this.context.register(SitePreferenceAutoConfiguration.class); this.context.refresh(); - assertNotNull(this.context.getBean(SitePreferenceHandlerInterceptor.class)); + assertThat(this.context.getBean(SitePreferenceHandlerInterceptor.class)) + .isNotNull(); } @Test @@ -73,7 +71,8 @@ public class SitePreferenceAutoConfigurationTests { "spring.mobile.sitepreference.enabled:true"); this.context.register(SitePreferenceAutoConfiguration.class); this.context.refresh(); - assertNotNull(this.context.getBean(SitePreferenceHandlerInterceptor.class)); + assertThat(this.context.getBean(SitePreferenceHandlerInterceptor.class)) + .isNotNull(); } @Test(expected = NoSuchBeanDefinitionException.class) @@ -91,8 +90,9 @@ public class SitePreferenceAutoConfigurationTests { this.context = new AnnotationConfigWebApplicationContext(); this.context.register(SitePreferenceAutoConfiguration.class); this.context.refresh(); - assertNotNull( - this.context.getBean(SitePreferenceHandlerMethodArgumentResolver.class)); + assertThat( + this.context.getBean(SitePreferenceHandlerMethodArgumentResolver.class)) + .isNotNull(); } @Test @@ -102,8 +102,9 @@ public class SitePreferenceAutoConfigurationTests { "spring.mobile.sitepreference.enabled:true"); this.context.register(SitePreferenceAutoConfiguration.class); this.context.refresh(); - assertNotNull( - this.context.getBean(SitePreferenceHandlerMethodArgumentResolver.class)); + assertThat( + this.context.getBean(SitePreferenceHandlerMethodArgumentResolver.class)) + .isNotNull(); } @Test(expected = NoSuchBeanDefinitionException.class) @@ -129,8 +130,8 @@ public class SitePreferenceAutoConfigurationTests { .getBean(RequestMappingHandlerMapping.class); HandlerInterceptor[] interceptors = mapping .getHandler(new MockHttpServletRequest()).getInterceptors(); - assertThat(interceptors, - hasItemInArray(instanceOf(SitePreferenceHandlerInterceptor.class))); + assertThat(interceptors) + .hasAtLeastOneElementOfType(SitePreferenceHandlerInterceptor.class); } @Configuration diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mongo/MongoAutoConfigurationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mongo/MongoAutoConfigurationTests.java index 30af32eee3..5d5a95bacb 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mongo/MongoAutoConfigurationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mongo/MongoAutoConfigurationTests.java @@ -27,7 +27,7 @@ import org.springframework.context.annotation.AnnotationConfigApplicationContext import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link MongoAutoConfiguration}. @@ -49,7 +49,7 @@ public class MongoAutoConfigurationTests { public void clientExists() { this.context = new AnnotationConfigApplicationContext( PropertyPlaceholderAutoConfiguration.class, MongoAutoConfiguration.class); - assertEquals(1, this.context.getBeanNamesForType(Mongo.class).length); + assertThat(this.context.getBeanNamesForType(Mongo.class).length).isEqualTo(1); } @SuppressWarnings("deprecation") @@ -61,8 +61,8 @@ public class MongoAutoConfigurationTests { this.context.register(OptionsConfig.class, PropertyPlaceholderAutoConfiguration.class, MongoAutoConfiguration.class); this.context.refresh(); - assertEquals(300, - this.context.getBean(Mongo.class).getMongoOptions().getSocketTimeout()); + assertThat(this.context.getBean(Mongo.class).getMongoOptions().getSocketTimeout()) + .isEqualTo(300); } @SuppressWarnings("deprecation") @@ -74,8 +74,8 @@ public class MongoAutoConfigurationTests { this.context.register(OptionsConfig.class, PropertyPlaceholderAutoConfiguration.class, MongoAutoConfiguration.class); this.context.refresh(); - assertEquals(300, - this.context.getBean(Mongo.class).getMongoOptions().getSocketTimeout()); + assertThat(this.context.getBean(Mongo.class).getMongoOptions().getSocketTimeout()) + .isEqualTo(300); } @Configuration diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mongo/MongoPropertiesTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mongo/MongoPropertiesTests.java index fd6f5dddeb..4f386c7e2d 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mongo/MongoPropertiesTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mongo/MongoPropertiesTests.java @@ -29,10 +29,7 @@ import org.springframework.boot.test.EnvironmentTestUtils; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.context.annotation.Configuration; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.hasSize; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link MongoProperties}. @@ -50,7 +47,7 @@ public class MongoPropertiesTests { context.register(Conf.class); context.refresh(); MongoProperties properties = context.getBean(MongoProperties.class); - assertThat(properties.getPassword(), equalTo("word".toCharArray())); + assertThat(properties.getPassword()).isEqualTo("word".toCharArray()); } @Test @@ -59,7 +56,7 @@ public class MongoPropertiesTests { properties.setPort(12345); MongoClient client = properties.createMongoClient(null, null); List allAddresses = client.getAllAddress(); - assertThat(allAddresses, hasSize(1)); + assertThat(allAddresses).hasSize(1); assertServerAddress(allAddresses.get(0), "localhost", 12345); } @@ -69,7 +66,7 @@ public class MongoPropertiesTests { properties.setHost("mongo.example.com"); MongoClient client = properties.createMongoClient(null, null); List allAddresses = client.getAllAddress(); - assertThat(allAddresses, hasSize(1)); + assertThat(allAddresses).hasSize(1); assertServerAddress(allAddresses.get(0), "mongo.example.com", 27017); } @@ -112,25 +109,25 @@ public class MongoPropertiesTests { + "mongo2.example.com:23456/test"); MongoClient client = properties.createMongoClient(null, null); List allAddresses = client.getAllAddress(); - assertEquals(2, allAddresses.size()); + assertThat(allAddresses).hasSize(2); assertServerAddress(allAddresses.get(0), "mongo1.example.com", 12345); assertServerAddress(allAddresses.get(1), "mongo2.example.com", 23456); List credentialsList = client.getCredentialsList(); - assertEquals(1, credentialsList.size()); + assertThat(credentialsList).hasSize(1); assertMongoCredential(credentialsList.get(0), "user", "secret", "test"); } private void assertServerAddress(ServerAddress serverAddress, String expectedHost, int expectedPort) { - assertThat(serverAddress.getHost(), equalTo(expectedHost)); - assertThat(serverAddress.getPort(), equalTo(expectedPort)); + assertThat(serverAddress.getHost()).isEqualTo(expectedHost); + assertThat(serverAddress.getPort()).isEqualTo(expectedPort); } private void assertMongoCredential(MongoCredential credentials, String expectedUsername, String expectedPassword, String expectedSource) { - assertThat(credentials.getUserName(), equalTo(expectedUsername)); - assertThat(credentials.getPassword(), equalTo(expectedPassword.toCharArray())); - assertThat(credentials.getSource(), equalTo(expectedSource)); + assertThat(credentials.getUserName()).isEqualTo(expectedUsername); + assertThat(credentials.getPassword()).isEqualTo(expectedPassword.toCharArray()); + assertThat(credentials.getSource()).isEqualTo(expectedSource); } @Configuration diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mongo/embedded/EmbeddedMongoAutoConfigurationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mongo/embedded/EmbeddedMongoAutoConfigurationTests.java index 9aea032796..4d7e1b9ea0 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mongo/embedded/EmbeddedMongoAutoConfigurationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mongo/embedded/EmbeddedMongoAutoConfigurationTests.java @@ -36,11 +36,7 @@ import org.springframework.context.annotation.Configuration; import org.springframework.data.mongodb.core.MongoTemplate; import org.springframework.util.SocketUtils; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.hasItems; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.notNullValue; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link EmbeddedMongoAutoConfiguration}. @@ -78,8 +74,8 @@ public class EmbeddedMongoAutoConfigurationTests { "spring.mongodb.embedded.features=TEXT_SEARCH, SYNC_DELAY"); this.context.register(EmbeddedMongoAutoConfiguration.class); this.context.refresh(); - assertThat(this.context.getBean(EmbeddedMongoProperties.class).getFeatures(), - hasItems(Feature.TEXT_SEARCH, Feature.SYNC_DELAY)); + assertThat(this.context.getBean(EmbeddedMongoProperties.class).getFeatures()) + .contains(Feature.TEXT_SEARCH, Feature.SYNC_DELAY); } @Test @@ -90,9 +86,9 @@ public class EmbeddedMongoAutoConfigurationTests { MongoClientConfiguration.class, PropertyPlaceholderAutoConfiguration.class); this.context.refresh(); - assertThat(this.context.getBean(MongoClient.class).getAddress().getPort(), - equalTo(Integer.valueOf( - this.context.getEnvironment().getProperty("local.mongo.port")))); + assertThat(this.context.getBean(MongoClient.class).getAddress().getPort()) + .isEqualTo(Integer.valueOf( + this.context.getEnvironment().getProperty("local.mongo.port"))); } @Test @@ -108,8 +104,8 @@ public class EmbeddedMongoAutoConfigurationTests { MongoClientConfiguration.class, PropertyPlaceholderAutoConfiguration.class); this.context.refresh(); - assertThat(parent.getEnvironment().getProperty("local.mongo.port"), - is(notNullValue())); + assertThat(parent.getEnvironment().getProperty("local.mongo.port")) + .isNotNull(); } finally { parent.close(); @@ -132,7 +128,7 @@ public class EmbeddedMongoAutoConfigurationTests { MongoTemplate mongo = this.context.getBean(MongoTemplate.class); CommandResult buildInfo = mongo.executeCommand("{ buildInfo: 1 }"); - assertThat(buildInfo.getString("version"), equalTo(expectedVersion)); + assertThat(buildInfo.getString("version")).isEqualTo(expectedVersion); } @Configuration diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mustache/MustacheAutoConfigurationIntegrationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mustache/MustacheAutoConfigurationIntegrationTests.java index bd17e7da38..78680c8b21 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mustache/MustacheAutoConfigurationIntegrationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mustache/MustacheAutoConfigurationIntegrationTests.java @@ -46,7 +46,7 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.WebAppConfiguration; import org.springframework.web.bind.annotation.RequestMapping; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * Integration tests for {@link MustacheAutoConfiguration}. @@ -73,14 +73,14 @@ public class MustacheAutoConfigurationIntegrationTests { public void testHomePage() throws Exception { String body = new TestRestTemplate().getForObject("http://localhost:" + this.port, String.class); - assertTrue(body.contains("Hello World")); + assertThat(body.contains("Hello World")).isTrue(); } @Test public void testPartialPage() throws Exception { String body = new TestRestTemplate() .getForObject("http://localhost:" + this.port + "/partial", String.class); - assertTrue(body.contains("Hello World")); + assertThat(body.contains("Hello World")).isTrue(); } @Target(ElementType.TYPE) diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mustache/MustacheStandaloneIntegrationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mustache/MustacheStandaloneIntegrationTests.java index c0b0f9d465..ef08871732 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mustache/MustacheStandaloneIntegrationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mustache/MustacheStandaloneIntegrationTests.java @@ -31,7 +31,7 @@ import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * Integration Tests for {@link MustacheAutoConfiguration} outside of a web application. @@ -40,7 +40,7 @@ import static org.junit.Assert.assertEquals; */ @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(Application.class) -@IntegrationTest({ "spring.main.web_environment=false", "env.foo=Heaven", "foo=World" }) +@IntegrationTest({ "spring.main.web_environment=false", "env.foo=There", "foo=World" }) public class MustacheStandaloneIntegrationTests { @Autowired @@ -48,26 +48,27 @@ public class MustacheStandaloneIntegrationTests { @Test public void directCompilation() throws Exception { - assertEquals("Hello: World", this.compiler.compile("Hello: {{world}}") - .execute(Collections.singletonMap("world", "World"))); + assertThat(this.compiler.compile("Hello: {{world}}") + .execute(Collections.singletonMap("world", "World"))) + .isEqualTo("Hello: World"); } @Test public void environmentCollectorCompoundKey() throws Exception { - assertEquals("Hello: Heaven", - this.compiler.compile("Hello: {{env.foo}}").execute(new Object())); + assertThat(this.compiler.compile("Hello: {{env.foo}}").execute(new Object())) + .isEqualTo("Hello: There"); } @Test public void environmentCollectorCompoundKeyStandard() throws Exception { - assertEquals("Hello: Heaven", this.compiler.standardsMode(true) - .compile("Hello: {{env.foo}}").execute(new Object())); + assertThat(this.compiler.standardsMode(true).compile("Hello: {{env.foo}}") + .execute(new Object())).isEqualTo("Hello: There"); } @Test public void environmentCollectorSimpleKey() throws Exception { - assertEquals("Hello: World", - this.compiler.compile("Hello: {{foo}}").execute(new Object())); + assertThat(this.compiler.compile("Hello: {{foo}}").execute(new Object())) + .isEqualTo("Hello: World"); } @Configuration diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mustache/web/MustacheViewResolverTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mustache/web/MustacheViewResolverTests.java index 9dfc543fba..dff2651272 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mustache/web/MustacheViewResolverTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mustache/web/MustacheViewResolverTests.java @@ -28,10 +28,7 @@ import org.springframework.mock.web.MockServletContext; import org.springframework.web.context.support.StaticWebApplicationContext; import org.springframework.web.servlet.View; -import static org.hamcrest.Matchers.equalTo; -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; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.spy; @@ -57,39 +54,41 @@ public class MustacheViewResolverTests { @Test public void resolveNonExistent() throws Exception { - assertNull(this.resolver.resolveViewName("bar", null)); + assertThat(this.resolver.resolveViewName("bar", null)).isNull(); } @Test public void resolveNullLocale() throws Exception { - assertNotNull(this.resolver.resolveViewName("foo", null)); + assertThat(this.resolver.resolveViewName("foo", null)).isNotNull(); } @Test public void resolveDefaultLocale() throws Exception { - assertNotNull(this.resolver.resolveViewName("foo", Locale.US)); + assertThat(this.resolver.resolveViewName("foo", Locale.US)).isNotNull(); } @Test public void resolveDoubleLocale() throws Exception { - assertNotNull(this.resolver.resolveViewName("foo", Locale.CANADA_FRENCH)); + assertThat(this.resolver.resolveViewName("foo", Locale.CANADA_FRENCH)) + .isNotNull(); } @Test public void resolveTripleLocale() throws Exception { - assertNotNull(this.resolver.resolveViewName("foo", new Locale("en", "GB", "cy"))); + assertThat(this.resolver.resolveViewName("foo", new Locale("en", "GB", "cy"))) + .isNotNull(); } @Test public void resolveSpecificLocale() throws Exception { - assertNotNull(this.resolver.resolveViewName("foo", new Locale("de"))); + assertThat(this.resolver.resolveViewName("foo", new Locale("de"))).isNotNull(); } @Test public void setsContentType() throws Exception { this.resolver.setContentType("application/octet-stream"); View view = this.resolver.resolveViewName("foo", null); - assertThat(view.getContentType(), equalTo("application/octet-stream")); + assertThat(view.getContentType()).isEqualTo("application/octet-stream"); } diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mustache/web/MustacheViewTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mustache/web/MustacheViewTests.java index 1226b315eb..99bd801831 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mustache/web/MustacheViewTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mustache/web/MustacheViewTests.java @@ -28,7 +28,7 @@ import org.springframework.mock.web.MockServletContext; import org.springframework.web.context.WebApplicationContext; import org.springframework.web.context.support.AnnotationConfigWebApplicationContext; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link MustacheView}. @@ -60,7 +60,7 @@ public class MustacheViewTests { view.setApplicationContext(this.context); view.render(Collections.singletonMap("msg", "World"), this.request, this.response); - assertEquals("Hello World", this.response.getContentAsString()); + assertThat(this.response.getContentAsString()).isEqualTo("Hello World"); } } diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mustache/web/MustacheWebIntegrationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mustache/web/MustacheWebIntegrationTests.java index f2b09f85f4..756cdc9114 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mustache/web/MustacheWebIntegrationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mustache/web/MustacheWebIntegrationTests.java @@ -52,8 +52,7 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.WebAppConfiguration; import org.springframework.web.bind.annotation.RequestMapping; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * Integration Tests for {@link MustacheAutoConfiguration}, {@link MustacheViewResolver} @@ -82,21 +81,22 @@ public class MustacheWebIntegrationTests { Template tmpl = Mustache.compiler().compile(source); Map context = new HashMap(); context.put("arg", "world"); - assertEquals("Hello world!", tmpl.execute(context)); // returns "Hello world!" + assertThat(tmpl.execute(context)).isEqualTo("Hello world!"); // returns "Hello + // world!" } @Test public void testHomePage() throws Exception { String body = new TestRestTemplate().getForObject("http://localhost:" + this.port, String.class); - assertTrue(body.contains("Hello World")); + assertThat(body.contains("Hello World")).isTrue(); } @Test public void testPartialPage() throws Exception { String body = new TestRestTemplate() .getForObject("http://localhost:" + this.port + "/partial", String.class); - assertTrue(body.contains("Hello World")); + assertThat(body.contains("Hello World")).isTrue(); } @Target(ElementType.TYPE) diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/orm/jpa/AbstractJpaAutoConfigurationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/orm/jpa/AbstractJpaAutoConfigurationTests.java index 870d182c1a..595c3fd5da 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/orm/jpa/AbstractJpaAutoConfigurationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/orm/jpa/AbstractJpaAutoConfigurationTests.java @@ -52,12 +52,7 @@ import org.springframework.orm.jpa.support.OpenEntityManagerInViewInterceptor; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.web.context.support.AnnotationConfigWebApplicationContext; -import static org.hamcrest.CoreMatchers.instanceOf; -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.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * Base for JPA tests and tests for {@link JpaBaseConfiguration}. @@ -93,8 +88,8 @@ public abstract class AbstractJpaAutoConfigurationTests { public void testEntityManagerCreated() throws Exception { setupTestConfiguration(); this.context.refresh(); - assertNotNull(this.context.getBean(DataSource.class)); - assertNotNull(this.context.getBean(JpaTransactionManager.class)); + assertThat(this.context.getBean(DataSource.class)).isNotNull(); + assertThat(this.context.getBean(JpaTransactionManager.class)).isNotNull(); } @Test @@ -102,9 +97,9 @@ public abstract class AbstractJpaAutoConfigurationTests { this.context.register(DataSourceTransactionManagerAutoConfiguration.class); setupTestConfiguration(); this.context.refresh(); - assertNotNull(this.context.getBean(DataSource.class)); - assertTrue(this.context - .getBean("transactionManager") instanceof JpaTransactionManager); + assertThat(this.context.getBean(DataSource.class)).isNotNull(); + assertThat(this.context.getBean("transactionManager")) + .isInstanceOf(JpaTransactionManager.class); } @Test @@ -113,7 +108,7 @@ public abstract class AbstractJpaAutoConfigurationTests { context.register(TestConfiguration.class, EmbeddedDataSourceConfiguration.class, PropertyPlaceholderAutoConfiguration.class, getAutoConfigureClass()); context.refresh(); - assertNotNull(context.getBean(OpenEntityManagerInViewInterceptor.class)); + assertThat(context.getBean(OpenEntityManagerInViewInterceptor.class)).isNotNull(); context.close(); } @@ -125,7 +120,7 @@ public abstract class AbstractJpaAutoConfigurationTests { EmbeddedDataSourceConfiguration.class, PropertyPlaceholderAutoConfiguration.class, getAutoConfigureClass()); context.refresh(); - assertEquals(0, getInterceptorBeans(context).length); + assertThat(getInterceptorBeans(context).length).isEqualTo(0); context.close(); } @@ -137,7 +132,7 @@ public abstract class AbstractJpaAutoConfigurationTests { context.register(TestConfiguration.class, EmbeddedDataSourceConfiguration.class, PropertyPlaceholderAutoConfiguration.class, getAutoConfigureClass()); context.refresh(); - assertEquals(0, getInterceptorBeans(context).length); + assertThat(getInterceptorBeans(context).length).isEqualTo(0); context.close(); } @@ -150,9 +145,9 @@ public abstract class AbstractJpaAutoConfigurationTests { LocalContainerEntityManagerFactoryBean bean = this.context .getBean(LocalContainerEntityManagerFactoryBean.class); Map map = bean.getJpaPropertyMap(); - assertThat(map.get("a"), equalTo((Object) "b")); - assertThat(map.get("c"), equalTo((Object) "d")); - assertThat(map.get("a.b"), equalTo((Object) "c")); + assertThat(map.get("a")).isEqualTo("b"); + assertThat(map.get("c")).isEqualTo("d"); + assertThat(map.get("a.b")).isEqualTo("c"); } @Test @@ -165,7 +160,7 @@ public abstract class AbstractJpaAutoConfigurationTests { LocalContainerEntityManagerFactoryBean factoryBean = this.context .getBean(LocalContainerEntityManagerFactoryBean.class); Map map = factoryBean.getJpaPropertyMap(); - assertThat(map.get("configured"), equalTo((Object) "manually")); + assertThat(map.get("configured")).isEqualTo("manually"); } @Test @@ -177,7 +172,7 @@ public abstract class AbstractJpaAutoConfigurationTests { EntityManagerFactory factoryBean = this.context .getBean(EntityManagerFactory.class); Map map = factoryBean.getProperties(); - assertThat(map.get("configured"), equalTo((Object) "manually")); + assertThat(map.get("configured")).isEqualTo("manually"); } @Test @@ -186,7 +181,7 @@ public abstract class AbstractJpaAutoConfigurationTests { this.context.refresh(); PlatformTransactionManager txManager = this.context .getBean(PlatformTransactionManager.class); - assertThat(txManager, instanceOf(CustomJpaTransactionManager.class)); + assertThat(txManager).isInstanceOf(CustomJpaTransactionManager.class); } @Test @@ -198,8 +193,8 @@ public abstract class AbstractJpaAutoConfigurationTests { Field field = LocalContainerEntityManagerFactoryBean.class .getDeclaredField("persistenceUnitManager"); field.setAccessible(true); - assertThat(field.get(entityManagerFactoryBean), - equalTo((Object) this.context.getBean(PersistenceUnitManager.class))); + assertThat(field.get(entityManagerFactoryBean)) + .isEqualTo(this.context.getBean(PersistenceUnitManager.class)); } protected void setupTestConfiguration() { diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/orm/jpa/CustomHibernateJpaAutoConfigurationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/orm/jpa/CustomHibernateJpaAutoConfigurationTests.java index b0f86eb9e0..1828829559 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/orm/jpa/CustomHibernateJpaAutoConfigurationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/orm/jpa/CustomHibernateJpaAutoConfigurationTests.java @@ -32,9 +32,7 @@ import org.springframework.boot.test.EnvironmentTestUtils; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.context.annotation.Configuration; -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 HibernateJpaAutoConfiguration}. @@ -68,7 +66,7 @@ public class CustomHibernateJpaAutoConfigurationTests { String actual = bean.getHibernateProperties(dataSource) .get("hibernate.hbm2ddl.auto"); // Default is generic and safe - assertThat(actual, nullValue()); + assertThat(actual).isNull(); } @Test @@ -84,7 +82,7 @@ public class CustomHibernateJpaAutoConfigurationTests { DataSource dataSource = this.context.getBean(DataSource.class); String actual = bean.getHibernateProperties(dataSource) .get("hibernate.hbm2ddl.auto"); - assertThat(actual, equalTo("create-drop")); + assertThat(actual).isEqualTo("create-drop"); } @Test @@ -100,7 +98,7 @@ public class CustomHibernateJpaAutoConfigurationTests { JpaProperties bean = this.context.getBean(JpaProperties.class); DataSource dataSource = this.context.getBean(DataSource.class); Map hibernateProperties = bean.getHibernateProperties(dataSource); - assertThat(hibernateProperties.get("hibernate.ejb.naming_strategy"), nullValue()); + assertThat(hibernateProperties.get("hibernate.ejb.naming_strategy")).isNull(); } @Configuration diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaAutoConfigurationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaAutoConfigurationTests.java index 7d4fee64f5..10944fe63d 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaAutoConfigurationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaAutoConfigurationTests.java @@ -38,11 +38,7 @@ import org.springframework.boot.test.EnvironmentTestUtils; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.instanceOf; -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; /** * Tests for {@link HibernateJpaAutoConfiguration}. @@ -67,9 +63,8 @@ public class HibernateJpaAutoConfigurationTests "spring.datasource.schema:classpath:/ddl.sql"); setupTestConfiguration(); this.context.refresh(); - assertEquals(Integer.valueOf(1), - new JdbcTemplate(this.context.getBean(DataSource.class)) - .queryForObject("SELECT COUNT(*) from CITY", Integer.class)); + assertThat(new JdbcTemplate(this.context.getBean(DataSource.class)) + .queryForObject("SELECT COUNT(*) from CITY", Integer.class)).isEqualTo(1); } // This can't succeed because the data SQL is executed immediately after the schema @@ -80,9 +75,8 @@ public class HibernateJpaAutoConfigurationTests "spring.datasource.data:classpath:/city.sql"); setupTestConfiguration(); this.context.refresh(); - assertEquals(Integer.valueOf(1), - new JdbcTemplate(this.context.getBean(DataSource.class)) - .queryForObject("SELECT COUNT(*) from CITY", Integer.class)); + assertThat(new JdbcTemplate(this.context.getBean(DataSource.class)) + .queryForObject("SELECT COUNT(*) from CITY", Integer.class)).isEqualTo(1); } @Test @@ -96,7 +90,7 @@ public class HibernateJpaAutoConfigurationTests .getBean(LocalContainerEntityManagerFactoryBean.class); String actual = (String) bean.getJpaPropertyMap() .get("hibernate.ejb.naming_strategy"); - assertThat(actual, equalTo("org.hibernate.cfg.EJB3NamingStrategy")); + assertThat(actual).isEqualTo("org.hibernate.cfg.EJB3NamingStrategy"); } @Test @@ -112,7 +106,7 @@ public class HibernateJpaAutoConfigurationTests .get("hibernate.ejb.naming_strategy"); // You can't override this one from spring.jpa.properties because it has an // opinionated default - assertThat(actual, not(equalTo("org.hibernate.cfg.EJB3NamingStrategy"))); + assertThat(actual).isNotEqualTo("org.hibernate.cfg.EJB3NamingStrategy"); } @Test @@ -145,8 +139,8 @@ public class HibernateJpaAutoConfigurationTests Map jpaPropertyMap = this.context .getBean(LocalContainerEntityManagerFactoryBean.class) .getJpaPropertyMap(); - assertThat(jpaPropertyMap.get("hibernate.transaction.jta.platform"), - instanceOf(SpringJtaPlatform.class)); + assertThat(jpaPropertyMap.get("hibernate.transaction.jta.platform")) + .isInstanceOf(SpringJtaPlatform.class); } @Test @@ -160,8 +154,8 @@ public class HibernateJpaAutoConfigurationTests Map jpaPropertyMap = this.context .getBean(LocalContainerEntityManagerFactoryBean.class) .getJpaPropertyMap(); - assertThat((String) jpaPropertyMap.get("hibernate.transaction.jta.platform"), - equalTo(TestJtaPlatform.class.getName())); + assertThat((String) jpaPropertyMap.get("hibernate.transaction.jta.platform")) + .isEqualTo(TestJtaPlatform.class.getName()); } public static class TestJtaPlatform implements JtaPlatform { diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/reactor/ReactorAutoConfigurationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/reactor/ReactorAutoConfigurationTests.java index f1e4df7514..a1aa0ee75b 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/reactor/ReactorAutoConfigurationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/reactor/ReactorAutoConfigurationTests.java @@ -26,8 +26,7 @@ import org.springframework.context.annotation.AnnotationConfigApplicationContext import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; -import static org.hamcrest.Matchers.instanceOf; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link ReactorAutoConfiguration}. @@ -44,7 +43,7 @@ public class ReactorAutoConfigurationTests { this.context.register(ReactorAutoConfiguration.class); this.context.refresh(); EventBus eventBus = this.context.getBean(EventBus.class); - assertThat(eventBus.getDispatcher(), instanceOf(RingBufferDispatcher.class)); + assertThat(eventBus.getDispatcher()).isInstanceOf(RingBufferDispatcher.class); this.context.close(); } @@ -53,7 +52,7 @@ public class ReactorAutoConfigurationTests { this.context.register(TestConfiguration.class, ReactorAutoConfiguration.class); this.context.refresh(); EventBus eventBus = this.context.getBean(EventBus.class); - assertThat(eventBus.getDispatcher(), instanceOf(MpscDispatcher.class)); + assertThat(eventBus.getDispatcher()).isInstanceOf(MpscDispatcher.class); this.context.close(); } diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/SecurityAutoConfigurationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/SecurityAutoConfigurationTests.java index 38d62ef7d0..7559c20a50 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/SecurityAutoConfigurationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/SecurityAutoConfigurationTests.java @@ -61,13 +61,7 @@ import org.springframework.security.web.FilterChainProxy; import org.springframework.test.util.ReflectionTestUtils; import org.springframework.web.context.support.AnnotationConfigWebApplicationContext; -import static org.hamcrest.Matchers.is; -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.assertThat; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.fail; /** @@ -96,10 +90,10 @@ public class SecurityAutoConfigurationTests { ServerPropertiesAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); this.context.refresh(); - assertNotNull(this.context.getBean(AuthenticationManagerBuilder.class)); + assertThat(this.context.getBean(AuthenticationManagerBuilder.class)).isNotNull(); // 4 for static resources and one for the rest - assertEquals(5, - this.context.getBean(FilterChainProxy.class).getFilterChains().size()); + assertThat(this.context.getBean(FilterChainProxy.class).getFilterChains()) + .hasSize(5); } @Test @@ -111,9 +105,9 @@ public class SecurityAutoConfigurationTests { ServerPropertiesAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); this.context.refresh(); - assertEquals(FilterRegistrationBean.REQUEST_WRAPPER_FILTER_MAX_ORDER - 100, - this.context.getBean("securityFilterChainRegistration", - DelegatingFilterProxyRegistrationBean.class).getOrder()); + assertThat(this.context.getBean("securityFilterChainRegistration", + DelegatingFilterProxyRegistrationBean.class).getOrder()).isEqualTo( + FilterRegistrationBean.REQUEST_WRAPPER_FILTER_MAX_ORDER - 100); } @Test @@ -125,7 +119,7 @@ public class SecurityAutoConfigurationTests { PropertyPlaceholderAutoConfiguration.class); try { context.refresh(); - assertFalse(context.containsBean("securityFilterChainRegistration")); + assertThat(context.containsBean("securityFilterChainRegistration")).isFalse(); } finally { context.close(); @@ -141,9 +135,9 @@ public class SecurityAutoConfigurationTests { ServerPropertiesAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); this.context.refresh(); - assertEquals(FilterRegistrationBean.REQUEST_WRAPPER_FILTER_MAX_ORDER - 100, - this.context.getBean("securityFilterChainRegistration", - DelegatingFilterProxyRegistrationBean.class).getOrder()); + assertThat(this.context.getBean("securityFilterChainRegistration", + DelegatingFilterProxyRegistrationBean.class).getOrder()).isEqualTo( + FilterRegistrationBean.REQUEST_WRAPPER_FILTER_MAX_ORDER - 100); } @Test @@ -156,8 +150,8 @@ public class SecurityAutoConfigurationTests { ServerPropertiesAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); this.context.refresh(); - assertEquals(12345, this.context.getBean("securityFilterChainRegistration", - DelegatingFilterProxyRegistrationBean.class).getOrder()); + assertThat(this.context.getBean("securityFilterChainRegistration", + DelegatingFilterProxyRegistrationBean.class).getOrder()).isEqualTo(12345); } @Test @@ -170,8 +164,8 @@ public class SecurityAutoConfigurationTests { EnvironmentTestUtils.addEnvironment(this.context, "security.ignored:none"); this.context.refresh(); // Just the application endpoints now - assertEquals(1, - this.context.getBean(FilterChainProxy.class).getFilterChains().size()); + assertThat(this.context.getBean(FilterChainProxy.class).getFilterChains()) + .hasSize(1); } @Test @@ -184,7 +178,8 @@ public class SecurityAutoConfigurationTests { EnvironmentTestUtils.addEnvironment(this.context, "security.basic.enabled:false"); this.context.refresh(); // Ignores and the "matches-none" filter only - assertEquals(1, this.context.getBeanNamesForType(FilterChainProxy.class).length); + assertThat(this.context.getBeanNamesForType(FilterChainProxy.class).length) + .isEqualTo(1); } @Test @@ -195,7 +190,7 @@ public class SecurityAutoConfigurationTests { ServerPropertiesAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); this.context.refresh(); - assertNotNull(this.context.getBean(AuthenticationManager.class)); + assertThat(this.context.getBean(AuthenticationManager.class)).isNotNull(); } @Test @@ -215,8 +210,8 @@ public class SecurityAutoConfigurationTests { catch (BadCredentialsException e) { // expected } - assertTrue("Wrong event type: " + listener.event, - listener.event instanceof AuthenticationFailureBadCredentialsEvent); + assertThat(listener.event) + .isInstanceOf(AuthenticationFailureBadCredentialsEvent.class); } @Test @@ -227,10 +222,9 @@ public class SecurityAutoConfigurationTests { SecurityAutoConfiguration.class, ServerPropertiesAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); this.context.refresh(); - assertEquals( - this.context.getBean( - TestAuthenticationConfiguration.class).authenticationManager, - this.context.getBean(AuthenticationManager.class)); + assertThat(this.context.getBean(AuthenticationManager.class)) + .isEqualTo(this.context.getBean( + TestAuthenticationConfiguration.class).authenticationManager); } @Test @@ -242,8 +236,8 @@ public class SecurityAutoConfigurationTests { SecurityAutoConfiguration.class, ServerPropertiesAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); this.context.refresh(); - assertNotNull(this.context.getBean(UserDetailsSecurityCustomizer.class) - .getUserDetails().loadUserByUsername("user")); + assertThat(this.context.getBean(UserDetailsSecurityCustomizer.class) + .getUserDetails().loadUserByUsername("user")).isNotNull(); } @Test @@ -256,10 +250,9 @@ public class SecurityAutoConfigurationTests { ServerPropertiesAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); this.context.refresh(); - assertEquals( - this.context.getBean( - TestAuthenticationConfiguration.class).authenticationManager, - this.context.getBean(AuthenticationManager.class)); + assertThat(this.context.getBean(AuthenticationManager.class)) + .isEqualTo(this.context.getBean( + TestAuthenticationConfiguration.class).authenticationManager); } @Test @@ -275,8 +268,8 @@ public class SecurityAutoConfigurationTests { UsernamePasswordAuthenticationToken user = new UsernamePasswordAuthenticationToken( "foo", "bar", AuthorityUtils.commaSeparatedStringToAuthorityList("ROLE_USER")); - assertNotNull( - this.context.getBean(AuthenticationManager.class).authenticate(user)); + assertThat(this.context.getBean(AuthenticationManager.class).authenticate(user)) + .isNotNull(); pingAuthenticationListener(); } @@ -293,8 +286,8 @@ public class SecurityAutoConfigurationTests { UsernamePasswordAuthenticationToken user = new UsernamePasswordAuthenticationToken( "foo", "bar", AuthorityUtils.commaSeparatedStringToAuthorityList("ROLE_USER")); - assertNotNull( - this.context.getBean(AuthenticationManager.class).authenticate(user)); + assertThat(this.context.getBean(AuthenticationManager.class).authenticate(user)) + .isNotNull(); } @Test @@ -312,7 +305,7 @@ public class SecurityAutoConfigurationTests { // This can fail if security @Conditionals force early instantiation of the // HibernateJpaAutoConfiguration (e.g. the EntityManagerFactory is not found) this.context.refresh(); - assertNotNull(this.context.getBean(JpaTransactionManager.class)); + assertThat(this.context.getBean(JpaTransactionManager.class)).isNotNull(); } @Test @@ -329,7 +322,7 @@ public class SecurityAutoConfigurationTests { UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken( security.getUser().getName(), security.getUser().getPassword()); - assertNotNull(manager.authenticate(token)); + assertThat(manager.authenticate(token)).isNotNull(); } @Test @@ -356,7 +349,7 @@ public class SecurityAutoConfigurationTests { } token = new UsernamePasswordAuthenticationToken("foo", "bar"); - assertNotNull(manager.authenticate(token)); + assertThat(manager.authenticate(token)).isNotNull(); } @Test @@ -366,7 +359,8 @@ public class SecurityAutoConfigurationTests { this.context.register(AuthenticationManagerCustomizer.class, SecurityAutoConfiguration.class, ServerPropertiesAutoConfiguration.class); this.context.refresh(); - assertNotNull(this.context.getBean(SecurityEvaluationContextExtension.class)); + assertThat(this.context.getBean(SecurityEvaluationContextExtension.class)) + .isNotNull(); } @Test @@ -384,7 +378,7 @@ public class SecurityAutoConfigurationTests { @SuppressWarnings("unchecked") EnumSet dispatcherTypes = (EnumSet) ReflectionTestUtils .getField(bean, "dispatcherTypes"); - assertThat(dispatcherTypes, is(nullValue())); + assertThat(dispatcherTypes).isNull(); } @Test @@ -404,8 +398,8 @@ public class SecurityAutoConfigurationTests { @SuppressWarnings("unchecked") EnumSet dispatcherTypes = (EnumSet) ReflectionTestUtils .getField(bean, "dispatcherTypes"); - assertThat(dispatcherTypes, - is(EnumSet.of(DispatcherType.INCLUDE, DispatcherType.ERROR))); + assertThat(dispatcherTypes).containsOnly(DispatcherType.INCLUDE, + DispatcherType.ERROR); } private static final class AuthenticationListener diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/SecurityPropertiesTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/SecurityPropertiesTests.java index ea57ccc357..f4f5c335a6 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/SecurityPropertiesTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/SecurityPropertiesTests.java @@ -27,9 +27,7 @@ import org.springframework.beans.MutablePropertyValues; import org.springframework.boot.bind.RelaxedDataBinder; import org.springframework.core.convert.support.DefaultConversionService; -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 SecurityProperties}. @@ -52,32 +50,32 @@ public class SecurityPropertiesTests { public void testBindingIgnoredSingleValued() { this.binder.bind(new MutablePropertyValues( Collections.singletonMap("security.ignored", "/css/**"))); - assertFalse(this.binder.getBindingResult().hasErrors()); - assertEquals(1, this.security.getIgnored().size()); + assertThat(this.binder.getBindingResult().hasErrors()).isFalse(); + assertThat(this.security.getIgnored()).hasSize(1); } @Test public void testBindingIgnoredEmpty() { this.binder.bind(new MutablePropertyValues( Collections.singletonMap("security.ignored", ""))); - assertFalse(this.binder.getBindingResult().hasErrors()); - assertEquals(0, this.security.getIgnored().size()); + assertThat(this.binder.getBindingResult().hasErrors()).isFalse(); + assertThat(this.security.getIgnored()).isEmpty(); } @Test public void testBindingIgnoredDisable() { this.binder.bind(new MutablePropertyValues( Collections.singletonMap("security.ignored", "none"))); - assertFalse(this.binder.getBindingResult().hasErrors()); - assertEquals(1, this.security.getIgnored().size()); + assertThat(this.binder.getBindingResult().hasErrors()).isFalse(); + assertThat(this.security.getIgnored()).hasSize(1); } @Test public void testBindingIgnoredMultiValued() { this.binder.bind(new MutablePropertyValues( Collections.singletonMap("security.ignored", "/css/**,/images/**"))); - assertFalse(this.binder.getBindingResult().hasErrors()); - assertEquals(2, this.security.getIgnored().size()); + assertThat(this.binder.getBindingResult().hasErrors()).isFalse(); + assertThat(this.security.getIgnored()).hasSize(2); } @Test @@ -86,41 +84,42 @@ public class SecurityPropertiesTests { map.put("security.ignored[0]", "/css/**"); map.put("security.ignored[1]", "/foo/**"); this.binder.bind(new MutablePropertyValues(map)); - assertFalse(this.binder.getBindingResult().hasErrors()); - assertEquals(2, this.security.getIgnored().size()); - assertTrue(this.security.getIgnored().contains("/foo/**")); + assertThat(this.binder.getBindingResult().hasErrors()).isFalse(); + assertThat(this.security.getIgnored()).hasSize(2); + assertThat(this.security.getIgnored().contains("/foo/**")).isTrue(); } @Test public void testDefaultPasswordAutogeneratedIfUnresolvedPlaceholder() { this.binder.bind(new MutablePropertyValues( Collections.singletonMap("security.user.password", "${ADMIN_PASSWORD}"))); - assertFalse(this.binder.getBindingResult().hasErrors()); - assertTrue(this.security.getUser().isDefaultPassword()); + assertThat(this.binder.getBindingResult().hasErrors()).isFalse(); + assertThat(this.security.getUser().isDefaultPassword()).isTrue(); } @Test public void testDefaultPasswordAutogeneratedIfEmpty() { this.binder.bind(new MutablePropertyValues( Collections.singletonMap("security.user.password", ""))); - assertFalse(this.binder.getBindingResult().hasErrors()); - assertTrue(this.security.getUser().isDefaultPassword()); + assertThat(this.binder.getBindingResult().hasErrors()).isFalse(); + assertThat(this.security.getUser().isDefaultPassword()).isTrue(); } @Test public void testRoles() { this.binder.bind(new MutablePropertyValues( Collections.singletonMap("security.user.role", "USER,ADMIN"))); - assertFalse(this.binder.getBindingResult().hasErrors()); - assertEquals("[USER, ADMIN]", this.security.getUser().getRole().toString()); + assertThat(this.binder.getBindingResult().hasErrors()).isFalse(); + assertThat(this.security.getUser().getRole().toString()) + .isEqualTo("[USER, ADMIN]"); } @Test public void testRole() { this.binder.bind(new MutablePropertyValues( Collections.singletonMap("security.user.role", "ADMIN"))); - assertFalse(this.binder.getBindingResult().hasErrors()); - assertEquals("[ADMIN]", this.security.getUser().getRole().toString()); + assertThat(this.binder.getBindingResult().hasErrors()).isFalse(); + assertThat(this.security.getUser().getRole().toString()).isEqualTo("[ADMIN]"); } } diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/SpringBootWebSecurityConfigurationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/SpringBootWebSecurityConfigurationTests.java index 4786521f8a..b5f706dc63 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/SpringBootWebSecurityConfigurationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/SpringBootWebSecurityConfigurationTests.java @@ -21,6 +21,7 @@ import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; +import java.util.List; import javax.servlet.Filter; @@ -61,11 +62,9 @@ import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; import org.springframework.web.context.WebApplicationContext; +import static org.assertj.core.api.Assertions.assertThat; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.notNullValue; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; /** * Tests for {@link SpringBootWebSecurityConfiguration}. @@ -87,17 +86,19 @@ public class SpringBootWebSecurityConfigurationTests { @Test public void testDefaultIgnores() { - assertTrue(SpringBootWebSecurityConfiguration.getIgnored(new SecurityProperties()) - .contains("/css/**")); + List ignored = SpringBootWebSecurityConfiguration + .getIgnored(new SecurityProperties()); + assertThat(ignored).contains("/css/**"); } @Test public void testWebConfigurationOverrideGlobalAuthentication() throws Exception { this.context = SpringApplication.run(TestWebConfiguration.class, "--server.port=0"); - assertNotNull(this.context.getBean(AuthenticationManagerBuilder.class)); - assertNotNull(this.context.getBean(AuthenticationManager.class) - .authenticate(new UsernamePasswordAuthenticationToken("dave", "secret"))); + assertThat(this.context.getBean(AuthenticationManagerBuilder.class)).isNotNull(); + assertThat(this.context.getBean(AuthenticationManager.class) + .authenticate(new UsernamePasswordAuthenticationToken("dave", "secret"))) + .isNotNull(); } @Test @@ -165,9 +166,10 @@ public class SpringBootWebSecurityConfigurationTests { public void testWebConfigurationInjectGlobalAuthentication() throws Exception { this.context = SpringApplication.run(TestInjectWebConfiguration.class, "--server.port=0"); - assertNotNull(this.context.getBean(AuthenticationManagerBuilder.class)); - assertNotNull(this.context.getBean(AuthenticationManager.class) - .authenticate(new UsernamePasswordAuthenticationToken("dave", "secret"))); + assertThat(this.context.getBean(AuthenticationManagerBuilder.class)).isNotNull(); + assertThat(this.context.getBean(AuthenticationManager.class) + .authenticate(new UsernamePasswordAuthenticationToken("dave", "secret"))) + .isNotNull(); } // gh-3447 @@ -184,14 +186,14 @@ public class SpringBootWebSecurityConfigurationTests { ResponseEntity result = rest .postForEntity("http://localhost:" + port + "/", form, Object.class); - assertEquals(HttpStatus.FORBIDDEN, result.getStatusCode()); + assertThat(result.getStatusCode()).isEqualTo(HttpStatus.FORBIDDEN); // override method with GET form = new LinkedMultiValueMap(); form.add("_method", "GET"); result = rest.postForEntity("http://localhost:" + port + "/", form, Object.class); - assertEquals(HttpStatus.NOT_FOUND, result.getStatusCode()); + assertThat(result.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND); } @Test @@ -306,4 +308,5 @@ public class SpringBootWebSecurityConfigurationTests { } } + } diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/oauth2/OAuth2AutoConfigurationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/oauth2/OAuth2AutoConfigurationTests.java index c90df3a789..ef28ea2c17 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/oauth2/OAuth2AutoConfigurationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/oauth2/OAuth2AutoConfigurationTests.java @@ -92,9 +92,7 @@ import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.client.RestTemplate; -import static org.hamcrest.CoreMatchers.equalTo; -import static org.hamcrest.Matchers.is; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; /** * Verify Spring Security OAuth2 auto-configuration secures end points properly, accepts @@ -130,11 +128,11 @@ public class OAuth2AutoConfigurationTests { .getBean(ClientDetailsService.class); ClientDetails clientDetails = clientDetailsService .loadClientByClientId(config.getClientId()); - assertThat(AopUtils.isJdkDynamicProxy(clientDetailsService), equalTo(true)); - assertThat(AopUtils.getTargetClass(clientDetailsService).getName(), - is(equalTo(InMemoryClientDetailsService.class.getName()))); - assertThat(handler instanceof ApprovalStoreUserApprovalHandler, equalTo(true)); - assertThat(clientDetails, equalTo(config)); + assertThat(AopUtils.isJdkDynamicProxy(clientDetailsService)).isTrue(); + assertThat(AopUtils.getTargetClass(clientDetailsService).getName()) + .isEqualTo(InMemoryClientDetailsService.class.getName()); + assertThat(handler).isInstanceOf(ApprovalStoreUserApprovalHandler.class); + assertThat(clientDetails).isEqualTo(config); verifyAuthentication(config); } @@ -151,13 +149,13 @@ public class OAuth2AutoConfigurationTests { MinimalSecureWebApplication.class); this.context.refresh(); ClientDetails config = this.context.getBean(ClientDetails.class); - assertThat(config.getClientId(), equalTo("myclientid")); - assertThat(config.getClientSecret(), equalTo("mysecret")); - assertThat(config.isAutoApprove("read"), equalTo(true)); - assertThat(config.isAutoApprove("write"), equalTo(true)); - assertThat(config.isAutoApprove("foo"), equalTo(false)); - assertThat(config.getAccessTokenValiditySeconds(), equalTo(40)); - assertThat(config.getRefreshTokenValiditySeconds(), equalTo(80)); + assertThat(config.getClientId()).isEqualTo("myclientid"); + assertThat(config.getClientSecret()).isEqualTo("mysecret"); + assertThat(config.isAutoApprove("read")).isTrue(); + assertThat(config.isAutoApprove("write")).isTrue(); + assertThat(config.isAutoApprove("foo")).isFalse(); + assertThat(config.getAccessTokenValiditySeconds()).isEqualTo(40); + assertThat(config.getRefreshTokenValiditySeconds()).isEqualTo(80); verifyAuthentication(config); } @@ -167,8 +165,8 @@ public class OAuth2AutoConfigurationTests { this.context.register(AuthorizationServerConfiguration.class, MinimalSecureWebApplication.class); this.context.refresh(); - assertThat(countBeans(RESOURCE_SERVER_CONFIG), equalTo(0)); - assertThat(countBeans(AUTHORIZATION_SERVER_CONFIG), equalTo(1)); + assertThat(countBeans(RESOURCE_SERVER_CONFIG)).isEqualTo(0); + assertThat(countBeans(AUTHORIZATION_SERVER_CONFIG)).isEqualTo(1); } @Test @@ -177,10 +175,10 @@ public class OAuth2AutoConfigurationTests { this.context.register(ClientConfiguration.class, MinimalSecureWebApplication.class); this.context.refresh(); - assertThat(countBeans(RESOURCE_SERVER_CONFIG), equalTo(0)); - assertThat(countBeans(AUTHORIZATION_SERVER_CONFIG), equalTo(0)); + assertThat(countBeans(RESOURCE_SERVER_CONFIG)).isEqualTo(0); + assertThat(countBeans(AUTHORIZATION_SERVER_CONFIG)).isEqualTo(0); // Scoped target and proxy: - assertThat(countBeans(OAuth2ClientContext.class), equalTo(2)); + assertThat(countBeans(OAuth2ClientContext.class)).isEqualTo(2); } @Test @@ -191,10 +189,10 @@ public class OAuth2AutoConfigurationTests { EnvironmentTestUtils.addEnvironment(this.context, "security.oauth2.resource.jwt.keyValue:DEADBEEF"); this.context.refresh(); - assertThat(countBeans(RESOURCE_SERVER_CONFIG), equalTo(1)); - assertThat(countBeans(AUTHORIZATION_SERVER_CONFIG), equalTo(0)); - assertThat(countBeans(UserApprovalHandler.class), equalTo(0)); - assertThat(countBeans(DefaultTokenServices.class), equalTo(1)); + assertThat(countBeans(RESOURCE_SERVER_CONFIG)).isEqualTo(1); + assertThat(countBeans(AUTHORIZATION_SERVER_CONFIG)).isEqualTo(0); + assertThat(countBeans(UserApprovalHandler.class)).isEqualTo(0); + assertThat(countBeans(DefaultTokenServices.class)).isEqualTo(1); } @Test @@ -204,9 +202,9 @@ public class OAuth2AutoConfigurationTests { CustomResourceServer.class, MinimalSecureWebApplication.class); this.context.refresh(); ClientDetails config = this.context.getBean(ClientDetails.class); - assertThat(countBeans(AUTHORIZATION_SERVER_CONFIG), equalTo(1)); - assertThat(countBeans(CustomResourceServer.class), equalTo(1)); - assertThat(countBeans(RESOURCE_SERVER_CONFIG), equalTo(1)); + assertThat(countBeans(AUTHORIZATION_SERVER_CONFIG)).isEqualTo(1); + assertThat(countBeans(CustomResourceServer.class)).isEqualTo(1); + assertThat(countBeans(RESOURCE_SERVER_CONFIG)).isEqualTo(1); verifyAuthentication(config); } @@ -225,8 +223,8 @@ public class OAuth2AutoConfigurationTests { config.setAuthorizedGrantTypes(Arrays.asList("password")); config.setAuthorities(AuthorityUtils.commaSeparatedStringToAuthorityList("USER")); config.setScope(Arrays.asList("read")); - assertThat(countBeans(AUTHORIZATION_SERVER_CONFIG), equalTo(0)); - assertThat(countBeans(RESOURCE_SERVER_CONFIG), equalTo(1)); + assertThat(countBeans(AUTHORIZATION_SERVER_CONFIG)).isEqualTo(0); + assertThat(countBeans(RESOURCE_SERVER_CONFIG)).isEqualTo(1); verifyAuthentication(config); } @@ -242,9 +240,9 @@ public class OAuth2AutoConfigurationTests { .getBean(DelegatingMethodSecurityMetadataSource.class); List sources = source .getMethodSecurityMetadataSources(); - assertThat(sources.size(), equalTo(1)); - assertThat(sources.get(0).getClass().getName(), - equalTo(PrePostAnnotationSecurityMetadataSource.class.getName())); + assertThat(sources.size()).isEqualTo(1); + assertThat(sources.get(0).getClass().getName()) + .isEqualTo(PrePostAnnotationSecurityMetadataSource.class.getName()); verifyAuthentication(config); } @@ -260,9 +258,9 @@ public class OAuth2AutoConfigurationTests { .getBean(DelegatingMethodSecurityMetadataSource.class); List sources = source .getMethodSecurityMetadataSources(); - assertThat(sources.size(), equalTo(1)); - assertThat(sources.get(0).getClass().getName(), - equalTo(SecuredAnnotationSecurityMetadataSource.class.getName())); + assertThat(sources.size()).isEqualTo(1); + assertThat(sources.get(0).getClass().getName()) + .isEqualTo(SecuredAnnotationSecurityMetadataSource.class.getName()); verifyAuthentication(config, HttpStatus.OK); } @@ -278,9 +276,9 @@ public class OAuth2AutoConfigurationTests { .getBean(DelegatingMethodSecurityMetadataSource.class); List sources = source .getMethodSecurityMetadataSources(); - assertThat(sources.size(), equalTo(1)); - assertThat(sources.get(0).getClass().getName(), - equalTo(Jsr250MethodSecurityMetadataSource.class.getName())); + assertThat(sources.size()).isEqualTo(1); + assertThat(sources.get(0).getClass().getName()) + .isEqualTo(Jsr250MethodSecurityMetadataSource.class.getName()); verifyAuthentication(config, HttpStatus.OK); } @@ -294,9 +292,9 @@ public class OAuth2AutoConfigurationTests { .getBean(DelegatingMethodSecurityMetadataSource.class); List sources = source .getMethodSecurityMetadataSources(); - assertThat(sources.size(), equalTo(1)); - assertThat(sources.get(0).getClass().getName(), - equalTo(PrePostAnnotationSecurityMetadataSource.class.getName())); + assertThat(sources.size()).isEqualTo(1); + assertThat(sources.get(0).getClass().getName()) + .isEqualTo(PrePostAnnotationSecurityMetadataSource.class.getName()); } /** @@ -323,19 +321,19 @@ public class OAuth2AutoConfigurationTests { String authorizationToken = tokenResponse.findValue("access_token").asText(); String tokenType = tokenResponse.findValue("token_type").asText(); String scope = tokenResponse.findValues("scope").get(0).toString(); - assertThat(tokenType, equalTo("bearer")); - assertThat(scope, equalTo("\"read\"")); + assertThat(tokenType).isEqualTo("bearer"); + assertThat(scope).isEqualTo("\"read\""); // Now we should be able to see that endpoint. headers.set("Authorization", "BEARER " + authorizationToken); ResponseEntity securedResponse = rest .exchange(new RequestEntity(headers, HttpMethod.GET, URI.create(baseUrl + "/securedFind")), String.class); - assertThat(securedResponse.getStatusCode(), equalTo(HttpStatus.OK)); - assertThat(securedResponse.getBody(), equalTo( - "You reached an endpoint " + "secured by Spring Security OAuth2")); + assertThat(securedResponse.getStatusCode()).isEqualTo(HttpStatus.OK); + assertThat(securedResponse.getBody()).isEqualTo( + "You reached an endpoint " + "secured by Spring Security OAuth2"); ResponseEntity entity = rest.exchange(new RequestEntity(headers, HttpMethod.POST, URI.create(baseUrl + "/securedSave")), String.class); - assertThat(entity.getStatusCode(), equalTo(finalStatus)); + assertThat(entity.getStatusCode()).isEqualTo(finalStatus); } private HttpHeaders getHeaders(ClientDetails config) { @@ -359,7 +357,7 @@ public class OAuth2AutoConfigurationTests { URI uri = URI.create(baseUrl + "/secured"); ResponseEntity entity = rest .exchange(new RequestEntity(HttpMethod.GET, uri), String.class); - assertThat(entity.getStatusCode(), equalTo(HttpStatus.UNAUTHORIZED)); + assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED); } private int countBeans(Class type) { diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/oauth2/resource/FixedAuthoritiesExtractorTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/oauth2/resource/FixedAuthoritiesExtractorTests.java index c1272fc2e8..549f7c6047 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/oauth2/resource/FixedAuthoritiesExtractorTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/oauth2/resource/FixedAuthoritiesExtractorTests.java @@ -22,7 +22,7 @@ import java.util.Map; import org.junit.Test; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link FixedAuthoritiesExtractor}. @@ -38,29 +38,29 @@ public class FixedAuthoritiesExtractorTests { @Test public void authorities() { this.map.put("authorities", "ROLE_ADMIN"); - assertEquals("[ROLE_ADMIN]", - this.extractor.extractAuthorities(this.map).toString()); + assertThat(this.extractor.extractAuthorities(this.map).toString()) + .isEqualTo("[ROLE_ADMIN]"); } @Test public void authoritiesCommaSeparated() { this.map.put("authorities", "ROLE_USER,ROLE_ADMIN"); - assertEquals("[ROLE_USER, ROLE_ADMIN]", - this.extractor.extractAuthorities(this.map).toString()); + assertThat(this.extractor.extractAuthorities(this.map).toString()) + .isEqualTo("[ROLE_USER, ROLE_ADMIN]"); } @Test public void authoritiesArray() { this.map.put("authorities", new String[] { "ROLE_USER", "ROLE_ADMIN" }); - assertEquals("[ROLE_USER, ROLE_ADMIN]", - this.extractor.extractAuthorities(this.map).toString()); + assertThat(this.extractor.extractAuthorities(this.map).toString()) + .isEqualTo("[ROLE_USER, ROLE_ADMIN]"); } @Test public void authoritiesList() { this.map.put("authorities", Arrays.asList("ROLE_USER", "ROLE_ADMIN")); - assertEquals("[ROLE_USER, ROLE_ADMIN]", - this.extractor.extractAuthorities(this.map).toString()); + assertThat(this.extractor.extractAuthorities(this.map).toString()) + .isEqualTo("[ROLE_USER, ROLE_ADMIN]"); } } diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/oauth2/resource/ResourceServerPropertiesTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/oauth2/resource/ResourceServerPropertiesTests.java index 6cea398bb4..37be41276b 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/oauth2/resource/ResourceServerPropertiesTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/oauth2/resource/ResourceServerPropertiesTests.java @@ -21,7 +21,7 @@ import java.util.Map; import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.Test; -import static org.junit.Assert.assertNotNull; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link ResourceServerProperties}. @@ -41,14 +41,13 @@ public class ResourceServerPropertiesTests { String json = mapper.writeValueAsString(this.properties); Map value = mapper.readValue(json, Map.class); Map jwt = (Map) value.get("jwt"); - assertNotNull("Wrong json: " + json, jwt.get("keyUri")); + assertThat(jwt.get("keyUri")).isNotNull(); } @Test public void tokenKeyDerived() throws Exception { this.properties.setUserInfoUri("http://example.com/userinfo"); - assertNotNull("Wrong properties: " + this.properties, - this.properties.getJwt().getKeyUri()); + assertThat(this.properties.getJwt().getKeyUri()).isNotNull(); } } diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/oauth2/resource/ResourceServerTokenServicesConfigurationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/oauth2/resource/ResourceServerTokenServicesConfigurationTests.java index a0ca7002dd..080931caf8 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/oauth2/resource/ResourceServerTokenServicesConfigurationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/oauth2/resource/ResourceServerTokenServicesConfigurationTests.java @@ -53,10 +53,8 @@ import org.springframework.security.oauth2.provider.token.DefaultTokenServices; import org.springframework.security.oauth2.provider.token.RemoteTokenServices; import org.springframework.social.connect.ConnectionFactoryLocator; import org.springframework.stereotype.Component; -import org.springframework.test.util.ReflectionTestUtils; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; /** @@ -90,7 +88,7 @@ public class ResourceServerTokenServicesConfigurationTests { this.context = new SpringApplicationBuilder(ResourceConfiguration.class) .web(false).run(); RemoteTokenServices services = this.context.getBean(RemoteTokenServices.class); - assertNotNull(services); + assertThat(services).isNotNull(); } @Test @@ -101,7 +99,7 @@ public class ResourceServerTokenServicesConfigurationTests { this.context = new SpringApplicationBuilder(ResourceConfiguration.class) .environment(this.environment).web(false).run(); RemoteTokenServices services = this.context.getBean(RemoteTokenServices.class); - assertNotNull(services); + assertThat(services).isNotNull(); } @Test @@ -112,7 +110,7 @@ public class ResourceServerTokenServicesConfigurationTests { .environment(this.environment).web(false).run(); UserInfoTokenServices services = this.context .getBean(UserInfoTokenServices.class); - assertNotNull(services); + assertThat(services).isNotNull(); } @Test @@ -123,9 +121,9 @@ public class ResourceServerTokenServicesConfigurationTests { .environment(this.environment).web(false).run(); UserInfoTokenServices services = this.context .getBean(UserInfoTokenServices.class); - assertNotNull(services); - assertEquals(this.context.getBean(AuthoritiesExtractor.class), - ReflectionTestUtils.getField(services, "authoritiesExtractor")); + assertThat(services).isNotNull(); + assertThat(services).extracting("authoritiesExtractor") + .containsExactly(this.context.getBean(AuthoritiesExtractor.class)); } @Test @@ -138,7 +136,7 @@ public class ResourceServerTokenServicesConfigurationTests { .environment(this.environment).web(true).run(); BeanDefinition bean = ((BeanDefinitionRegistry) this.context) .getBeanDefinition("scopedTarget.oauth2ClientContext"); - assertEquals("request", bean.getScope()); + assertThat(bean.getScope()).isEqualTo("request"); } @Test @@ -151,7 +149,7 @@ public class ResourceServerTokenServicesConfigurationTests { .environment(this.environment).web(false).run(); UserInfoTokenServices services = this.context .getBean(UserInfoTokenServices.class); - assertNotNull(services); + assertThat(services).isNotNull(); } @Test @@ -164,7 +162,7 @@ public class ResourceServerTokenServicesConfigurationTests { Customizer.class).environment(this.environment).web(false).run(); UserInfoTokenServices services = this.context .getBean(UserInfoTokenServices.class); - assertNotNull(services); + assertThat(services).isNotNull(); } @Test @@ -174,7 +172,7 @@ public class ResourceServerTokenServicesConfigurationTests { this.context = new SpringApplicationBuilder(ResourceConfiguration.class) .environment(this.environment).web(false).run(); DefaultTokenServices services = this.context.getBean(DefaultTokenServices.class); - assertNotNull(services); + assertThat(services).isNotNull(); } @Test @@ -184,7 +182,7 @@ public class ResourceServerTokenServicesConfigurationTests { this.context = new SpringApplicationBuilder(ResourceConfiguration.class) .environment(this.environment).web(false).run(); DefaultTokenServices services = this.context.getBean(DefaultTokenServices.class); - assertNotNull(services); + assertThat(services).isNotNull(); } @Test @@ -197,10 +195,10 @@ public class ResourceServerTokenServicesConfigurationTests { .environment(this.environment).web(true).run(); ConnectionFactoryLocator connectionFactory = this.context .getBean(ConnectionFactoryLocator.class); - assertNotNull(connectionFactory); + assertThat(connectionFactory).isNotNull(); SpringSocialTokenServices services = this.context .getBean(SpringSocialTokenServices.class); - assertNotNull(services); + assertThat(services).isNotNull(); } @Configuration diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/oauth2/resource/UserInfoTokenServicesRefreshTokenTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/oauth2/resource/UserInfoTokenServicesRefreshTokenTests.java index 6784734fef..3c9fc539eb 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/oauth2/resource/UserInfoTokenServicesRefreshTokenTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/oauth2/resource/UserInfoTokenServicesRefreshTokenTests.java @@ -53,7 +53,7 @@ import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestController; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link UserInfoTokenServices}. @@ -84,7 +84,7 @@ public class UserInfoTokenServicesRefreshTokenTests { @Test public void sunnyDay() { - assertEquals("me", this.services.loadAuthentication("FOO").getName()); + assertThat(this.services.loadAuthentication("FOO").getName()).isEqualTo("me"); } @Test @@ -95,10 +95,11 @@ public class UserInfoTokenServicesRefreshTokenTests { token.setRefreshToken(new DefaultExpiringOAuth2RefreshToken("BAR", new Date(0L))); context.setAccessToken(token); this.services.setRestTemplate(new OAuth2RestTemplate(resource, context)); - assertEquals("me", this.services.loadAuthentication("FOO").getName()); - assertEquals("FOO", context.getAccessToken().getValue()); + assertThat(this.services.loadAuthentication("FOO").getName()).isEqualTo("me"); + assertThat(context.getAccessToken().getValue()).isEqualTo("FOO"); // The refresh token is still intact - assertEquals(token.getRefreshToken(), context.getAccessToken().getRefreshToken()); + assertThat(context.getAccessToken().getRefreshToken()) + .isEqualTo(token.getRefreshToken()); } @Test @@ -107,8 +108,8 @@ public class UserInfoTokenServicesRefreshTokenTests { OAuth2ClientContext context = new DefaultOAuth2ClientContext(); context.setAccessToken(new DefaultOAuth2AccessToken("FOO")); this.services.setRestTemplate(new OAuth2RestTemplate(resource, context)); - assertEquals("me", this.services.loadAuthentication("BAR").getName()); - assertEquals("BAR", context.getAccessToken().getValue()); + assertThat(this.services.loadAuthentication("BAR").getName()).isEqualTo("me"); + assertThat(context.getAccessToken().getValue()).isEqualTo("BAR"); } @Configuration diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/oauth2/resource/UserInfoTokenServicesTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/oauth2/resource/UserInfoTokenServicesTests.java index 64791bf3e3..189643dce5 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/oauth2/resource/UserInfoTokenServicesTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/oauth2/resource/UserInfoTokenServicesTests.java @@ -34,7 +34,7 @@ import org.springframework.security.oauth2.client.resource.UserRedirectRequiredE import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken; import org.springframework.security.oauth2.common.exceptions.InvalidTokenException; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.BDDMockito.given; import static org.mockito.Matchers.any; import static org.mockito.Matchers.eq; @@ -75,7 +75,8 @@ public class UserInfoTokenServicesTests { @Test public void sunnyDay() { this.services.setRestTemplate(this.template); - assertEquals("unknown", this.services.loadAuthentication("FOO").getName()); + assertThat(this.services.loadAuthentication("FOO").getName()) + .isEqualTo("unknown"); } @Test @@ -85,14 +86,16 @@ public class UserInfoTokenServicesTests { .willThrow(new UserRedirectRequiredException("foo:bar", Collections.emptyMap())); this.expected.expect(InvalidTokenException.class); - assertEquals("unknown", this.services.loadAuthentication("FOO").getName()); + assertThat(this.services.loadAuthentication("FOO").getName()) + .isEqualTo("unknown"); } @Test public void userId() { this.map.put("userid", "spencer"); this.services.setRestTemplate(this.template); - assertEquals("spencer", this.services.loadAuthentication("FOO").getName()); + assertThat(this.services.loadAuthentication("FOO").getName()) + .isEqualTo("spencer"); } } diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/sendgrid/SendGridAutoConfigurationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/sendgrid/SendGridAutoConfigurationTests.java index 791b5ee840..3816cbea15 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/sendgrid/SendGridAutoConfigurationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/sendgrid/SendGridAutoConfigurationTests.java @@ -17,8 +17,6 @@ package org.springframework.boot.autoconfigure.sendgrid; import com.sendgrid.SendGrid; -import org.apache.http.conn.routing.HttpRoutePlanner; -import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.conn.DefaultProxyRoutePlanner; import org.junit.After; import org.junit.Test; @@ -28,11 +26,8 @@ import org.springframework.boot.test.EnvironmentTestUtils; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; -import org.springframework.test.util.ReflectionTestUtils; -import static org.hamcrest.Matchers.instanceOf; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link SendGridAutoConfiguration}. @@ -55,16 +50,15 @@ public class SendGridAutoConfigurationTests { public void expectedSendGridBeanCreatedUsername() { loadContext("spring.sendgrid.username:user", "spring.sendgrid.password:secret"); SendGrid sendGrid = this.context.getBean(SendGrid.class); - assertEquals("user", ReflectionTestUtils.getField(sendGrid, "username")); - assertEquals("secret", ReflectionTestUtils.getField(sendGrid, "password")); + assertThat(sendGrid).extracting("username").containsExactly("user"); + assertThat(sendGrid).extracting("password").containsExactly("secret"); } @Test public void expectedSendGridBeanCreatedApiKey() { loadContext("spring.sendgrid.apiKey:SG.SECRET-API-KEY"); SendGrid sendGrid = this.context.getBean(SendGrid.class); - assertEquals("SG.SECRET-API-KEY", - ReflectionTestUtils.getField(sendGrid, "password")); + assertThat(sendGrid).extracting("password").containsExactly("SG.SECRET-API-KEY"); } @Test(expected = NoSuchBeanDefinitionException.class) @@ -78,8 +72,8 @@ public class SendGridAutoConfigurationTests { loadContext(ManualSendGridConfiguration.class, "spring.sendgrid.username:user", "spring.sendgrid.password:secret"); SendGrid sendGrid = this.context.getBean(SendGrid.class); - assertEquals("manual-user", ReflectionTestUtils.getField(sendGrid, "username")); - assertEquals("manual-secret", ReflectionTestUtils.getField(sendGrid, "password")); + assertThat(sendGrid).extracting("username").containsExactly("manual-user"); + assertThat(sendGrid).extracting("password").containsExactly("manual-secret"); } @Test @@ -88,11 +82,8 @@ public class SendGridAutoConfigurationTests { "spring.sendgrid.proxy.host:localhost", "spring.sendgrid.proxy.port:5678"); SendGrid sendGrid = this.context.getBean(SendGrid.class); - CloseableHttpClient client = (CloseableHttpClient) ReflectionTestUtils - .getField(sendGrid, "client"); - HttpRoutePlanner routePlanner = (HttpRoutePlanner) ReflectionTestUtils - .getField(client, "routePlanner"); - assertThat(routePlanner, instanceOf(DefaultProxyRoutePlanner.class)); + assertThat(sendGrid).extracting("client").extracting("routePlanner") + .hasOnlyElementsOfType(DefaultProxyRoutePlanner.class); } private void loadContext(String... environment) { diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/session/SessionAutoConfigurationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/session/SessionAutoConfigurationTests.java index 448fa0aad9..b47ed73b06 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/session/SessionAutoConfigurationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/session/SessionAutoConfigurationTests.java @@ -32,7 +32,7 @@ import org.springframework.context.annotation.AnnotationConfigApplicationContext import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; -import static org.junit.Assert.assertNotNull; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link SessionAutoConfiguration}. @@ -62,7 +62,7 @@ public class SessionAutoConfigurationTests { PropertyPlaceholderAutoConfiguration.class); this.context.refresh(); ServerProperties server = this.context.getBean(ServerProperties.class); - assertNotNull(server); + assertThat(server).isNotNull(); } @Test @@ -77,7 +77,7 @@ public class SessionAutoConfigurationTests { PropertyPlaceholderAutoConfiguration.class); this.context.refresh(); ServerProperties server = this.context.getBean(ServerProperties.class); - assertNotNull(server); + assertThat(server).isNotNull(); } @Configuration diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/social/AbstractSocialAutoConfigurationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/social/AbstractSocialAutoConfigurationTests.java index 1da424fc02..7bfc1693ea 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/social/AbstractSocialAutoConfigurationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/social/AbstractSocialAutoConfigurationTests.java @@ -25,7 +25,7 @@ import org.springframework.social.connect.ConnectionRepository; import org.springframework.social.connect.UsersConnectionRepository; import org.springframework.web.context.support.AnnotationConfigWebApplicationContext; -import static org.junit.Assert.assertNotNull; +import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.fail; /** @@ -49,10 +49,10 @@ public class AbstractSocialAutoConfigurationTests { } protected void assertConnectionFrameworkBeans() { - assertNotNull(this.context.getBean(UsersConnectionRepository.class)); - assertNotNull(this.context.getBean(ConnectionRepository.class)); - assertNotNull(this.context.getBean(ConnectionFactoryLocator.class)); - assertNotNull(this.context.getBean(UserIdSource.class)); + assertThat(this.context.getBean(UsersConnectionRepository.class)).isNotNull(); + assertThat(this.context.getBean(ConnectionRepository.class)).isNotNull(); + assertThat(this.context.getBean(ConnectionFactoryLocator.class)).isNotNull(); + assertThat(this.context.getBean(UserIdSource.class)).isNotNull(); } protected void assertNoConnectionFrameworkBeans() { @@ -64,7 +64,7 @@ public class AbstractSocialAutoConfigurationTests { protected void assertMissingBean(Class beanClass) { try { - assertNotNull(this.context.getBean(beanClass)); + assertThat(this.context.getBean(beanClass)).isNotNull(); fail("Unexpected bean in context of type " + beanClass.getName()); } catch (NoSuchBeanDefinitionException ex) { diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/social/FacebookAutoConfigurationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/social/FacebookAutoConfigurationTests.java index c58e550a28..5638ba288b 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/social/FacebookAutoConfigurationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/social/FacebookAutoConfigurationTests.java @@ -22,7 +22,7 @@ import org.springframework.boot.test.EnvironmentTestUtils; import org.springframework.social.facebook.api.Facebook; import org.springframework.web.context.support.AnnotationConfigWebApplicationContext; -import static org.junit.Assert.assertNotNull; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link FacebookAutoConfiguration}. @@ -42,7 +42,7 @@ public class FacebookAutoConfigurationTests extends AbstractSocialAutoConfigurat this.context.register(SocialWebAutoConfiguration.class); this.context.refresh(); assertConnectionFrameworkBeans(); - assertNotNull(this.context.getBean(Facebook.class)); + assertThat(this.context.getBean(Facebook.class)).isNotNull(); } @Test diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/social/LinkedInAutoConfigurationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/social/LinkedInAutoConfigurationTests.java index 2a0ff5f34a..6814c1e8c3 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/social/LinkedInAutoConfigurationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/social/LinkedInAutoConfigurationTests.java @@ -22,7 +22,7 @@ import org.springframework.boot.test.EnvironmentTestUtils; import org.springframework.social.linkedin.api.LinkedIn; import org.springframework.web.context.support.AnnotationConfigWebApplicationContext; -import static org.junit.Assert.assertNotNull; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link LinkedInAutoConfiguration}. @@ -42,7 +42,7 @@ public class LinkedInAutoConfigurationTests extends AbstractSocialAutoConfigurat this.context.register(SocialWebAutoConfiguration.class); this.context.refresh(); assertConnectionFrameworkBeans(); - assertNotNull(this.context.getBean(LinkedIn.class)); + assertThat(this.context.getBean(LinkedIn.class)).isNotNull(); } @Test diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/social/MultiApiAutoConfigurationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/social/MultiApiAutoConfigurationTests.java index a96bd03e10..4c8a842ad5 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/social/MultiApiAutoConfigurationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/social/MultiApiAutoConfigurationTests.java @@ -24,7 +24,7 @@ import org.springframework.social.linkedin.api.LinkedIn; import org.springframework.social.twitter.api.Twitter; import org.springframework.web.context.support.AnnotationConfigWebApplicationContext; -import static org.junit.Assert.assertNotNull; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for Spring Social configuration with multiple API providers. @@ -38,7 +38,7 @@ public class MultiApiAutoConfigurationTests extends AbstractSocialAutoConfigurat setupContext("spring.social.twitter.appId:12345", "spring.social.twitter.appSecret:secret"); assertConnectionFrameworkBeans(); - assertNotNull(this.context.getBean(Twitter.class)); + assertThat(this.context.getBean(Twitter.class)).isNotNull(); assertMissingBean(Facebook.class); assertMissingBean(LinkedIn.class); } @@ -48,7 +48,7 @@ public class MultiApiAutoConfigurationTests extends AbstractSocialAutoConfigurat setupContext("spring.social.facebook.appId:12345", "spring.social.facebook.appSecret:secret"); assertConnectionFrameworkBeans(); - assertNotNull(this.context.getBean(Facebook.class)); + assertThat(this.context.getBean(Facebook.class)).isNotNull(); assertMissingBean(Twitter.class); assertMissingBean(LinkedIn.class); } @@ -58,7 +58,7 @@ public class MultiApiAutoConfigurationTests extends AbstractSocialAutoConfigurat setupContext("spring.social.linkedin.appId:12345", "spring.social.linkedin.appSecret:secret"); assertConnectionFrameworkBeans(); - assertNotNull(this.context.getBean(LinkedIn.class)); + assertThat(this.context.getBean(LinkedIn.class)).isNotNull(); assertMissingBean(Twitter.class); assertMissingBean(Facebook.class); } @@ -70,8 +70,8 @@ public class MultiApiAutoConfigurationTests extends AbstractSocialAutoConfigurat "spring.social.linkedin.appId:12345", "spring.social.linkedin.appSecret:secret"); assertConnectionFrameworkBeans(); - assertNotNull(this.context.getBean(Facebook.class)); - assertNotNull(this.context.getBean(LinkedIn.class)); + assertThat(this.context.getBean(Facebook.class)).isNotNull(); + assertThat(this.context.getBean(LinkedIn.class)).isNotNull(); assertMissingBean(Twitter.class); } @@ -82,8 +82,8 @@ public class MultiApiAutoConfigurationTests extends AbstractSocialAutoConfigurat "spring.social.twitter.appId:12345", "spring.social.twitter.appSecret:secret"); assertConnectionFrameworkBeans(); - assertNotNull(this.context.getBean(Facebook.class)); - assertNotNull(this.context.getBean(Twitter.class)); + assertThat(this.context.getBean(Facebook.class)).isNotNull(); + assertThat(this.context.getBean(Twitter.class)).isNotNull(); assertMissingBean(LinkedIn.class); } @@ -94,8 +94,8 @@ public class MultiApiAutoConfigurationTests extends AbstractSocialAutoConfigurat "spring.social.twitter.appId:12345", "spring.social.twitter.appSecret:secret"); assertConnectionFrameworkBeans(); - assertNotNull(this.context.getBean(LinkedIn.class)); - assertNotNull(this.context.getBean(Twitter.class)); + assertThat(this.context.getBean(LinkedIn.class)).isNotNull(); + assertThat(this.context.getBean(Twitter.class)).isNotNull(); assertMissingBean(Facebook.class); } diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/social/TwitterAutoConfigurationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/social/TwitterAutoConfigurationTests.java index 85658723a5..a40dbd8e6c 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/social/TwitterAutoConfigurationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/social/TwitterAutoConfigurationTests.java @@ -22,7 +22,7 @@ import org.springframework.boot.test.EnvironmentTestUtils; import org.springframework.social.twitter.api.Twitter; import org.springframework.web.context.support.AnnotationConfigWebApplicationContext; -import static org.junit.Assert.assertNotNull; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link TwitterAutoConfiguration}. @@ -42,7 +42,7 @@ public class TwitterAutoConfigurationTests extends AbstractSocialAutoConfigurati this.context.register(SocialWebAutoConfiguration.class); this.context.refresh(); assertConnectionFrameworkBeans(); - assertNotNull(this.context.getBean(Twitter.class)); + assertThat(this.context.getBean(Twitter.class)).isNotNull(); } @Test diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/template/ViewResolverPropertiesTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/template/ViewResolverPropertiesTests.java old mode 100755 new mode 100644 index 8030f9709b..5674de9c76 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/template/ViewResolverPropertiesTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/template/ViewResolverPropertiesTests.java @@ -22,7 +22,6 @@ import org.junit.Test; import org.springframework.util.MimeTypeUtils; -import static org.hamcrest.Matchers.hasToString; import static org.assertj.core.api.Assertions.assertThat; /** @@ -34,22 +33,22 @@ public class ViewResolverPropertiesTests { @Test public void defaultContentType() { - assertThat(new ViewResolverProperties().getContentType(), - hasToString("text/html;charset=UTF-8")); + assertThat(new ViewResolverProperties().getContentType()) + .hasToString("text/html;charset=UTF-8"); } @Test public void customContentTypeDefaultCharset() { ViewResolverProperties properties = new ViewResolverProperties(); properties.setContentType(MimeTypeUtils.parseMimeType("text/plain")); - assertThat(properties.getContentType(), hasToString("text/plain;charset=UTF-8")); + assertThat(properties.getContentType()).hasToString("text/plain;charset=UTF-8"); } @Test public void defaultContentTypeCustomCharset() { ViewResolverProperties properties = new ViewResolverProperties(); properties.setCharset(Charset.forName("UTF-16")); - assertThat(properties.getContentType(), hasToString("text/html;charset=UTF-16")); + assertThat(properties.getContentType()).hasToString("text/html;charset=UTF-16"); } @Test @@ -57,7 +56,7 @@ public class ViewResolverPropertiesTests { ViewResolverProperties properties = new ViewResolverProperties(); properties.setContentType(MimeTypeUtils.parseMimeType("text/plain")); properties.setCharset(Charset.forName("UTF-16")); - assertThat(properties.getContentType(), hasToString("text/plain;charset=UTF-16")); + assertThat(properties.getContentType()).hasToString("text/plain;charset=UTF-16"); } @Test @@ -65,8 +64,8 @@ public class ViewResolverPropertiesTests { ViewResolverProperties properties = new ViewResolverProperties(); properties.setContentType(MimeTypeUtils.parseMimeType("text/plain;foo=bar")); properties.setCharset(Charset.forName("UTF-16")); - assertThat(properties.getContentType(), - hasToString("text/plain;charset=UTF-16;foo=bar")); + assertThat(properties.getContentType()) + .hasToString("text/plain;charset=UTF-16;foo=bar"); } private static class ViewResolverProperties extends AbstractViewResolverProperties { diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/test/ImportAutoConfigurationImportSelectorTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/test/ImportAutoConfigurationImportSelectorTests.java index 159c2de79c..e7785c222e 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/test/ImportAutoConfigurationImportSelectorTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/test/ImportAutoConfigurationImportSelectorTests.java @@ -30,8 +30,7 @@ import org.springframework.core.env.Environment; import org.springframework.core.io.DefaultResourceLoader; import org.springframework.core.type.AnnotationMetadata; -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.verifyZeroInteractions; @@ -68,7 +67,7 @@ public class ImportAutoConfigurationImportSelectorTests { String[] value = new String[] { FreeMarkerAutoConfiguration.class.getName() }; configureValue(value); String[] imports = this.importSelector.selectImports(this.annotationMetadata); - assertThat(imports, equalTo(value)); + assertThat(imports).isEqualTo(value); } @Test diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/thymeleaf/ThymeleafAutoConfigurationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/thymeleaf/ThymeleafAutoConfigurationTests.java index c1bd3b336c..81075f9c4e 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/thymeleaf/ThymeleafAutoConfigurationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/thymeleaf/ThymeleafAutoConfigurationTests.java @@ -42,12 +42,8 @@ import org.springframework.web.servlet.ViewResolver; import org.springframework.web.servlet.resource.ResourceUrlEncodingFilter; import org.springframework.web.servlet.support.RequestContext; +import static org.assertj.core.api.Assertions.assertThat; import static org.hamcrest.Matchers.containsString; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; /** * Tests for {@link ThymeleafAutoConfiguration}. @@ -80,7 +76,7 @@ public class ThymeleafAutoConfigurationTests { TemplateEngine engine = this.context.getBean(TemplateEngine.class); Context attrs = new Context(Locale.UK, Collections.singletonMap("foo", "bar")); String result = engine.process("template.txt", attrs); - assertEquals("bar", result); + assertThat(result).isEqualTo("bar"); } @Test @@ -92,11 +88,12 @@ public class ThymeleafAutoConfigurationTests { this.context.refresh(); this.context.getBean(TemplateEngine.class).initialize(); ITemplateResolver resolver = this.context.getBean(ITemplateResolver.class); - assertTrue(resolver instanceof TemplateResolver); - assertEquals("UTF-16", ((TemplateResolver) resolver).getCharacterEncoding()); + assertThat(resolver instanceof TemplateResolver).isTrue(); + assertThat(((TemplateResolver) resolver).getCharacterEncoding()) + .isEqualTo("UTF-16"); ThymeleafViewResolver views = this.context.getBean(ThymeleafViewResolver.class); - assertEquals("UTF-16", views.getCharacterEncoding()); - assertEquals("text/html;charset=UTF-16", views.getContentType()); + assertThat(views.getCharacterEncoding()).isEqualTo("UTF-16"); + assertThat(views.getContentType()).isEqualTo("text/html;charset=UTF-16"); } @Test @@ -108,7 +105,7 @@ public class ThymeleafAutoConfigurationTests { this.context.refresh(); this.context.getBean(TemplateEngine.class).initialize(); ITemplateResolver resolver = this.context.getBean(ITemplateResolver.class); - assertEquals(Integer.valueOf(25), resolver.getOrder()); + assertThat(resolver.getOrder()).isEqualTo(Integer.valueOf(25)); } @Test @@ -119,7 +116,7 @@ public class ThymeleafAutoConfigurationTests { PropertyPlaceholderAutoConfiguration.class); this.context.refresh(); ThymeleafViewResolver views = this.context.getBean(ThymeleafViewResolver.class); - assertArrayEquals(new String[] { "foo", "bar" }, views.getViewNames()); + assertThat(views.getViewNames()).isEqualTo(new String[] { "foo", "bar" }); } @Test @@ -157,8 +154,8 @@ public class ThymeleafAutoConfigurationTests { request.setAttribute(RequestContext.WEB_APPLICATION_CONTEXT_ATTRIBUTE, context); view.render(Collections.singletonMap("foo", "bar"), request, response); String result = response.getContentAsString(); - assertTrue("Wrong result: " + result, result.contains("Content")); - assertTrue("Wrong result: " + result, result.contains("bar")); + assertThat(result).contains("Content"); + assertThat(result).contains("bar"); context.close(); } @@ -170,7 +167,7 @@ public class ThymeleafAutoConfigurationTests { TemplateEngine engine = this.context.getBean(TemplateEngine.class); Context attrs = new Context(Locale.UK, Collections.singletonMap("foo", "bar")); String result = engine.process("data-dialect", attrs); - assertEquals("", result); + assertThat(result).isEqualTo(""); } @Test @@ -181,7 +178,7 @@ public class ThymeleafAutoConfigurationTests { TemplateEngine engine = this.context.getBean(TemplateEngine.class); Context attrs = new Context(Locale.UK); String result = engine.process("java8time-dialect", attrs); - assertEquals("2015-11-24", result); + assertThat(result).isEqualTo("2015-11-24"); } @Test @@ -192,7 +189,7 @@ public class ThymeleafAutoConfigurationTests { TemplateEngine engine = this.context.getBean(TemplateEngine.class); Context attrs = new Context(Locale.UK, Collections.singletonMap("foo", "bar")); String result = engine.process("home", attrs); - assertEquals("bar", result); + assertThat(result).isEqualTo("bar"); } @Test @@ -200,13 +197,13 @@ public class ThymeleafAutoConfigurationTests { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext( ThymeleafAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); - assertEquals(0, context.getBeanNamesForType(ViewResolver.class).length); + assertThat(context.getBeanNamesForType(ViewResolver.class).length).isEqualTo(0); try { TemplateEngine engine = context.getBean(TemplateEngine.class); Context attrs = new Context(Locale.UK, Collections.singletonMap("greeting", "Hello World")); String result = engine.process("message", attrs); - assertThat(result, containsString("Hello World")); + assertThat(result).contains("Hello World"); } finally { context.close(); @@ -218,8 +215,8 @@ public class ThymeleafAutoConfigurationTests { this.context.register(ThymeleafAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); this.context.refresh(); - assertEquals(0, - this.context.getBeansOfType(ResourceUrlEncodingFilter.class).size()); + assertThat(this.context.getBeansOfType(ResourceUrlEncodingFilter.class)) + .isEmpty(); } @Test @@ -230,7 +227,7 @@ public class ThymeleafAutoConfigurationTests { EnvironmentTestUtils.addEnvironment(this.context, "spring.resources.chain.enabled:true"); this.context.refresh(); - assertNotNull(this.context.getBean(ResourceUrlEncodingFilter.class)); + assertThat(this.context.getBean(ResourceUrlEncodingFilter.class)).isNotNull(); } } diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/thymeleaf/ThymeleafTemplateAvailabilityProviderTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/thymeleaf/ThymeleafTemplateAvailabilityProviderTests.java index cc8d85f279..e46b360a53 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/thymeleaf/ThymeleafTemplateAvailabilityProviderTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/thymeleaf/ThymeleafTemplateAvailabilityProviderTests.java @@ -23,8 +23,7 @@ import org.springframework.core.io.DefaultResourceLoader; import org.springframework.core.io.ResourceLoader; import org.springframework.mock.env.MockEnvironment; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link ThymeleafTemplateAvailabilityProvider}. @@ -41,30 +40,29 @@ public class ThymeleafTemplateAvailabilityProviderTests { @Test public void availabilityOfTemplateInDefaultLocation() { - assertTrue(this.provider.isTemplateAvailable("home", this.environment, - getClass().getClassLoader(), this.resourceLoader)); + assertThat(this.provider.isTemplateAvailable("home", this.environment, + getClass().getClassLoader(), this.resourceLoader)).isTrue(); } @Test public void availabilityOfTemplateThatDoesNotExist() { - assertFalse(this.provider.isTemplateAvailable("whatever", this.environment, - getClass().getClassLoader(), this.resourceLoader)); + assertThat(this.provider.isTemplateAvailable("whatever", this.environment, + getClass().getClassLoader(), this.resourceLoader)).isFalse(); } @Test public void availabilityOfTemplateWithCustomPrefix() { this.environment.setProperty("spring.thymeleaf.prefix", "classpath:/custom-templates/"); - - assertTrue(this.provider.isTemplateAvailable("custom", this.environment, - getClass().getClassLoader(), this.resourceLoader)); + assertThat(this.provider.isTemplateAvailable("custom", this.environment, + getClass().getClassLoader(), this.resourceLoader)).isTrue(); } @Test public void availabilityOfTemplateWithCustomSuffix() { this.environment.setProperty("spring.thymeleaf.suffix", ".thymeleaf"); - - assertTrue(this.provider.isTemplateAvailable("suffixed", this.environment, - getClass().getClassLoader(), this.resourceLoader)); + assertThat(this.provider.isTemplateAvailable("suffixed", this.environment, + getClass().getClassLoader(), this.resourceLoader)).isTrue(); } + } diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/transaction/TransactionAutoConfigurationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/transaction/TransactionAutoConfigurationTests.java index 5b713b2810..06c0e22dd5 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/transaction/TransactionAutoConfigurationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/transaction/TransactionAutoConfigurationTests.java @@ -30,9 +30,7 @@ import org.springframework.context.annotation.Configuration; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.support.TransactionTemplate; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; /** @@ -54,7 +52,7 @@ public class TransactionAutoConfigurationTests { @Test public void noTransactionManager() { load(EmptyConfiguration.class); - assertEquals(0, this.context.getBeansOfType(TransactionTemplate.class).size()); + assertThat(this.context.getBeansOfType(TransactionTemplate.class)).isEmpty(); } @Test @@ -65,13 +63,14 @@ public class TransactionAutoConfigurationTests { .getBean(PlatformTransactionManager.class); TransactionTemplate transactionTemplate = this.context .getBean(TransactionTemplate.class); - assertSame(transactionManager, transactionTemplate.getTransactionManager()); + assertThat(transactionTemplate.getTransactionManager()) + .isSameAs(transactionManager); } @Test public void severalTransactionManagers() { load(SeveralTransactionManagersConfiguration.class); - assertEquals(0, this.context.getBeansOfType(TransactionTemplate.class).size()); + assertThat(this.context.getBeansOfType(TransactionTemplate.class)).isEmpty(); } @Test @@ -79,8 +78,8 @@ public class TransactionAutoConfigurationTests { load(CustomTransactionManagerConfiguration.class); Map beans = this.context .getBeansOfType(TransactionTemplate.class); - assertEquals(1, beans.size()); - assertTrue(beans.containsKey("transactionTemplateFoo")); + assertThat(beans).hasSize(1); + assertThat(beans.containsKey("transactionTemplateFoo")).isTrue(); } private void load(Class... configs) { diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/transaction/jta/JtaAutoConfigurationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/transaction/jta/JtaAutoConfigurationTests.java index ddb67c643c..b26b729f6a 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/transaction/jta/JtaAutoConfigurationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/transaction/jta/JtaAutoConfigurationTests.java @@ -59,11 +59,7 @@ import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.jta.JtaTransactionManager; import org.springframework.util.FileSystemUtils; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.is; -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; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; @@ -107,10 +103,10 @@ public class JtaAutoConfigurationTests { EnvironmentTestUtils.addEnvironment(this.context, "spring.jta.enabled:false"); this.context.register(JtaAutoConfiguration.class); this.context.refresh(); - assertEquals(0, this.context.getBeansOfType(JtaTransactionManager.class).size()); - assertEquals(0, this.context.getBeansOfType(XADataSourceWrapper.class).size()); - assertEquals(0, - this.context.getBeansOfType(XAConnectionFactoryWrapper.class).size()); + assertThat(this.context.getBeansOfType(JtaTransactionManager.class)).isEmpty(); + assertThat(this.context.getBeansOfType(XADataSourceWrapper.class)).isEmpty(); + assertThat(this.context.getBeansOfType(XAConnectionFactoryWrapper.class)) + .isEmpty(); } @Test @@ -145,7 +141,7 @@ public class JtaAutoConfigurationTests { JtaPropertiesConfiguration.class, BitronixJtaConfiguration.class); String serverId = this.context.getBean(bitronix.tm.Configuration.class) .getServerId(); - assertThat(serverId, is(equalTo(InetAddress.getLocalHost().getHostAddress()))); + assertThat(serverId).isEqualTo(InetAddress.getLocalHost().getHostAddress()); } @Test @@ -158,7 +154,7 @@ public class JtaAutoConfigurationTests { this.context.refresh(); String serverId = this.context.getBean(bitronix.tm.Configuration.class) .getServerId(); - assertThat(serverId, is(equalTo("custom"))); + assertThat(serverId).isEqualTo("custom"); } @Test @@ -172,7 +168,7 @@ public class JtaAutoConfigurationTests { File epochFile = new File("target/transaction-logs/" + InetAddress.getLocalHost().getHostAddress() + ".tm0.epoch"); - assertTrue(epochFile.isFile()); + assertThat(epochFile.isFile()).isTrue(); } @Test @@ -186,7 +182,7 @@ public class JtaAutoConfigurationTests { this.context.refresh(); File epochFile = new File("target/transaction-logs/custom0.epoch"); - assertTrue(epochFile.isFile()); + assertThat(epochFile.isFile()).isTrue(); } @Test @@ -200,8 +196,8 @@ public class JtaAutoConfigurationTests { this.context.refresh(); AtomikosConnectionFactoryBean connectionFactory = this.context .getBean(AtomikosConnectionFactoryBean.class); - assertThat(connectionFactory.getMinPoolSize(), is(equalTo(5))); - assertThat(connectionFactory.getMaxPoolSize(), is(equalTo(10))); + assertThat(connectionFactory.getMinPoolSize()).isEqualTo(5); + assertThat(connectionFactory.getMaxPoolSize()).isEqualTo(10); } @Test @@ -215,8 +211,8 @@ public class JtaAutoConfigurationTests { this.context.refresh(); PoolingConnectionFactoryBean connectionFactory = this.context .getBean(PoolingConnectionFactoryBean.class); - assertThat(connectionFactory.getMinPoolSize(), is(equalTo(5))); - assertThat(connectionFactory.getMaxPoolSize(), is(equalTo(10))); + assertThat(connectionFactory.getMinPoolSize()).isEqualTo(5); + assertThat(connectionFactory.getMaxPoolSize()).isEqualTo(10); } @Test @@ -230,8 +226,8 @@ public class JtaAutoConfigurationTests { this.context.refresh(); AtomikosDataSourceBean dataSource = this.context .getBean(AtomikosDataSourceBean.class); - assertThat(dataSource.getMinPoolSize(), is(equalTo(5))); - assertThat(dataSource.getMaxPoolSize(), is(equalTo(10))); + assertThat(dataSource.getMinPoolSize()).isEqualTo(5); + assertThat(dataSource.getMaxPoolSize()).isEqualTo(10); } @Test @@ -245,8 +241,8 @@ public class JtaAutoConfigurationTests { this.context.refresh(); PoolingDataSourceBean dataSource = this.context .getBean(PoolingDataSourceBean.class); - assertThat(dataSource.getMinPoolSize(), is(equalTo(5))); - assertThat(dataSource.getMaxPoolSize(), is(equalTo(10))); + assertThat(dataSource.getMinPoolSize()).isEqualTo(5); + assertThat(dataSource.getMaxPoolSize()).isEqualTo(10); } @Configuration diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/velocity/VelocityAutoConfigurationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/velocity/VelocityAutoConfigurationTests.java index 720e0d5c18..7fd3e0a7a5 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/velocity/VelocityAutoConfigurationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/velocity/VelocityAutoConfigurationTests.java @@ -37,7 +37,6 @@ import org.springframework.context.annotation.AnnotationConfigApplicationContext import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; import org.springframework.mock.web.MockServletContext; -import org.springframework.test.util.ReflectionTestUtils; import org.springframework.web.context.support.AnnotationConfigWebApplicationContext; import org.springframework.web.servlet.View; import org.springframework.web.servlet.resource.ResourceUrlEncodingFilter; @@ -46,14 +45,8 @@ import org.springframework.web.servlet.view.AbstractTemplateViewResolver; import org.springframework.web.servlet.view.velocity.VelocityConfigurer; import org.springframework.web.servlet.view.velocity.VelocityViewResolver; +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.notNullValue; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertThat; /** * Tests for {@link VelocityAutoConfiguration}. @@ -83,8 +76,8 @@ public class VelocityAutoConfigurationTests { @Test public void defaultConfiguration() { registerAndRefreshContext(); - assertThat(this.context.getBean(VelocityViewResolver.class), notNullValue()); - assertThat(this.context.getBean(VelocityConfigurer.class), notNullValue()); + assertThat(this.context.getBean(VelocityViewResolver.class)).isNotNull(); + assertThat(this.context.getBean(VelocityConfigurer.class)).isNotNull(); } @Test @@ -106,8 +99,8 @@ public class VelocityAutoConfigurationTests { registerAndRefreshContext(); MockHttpServletResponse response = render("home"); String result = response.getContentAsString(); - assertThat(result, containsString("home")); - assertThat(response.getContentType(), equalTo("text/html;charset=UTF-8")); + assertThat(result).contains("home"); + assertThat(response.getContentType()).isEqualTo("text/html;charset=UTF-8"); } @Test @@ -115,15 +108,15 @@ public class VelocityAutoConfigurationTests { registerAndRefreshContext("spring.velocity.contentType:application/json"); MockHttpServletResponse response = render("home"); String result = response.getContentAsString(); - assertThat(result, containsString("home")); - assertThat(response.getContentType(), equalTo("application/json;charset=UTF-8")); + assertThat(result).contains("home"); + assertThat(response.getContentType()).isEqualTo("application/json;charset=UTF-8"); } @Test public void customCharset() throws Exception { registerAndRefreshContext("spring.velocity.charset:ISO-8859-1"); assertThat(this.context.getBean(VelocityConfigurer.class).getVelocityEngine() - .getProperty("input.encoding"), equalTo((Object) "ISO-8859-1")); + .getProperty("input.encoding")).isEqualTo("ISO-8859-1"); } @Test @@ -131,7 +124,7 @@ public class VelocityAutoConfigurationTests { registerAndRefreshContext("spring.velocity.prefix:prefix/"); MockHttpServletResponse response = render("prefixed"); String result = response.getContentAsString(); - assertThat(result, containsString("prefixed")); + assertThat(result).contains("prefixed"); } @Test @@ -139,7 +132,7 @@ public class VelocityAutoConfigurationTests { registerAndRefreshContext("spring.velocity.suffix:.freemarker"); MockHttpServletResponse response = render("suffixed"); String result = response.getContentAsString(); - assertThat(result, containsString("suffixed")); + assertThat(result).contains("suffixed"); } @Test @@ -148,24 +141,22 @@ public class VelocityAutoConfigurationTests { "spring.velocity.resourceLoaderPath:classpath:/custom-templates/"); MockHttpServletResponse response = render("custom"); String result = response.getContentAsString(); - assertThat(result, containsString("custom")); + assertThat(result).contains("custom"); } @Test public void disableCache() { registerAndRefreshContext("spring.velocity.cache:false"); - assertThat(this.context.getBean(VelocityViewResolver.class).getCacheLimit(), - equalTo(0)); + assertThat(this.context.getBean(VelocityViewResolver.class).getCacheLimit()) + .isEqualTo(0); } @Test public void customVelocitySettings() { registerAndRefreshContext( "spring.velocity.properties.directive.parse.max.depth:10"); - assertThat( - this.context.getBean(VelocityConfigurer.class).getVelocityEngine() - .getProperty("directive.parse.max.depth"), - equalTo((Object) "10")); + assertThat(this.context.getBean(VelocityConfigurer.class).getVelocityEngine() + .getProperty("directive.parse.max.depth")).isEqualTo("10"); } @Test @@ -178,7 +169,7 @@ public class VelocityAutoConfigurationTests { VelocityContext velocityContext = new VelocityContext(); velocityContext.put("greeting", "Hello World"); template.merge(velocityContext, writer); - assertThat(writer.toString(), containsString("Hello World")); + assertThat(writer.toString()).contains("Hello World"); } @Test @@ -193,7 +184,7 @@ public class VelocityAutoConfigurationTests { VelocityContext velocityContext = new VelocityContext(); velocityContext.put("greeting", "Hello World"); template.merge(velocityContext, writer); - assertThat(writer.toString(), containsString("Hello World")); + assertThat(writer.toString()).contains("Hello World"); } finally { context.close(); @@ -204,21 +195,21 @@ public class VelocityAutoConfigurationTests { public void usesEmbeddedVelocityViewResolver() { registerAndRefreshContext("spring.velocity.toolbox:/toolbox.xml"); VelocityViewResolver resolver = this.context.getBean(VelocityViewResolver.class); - assertThat(resolver, instanceOf(EmbeddedVelocityViewResolver.class)); + assertThat(resolver).isInstanceOf(EmbeddedVelocityViewResolver.class); } @Test public void registerResourceHandlingFilterDisabledByDefault() throws Exception { registerAndRefreshContext(); - assertEquals(0, - this.context.getBeansOfType(ResourceUrlEncodingFilter.class).size()); + assertThat(this.context.getBeansOfType(ResourceUrlEncodingFilter.class)) + .isEmpty(); } @Test public void registerResourceHandlingFilterOnlyIfResourceChainIsEnabled() throws Exception { registerAndRefreshContext("spring.resources.chain.enabled:true"); - assertNotNull(this.context.getBean(ResourceUrlEncodingFilter.class)); + assertThat(this.context.getBean(ResourceUrlEncodingFilter.class)).isNotNull(); } @Test @@ -226,8 +217,7 @@ public class VelocityAutoConfigurationTests { registerAndRefreshContext("spring.velocity.allow-session-override:true"); AbstractTemplateViewResolver viewResolver = this.context .getBean(VelocityViewResolver.class); - assertThat((Boolean) ReflectionTestUtils.getField(viewResolver, - "allowSessionOverride"), is(true)); + assertThat(viewResolver).extracting("allowSessionOverride").containsExactly(true); } private void registerAndRefreshContext(String... env) { @@ -243,7 +233,7 @@ public class VelocityAutoConfigurationTests { private MockHttpServletResponse render(String viewName) throws Exception { VelocityViewResolver resolver = this.context.getBean(VelocityViewResolver.class); View view = resolver.resolveViewName(viewName, Locale.UK); - assertThat(view, notNullValue()); + assertThat(view).isNotNull(); HttpServletRequest request = new MockHttpServletRequest(); request.setAttribute(RequestContext.WEB_APPLICATION_CONTEXT_ATTRIBUTE, this.context); @@ -251,4 +241,5 @@ public class VelocityAutoConfigurationTests { view.render(null, request, response); return response; } + } diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/velocity/VelocityTemplateAvailabilityProviderTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/velocity/VelocityTemplateAvailabilityProviderTests.java index d05cff9017..d8b8e218f5 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/velocity/VelocityTemplateAvailabilityProviderTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/velocity/VelocityTemplateAvailabilityProviderTests.java @@ -23,8 +23,7 @@ import org.springframework.core.io.DefaultResourceLoader; import org.springframework.core.io.ResourceLoader; import org.springframework.mock.env.MockEnvironment; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link VelocityTemplateAvailabilityProvider}. @@ -41,35 +40,35 @@ public class VelocityTemplateAvailabilityProviderTests { @Test public void availabilityOfTemplateInDefaultLocation() { - assertTrue(this.provider.isTemplateAvailable("home", this.environment, - getClass().getClassLoader(), this.resourceLoader)); + assertThat(this.provider.isTemplateAvailable("home", this.environment, + getClass().getClassLoader(), this.resourceLoader)).isTrue(); } @Test public void availabilityOfTemplateThatDoesNotExist() { - assertFalse(this.provider.isTemplateAvailable("whatever", this.environment, - getClass().getClassLoader(), this.resourceLoader)); + assertThat(this.provider.isTemplateAvailable("whatever", this.environment, + getClass().getClassLoader(), this.resourceLoader)).isFalse(); } @Test public void availabilityOfTemplateWithCustomLoaderPath() { this.environment.setProperty("spring.velocity.resourceLoaderPath", "classpath:/custom-templates/"); - assertTrue(this.provider.isTemplateAvailable("custom", this.environment, - getClass().getClassLoader(), this.resourceLoader)); + assertThat(this.provider.isTemplateAvailable("custom", this.environment, + getClass().getClassLoader(), this.resourceLoader)).isTrue(); } @Test public void availabilityOfTemplateWithCustomPrefix() { this.environment.setProperty("spring.velocity.prefix", "prefix/"); - assertTrue(this.provider.isTemplateAvailable("prefixed", this.environment, - getClass().getClassLoader(), this.resourceLoader)); + assertThat(this.provider.isTemplateAvailable("prefixed", this.environment, + getClass().getClassLoader(), this.resourceLoader)).isTrue(); } @Test public void availabilityOfTemplateWithCustomSuffix() { this.environment.setProperty("spring.velocity.suffix", ".freemarker"); - assertTrue(this.provider.isTemplateAvailable("suffixed", this.environment, - getClass().getClassLoader(), this.resourceLoader)); + assertThat(this.provider.isTemplateAvailable("suffixed", this.environment, + getClass().getClassLoader(), this.resourceLoader)).isTrue(); } } diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/BasicErrorControllerDirectMockMvcTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/BasicErrorControllerDirectMockMvcTests.java index 56da7ccc95..c1f39b2a2d 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/BasicErrorControllerDirectMockMvcTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/BasicErrorControllerDirectMockMvcTests.java @@ -48,7 +48,7 @@ import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.ConfigurableWebApplicationContext; import org.springframework.web.servlet.config.annotation.EnableWebMvc; -import static org.junit.Assert.assertTrue; +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.status; @@ -87,7 +87,7 @@ public class BasicErrorControllerDirectMockMvcTests { .perform(get("/error").accept(MediaType.TEXT_HTML)) .andExpect(status().is5xxServerError()).andReturn(); String content = response.getResponse().getContentAsString(); - assertTrue("Wrong content: " + content, content.contains("status=999")); + assertThat(content).contains("status=999"); } @Test @@ -98,7 +98,7 @@ public class BasicErrorControllerDirectMockMvcTests { .perform(get("/error").accept(MediaType.TEXT_HTML)) .andExpect(status().is5xxServerError()).andReturn(); String content = response.getResponse().getContentAsString(); - assertTrue("Wrong content: " + content, content.contains("status=999")); + assertThat(content).contains("status=999"); } @Test @@ -118,7 +118,7 @@ public class BasicErrorControllerDirectMockMvcTests { .perform(get("/error").accept(MediaType.TEXT_HTML)) .andExpect(status().is5xxServerError()).andReturn(); String content = response.getResponse().getContentAsString(); - assertTrue("Wrong content: " + content, content.contains("status=999")); + assertThat(content).contains("status=999"); } @Target(ElementType.TYPE) diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/BasicErrorControllerIntegrationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/BasicErrorControllerIntegrationTests.java index e79e26029a..29d80f323a 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/BasicErrorControllerIntegrationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/BasicErrorControllerIntegrationTests.java @@ -48,6 +48,7 @@ import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.WebAppConfiguration; import org.springframework.validation.BindException; +import org.springframework.web.bind.MethodArgumentNotValidException; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; @@ -56,11 +57,7 @@ import org.springframework.web.bind.annotation.RestController; import org.springframework.web.servlet.View; import org.springframework.web.servlet.view.AbstractView; -import static org.hamcrest.Matchers.containsString; -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; /** * Tests for {@link BasicErrorController} using a real HTTP server. @@ -93,8 +90,7 @@ public class BasicErrorControllerIntegrationTests { .getForEntity(createUrl("?trace=true"), Map.class); assertErrorAttributes(entity.getBody(), "500", "Internal Server Error", IllegalStateException.class, "Expected!", "/"); - assertFalse("trace parameter should not be set", - entity.getBody().containsKey("trace")); + assertThat(entity.getBody().containsKey("trace")).isFalse(); } @Test @@ -105,8 +101,7 @@ public class BasicErrorControllerIntegrationTests { .getForEntity(createUrl("?trace=true"), Map.class); assertErrorAttributes(entity.getBody(), "500", "Internal Server Error", IllegalStateException.class, "Expected!", "/"); - assertTrue("trace parameter should be set", - entity.getBody().containsKey("trace")); + assertThat(entity.getBody().containsKey("trace")).isTrue(); } @Test @@ -117,8 +112,7 @@ public class BasicErrorControllerIntegrationTests { .getForEntity(createUrl("?trace=true"), Map.class); assertErrorAttributes(entity.getBody(), "500", "Internal Server Error", IllegalStateException.class, "Expected!", "/"); - assertFalse("trace parameter should not be set", - entity.getBody().containsKey("trace")); + assertThat(entity.getBody().containsKey("trace")).isFalse(); } @Test @@ -129,8 +123,7 @@ public class BasicErrorControllerIntegrationTests { .getForEntity(createUrl("?trace=false"), Map.class); assertErrorAttributes(entity.getBody(), "500", "Internal Server Error", IllegalStateException.class, "Expected!", "/"); - assertTrue("trace parameter should be set", - entity.getBody().containsKey("trace")); + assertThat(entity.getBody().containsKey("trace")).isTrue(); } @Test @@ -163,10 +156,10 @@ public class BasicErrorControllerIntegrationTests { .accept(MediaType.APPLICATION_JSON).build(); ResponseEntity entity = new TestRestTemplate().exchange(request, Map.class); String resp = entity.getBody().toString(); - assertThat(resp, containsString("Error count: 1")); - assertThat(resp, containsString("errors=[{")); - assertThat(resp, containsString("codes=[")); - assertThat(resp, containsString("org.springframework.validation.BindException")); + assertThat(resp).contains("Error count: 1"); + assertThat(resp).contains("errors=[{"); + assertThat(resp).contains("codes=["); + assertThat(resp).contains("org.springframework.validation.BindException"); } @Test @@ -178,20 +171,20 @@ public class BasicErrorControllerIntegrationTests { .contentType(MediaType.APPLICATION_JSON).body("{}"); ResponseEntity entity = new TestRestTemplate().exchange(request, Map.class); String resp = entity.getBody().toString(); - assertThat(resp, containsString("Error count: 1")); - assertThat(resp, containsString("errors=[{")); - assertThat(resp, containsString("codes=[")); - assertThat(resp, containsString( - "org.springframework.web.bind.MethodArgumentNotValidException")); + assertThat(resp).contains("Error count: 1"); + assertThat(resp).contains("errors=[{"); + assertThat(resp).contains("codes=["); + assertThat(resp).contains(MethodArgumentNotValidException.class.getName()); } private void assertErrorAttributes(Map content, String status, String error, Class exception, String message, String path) { - assertEquals("Wrong status", status, content.get("status")); - assertEquals("Wrong error", error, content.get("error")); - assertEquals("Wrong exception", exception.getName(), content.get("exception")); - assertEquals("Wrong message", message, content.get("message")); - assertEquals("Wrong path", path, content.get("path")); + assertThat(content.get("status")).as("Wrong status").isEqualTo(status); + assertThat(content.get("error")).as("Wrong error").isEqualTo(error); + assertThat(content.get("exception")).as("Wrong exception") + .isEqualTo(exception.getName()); + assertThat(content.get("message")).as("Wrong message").isEqualTo(message); + assertThat(content.get("path")).as("Wrong path").isEqualTo(path); } private String createUrl(String path) { diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/BasicErrorControllerMockMvcTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/BasicErrorControllerMockMvcTests.java index e949c7a4cd..b233ac3a02 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/BasicErrorControllerMockMvcTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/BasicErrorControllerMockMvcTests.java @@ -58,7 +58,7 @@ import org.springframework.web.context.WebApplicationContext; import org.springframework.web.servlet.View; import org.springframework.web.servlet.view.AbstractView; -import static org.junit.Assert.assertTrue; +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.status; @@ -89,7 +89,7 @@ public class BasicErrorControllerMockMvcTests { MvcResult response = this.mockMvc.perform(get("/error")) .andExpect(status().is5xxServerError()).andReturn(); String content = response.getResponse().getContentAsString(); - assertTrue("Wrong content: " + content, content.contains("999")); + assertThat(content).contains("999"); } @Test @@ -99,7 +99,7 @@ public class BasicErrorControllerMockMvcTests { MvcResult response = this.mockMvc.perform(new ErrorDispatcher(result, "/error")) .andReturn(); String content = response.getResponse().getContentAsString(); - assertTrue("Wrong content: " + content, content.contains("Expected!")); + assertThat(content).contains("Expected!"); } @Test @@ -114,7 +114,7 @@ public class BasicErrorControllerMockMvcTests { // And the rendered status code is always wrong (but would be 400 in a real // system) String content = response.getResponse().getContentAsString(); - assertTrue("Wrong content: " + content, content.contains("Error count: 1")); + assertThat(content).contains("Error count: 1"); } @Test @@ -123,7 +123,7 @@ public class BasicErrorControllerMockMvcTests { .perform(get("/error").accept(MediaType.TEXT_HTML)) .andExpect(status().is5xxServerError()).andReturn(); String content = response.getResponse().getContentAsString(); - assertTrue("Wrong content: " + content, content.contains("ERROR_BEAN")); + assertThat(content).contains("ERROR_BEAN"); } @Target(ElementType.TYPE) @@ -214,6 +214,7 @@ public class BasicErrorControllerMockMvcTests { request.setRequestURI(this.path); return request; } + } } diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/ConditionalOnEnabledResourceChainTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/ConditionalOnEnabledResourceChainTests.java index f36c8daa9c..9305751d33 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/ConditionalOnEnabledResourceChainTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/ConditionalOnEnabledResourceChainTests.java @@ -24,8 +24,7 @@ import org.springframework.context.annotation.AnnotationConfigApplicationContext import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link ConditionalOnEnabledResourceChain}. @@ -44,31 +43,31 @@ public class ConditionalOnEnabledResourceChainTests { @Test public void disabledByDefault() { load(); - assertFalse(this.context.containsBean("foo")); + assertThat(this.context.containsBean("foo")).isFalse(); } @Test public void disabledExplicitly() { load("spring.resources.chain.enabled:false"); - assertFalse(this.context.containsBean("foo")); + assertThat(this.context.containsBean("foo")).isFalse(); } @Test public void enabledViaMainEnabledFlag() { load("spring.resources.chain.enabled:true"); - assertTrue(this.context.containsBean("foo")); + assertThat(this.context.containsBean("foo")).isTrue(); } @Test public void enabledViaFixedStrategyFlag() { load("spring.resources.chain.strategy.fixed.enabled:true"); - assertTrue(this.context.containsBean("foo")); + assertThat(this.context.containsBean("foo")).isTrue(); } @Test public void enabledViaContentStrategyFlag() { load("spring.resources.chain.strategy.content.enabled:true"); - assertTrue(this.context.containsBean("foo")); + assertThat(this.context.containsBean("foo")).isTrue(); } private void load(String... environment) { diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/DefaultErrorAttributesTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/DefaultErrorAttributesTests.java index e9d50b7c8e..3871c68ee5 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/DefaultErrorAttributesTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/DefaultErrorAttributesTests.java @@ -35,12 +35,7 @@ import org.springframework.web.context.request.RequestAttributes; import org.springframework.web.context.request.ServletRequestAttributes; import org.springframework.web.servlet.ModelAndView; -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.hamcrest.Matchers.startsWith; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link DefaultErrorAttributes}. @@ -60,7 +55,7 @@ public class DefaultErrorAttributesTests { public void includeTimeStamp() throws Exception { Map attributes = this.errorAttributes .getErrorAttributes(this.requestAttributes, false); - assertThat(attributes.get("timestamp"), instanceOf(Date.class)); + assertThat(attributes.get("timestamp")).isInstanceOf(Date.class); } @Test @@ -68,17 +63,17 @@ public class DefaultErrorAttributesTests { this.request.setAttribute("javax.servlet.error.status_code", 404); Map attributes = this.errorAttributes .getErrorAttributes(this.requestAttributes, false); - assertThat(attributes.get("error"), - equalTo((Object) HttpStatus.NOT_FOUND.getReasonPhrase())); - assertThat(attributes.get("status"), equalTo((Object) 404)); + assertThat(attributes.get("error")) + .isEqualTo(HttpStatus.NOT_FOUND.getReasonPhrase()); + assertThat(attributes.get("status")).isEqualTo(404); } @Test public void missingStatusCode() throws Exception { Map attributes = this.errorAttributes .getErrorAttributes(this.requestAttributes, false); - assertThat(attributes.get("error"), equalTo((Object) "None")); - assertThat(attributes.get("status"), equalTo((Object) 999)); + assertThat(attributes.get("error")).isEqualTo("None"); + assertThat(attributes.get("status")).isEqualTo(999); } @Test @@ -90,12 +85,11 @@ public class DefaultErrorAttributesTests { new RuntimeException("Ignored")); Map attributes = this.errorAttributes .getErrorAttributes(this.requestAttributes, false); - assertThat(this.errorAttributes.getError(this.requestAttributes), - sameInstance((Object) ex)); - assertThat(modelAndView, nullValue()); - assertThat(attributes.get("exception"), - equalTo((Object) RuntimeException.class.getName())); - assertThat(attributes.get("message"), equalTo((Object) "Test")); + assertThat(this.errorAttributes.getError(this.requestAttributes)).isSameAs(ex); + assertThat(modelAndView).isNull(); + assertThat(attributes.get("exception")) + .isEqualTo(RuntimeException.class.getName()); + assertThat(attributes.get("message")).isEqualTo("Test"); } @Test @@ -104,11 +98,10 @@ public class DefaultErrorAttributesTests { this.request.setAttribute("javax.servlet.error.exception", ex); Map attributes = this.errorAttributes .getErrorAttributes(this.requestAttributes, false); - assertThat(this.errorAttributes.getError(this.requestAttributes), - sameInstance((Object) ex)); - assertThat(attributes.get("exception"), - equalTo((Object) RuntimeException.class.getName())); - assertThat(attributes.get("message"), equalTo((Object) "Test")); + assertThat(this.errorAttributes.getError(this.requestAttributes)).isSameAs(ex); + assertThat(attributes.get("exception")) + .isEqualTo(RuntimeException.class.getName()); + assertThat(attributes.get("message")).isEqualTo("Test"); } @Test @@ -116,8 +109,8 @@ public class DefaultErrorAttributesTests { this.request.setAttribute("javax.servlet.error.message", "Test"); Map attributes = this.errorAttributes .getErrorAttributes(this.requestAttributes, false); - assertThat(attributes.get("exception"), nullValue()); - assertThat(attributes.get("message"), equalTo((Object) "Test")); + assertThat(attributes.get("exception")).isNull(); + assertThat(attributes.get("message")).isEqualTo("Test"); } @Test @@ -127,9 +120,9 @@ public class DefaultErrorAttributesTests { this.request.setAttribute("javax.servlet.error.message", "Test"); Map attributes = this.errorAttributes .getErrorAttributes(this.requestAttributes, false); - assertThat(attributes.get("exception"), - equalTo((Object) RuntimeException.class.getName())); - assertThat(attributes.get("message"), equalTo((Object) "Test")); + assertThat(attributes.get("exception")) + .isEqualTo(RuntimeException.class.getName()); + assertThat(attributes.get("message")).isEqualTo("Test"); } @Test @@ -139,11 +132,11 @@ public class DefaultErrorAttributesTests { this.request.setAttribute("javax.servlet.error.exception", wrapped); Map attributes = this.errorAttributes .getErrorAttributes(this.requestAttributes, false); - assertThat(this.errorAttributes.getError(this.requestAttributes), - sameInstance((Object) wrapped)); - assertThat(attributes.get("exception"), - equalTo((Object) RuntimeException.class.getName())); - assertThat(attributes.get("message"), equalTo((Object) "Test")); + assertThat(this.errorAttributes.getError(this.requestAttributes)) + .isSameAs(wrapped); + assertThat(attributes.get("exception")) + .isEqualTo(RuntimeException.class.getName()); + assertThat(attributes.get("message")).isEqualTo("Test"); } @Test @@ -152,11 +145,10 @@ public class DefaultErrorAttributesTests { this.request.setAttribute("javax.servlet.error.exception", error); Map attributes = this.errorAttributes .getErrorAttributes(this.requestAttributes, false); - assertThat(this.errorAttributes.getError(this.requestAttributes), - sameInstance((Object) error)); - assertThat(attributes.get("exception"), - equalTo((Object) OutOfMemoryError.class.getName())); - assertThat(attributes.get("message"), equalTo((Object) "Test error")); + assertThat(this.errorAttributes.getError(this.requestAttributes)).isSameAs(error); + assertThat(attributes.get("exception")) + .isEqualTo(OutOfMemoryError.class.getName()); + assertThat(attributes.get("message")).isEqualTo("Test error"); } @Test @@ -182,10 +174,9 @@ public class DefaultErrorAttributesTests { this.request.setAttribute("javax.servlet.error.exception", ex); Map attributes = this.errorAttributes .getErrorAttributes(this.requestAttributes, false); - assertThat(attributes.get("message"), equalTo((Object) ("Validation failed for " - + "object='objectName'. Error count: 1"))); - assertThat(attributes.get("errors"), - equalTo((Object) bindingResult.getAllErrors())); + assertThat(attributes.get("message")) + .isEqualTo("Validation failed for object='objectName'. Error count: 1"); + assertThat(attributes.get("errors")).isEqualTo(bindingResult.getAllErrors()); } @Test @@ -194,7 +185,7 @@ public class DefaultErrorAttributesTests { this.request.setAttribute("javax.servlet.error.exception", ex); Map attributes = this.errorAttributes .getErrorAttributes(this.requestAttributes, true); - assertThat(attributes.get("trace").toString(), startsWith("java.lang")); + assertThat(attributes.get("trace").toString()).startsWith("java.lang"); } @Test @@ -203,7 +194,7 @@ public class DefaultErrorAttributesTests { this.request.setAttribute("javax.servlet.error.exception", ex); Map attributes = this.errorAttributes .getErrorAttributes(this.requestAttributes, false); - assertThat(attributes.get("trace"), nullValue()); + assertThat(attributes.get("trace")).isNull(); } @Test @@ -211,7 +202,7 @@ public class DefaultErrorAttributesTests { this.request.setAttribute("javax.servlet.error.request_uri", "path"); Map attributes = this.errorAttributes .getErrorAttributes(this.requestAttributes, false); - assertThat(attributes.get("path"), equalTo((Object) "path")); - + assertThat(attributes.get("path")).isEqualTo("path"); } + } diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/DefaultErrorViewIntegrationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/DefaultErrorViewIntegrationTests.java index 14777a7033..8d73b7175e 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/DefaultErrorViewIntegrationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/DefaultErrorViewIntegrationTests.java @@ -42,8 +42,7 @@ import org.springframework.test.web.servlet.MvcResult; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +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.status; @@ -72,8 +71,8 @@ public class DefaultErrorViewIntegrationTests { .perform(get("/error").accept(MediaType.TEXT_HTML)) .andExpect(status().is5xxServerError()).andReturn(); String content = response.getResponse().getContentAsString(); - assertTrue("Wrong content: " + content, content.contains("")); - assertTrue("Wrong content: " + content, content.contains("999")); + assertThat(content).contains(""); + assertThat(content).contains("999"); } @Test @@ -86,9 +85,9 @@ public class DefaultErrorViewIntegrationTests { .accept(MediaType.TEXT_HTML)) .andExpect(status().is5xxServerError()).andReturn(); String content = response.getResponse().getContentAsString(); - assertTrue("Wrong content: " + content, content.contains("<script>")); - assertTrue("Wrong content: " + content, content.contains("Hello World")); - assertTrue("Wrong content: " + content, content.contains("999")); + assertThat(content).contains("<script>"); + assertThat(content).contains("Hello World"); + assertThat(content).contains("999"); } @Test @@ -102,8 +101,7 @@ public class DefaultErrorViewIntegrationTests { .accept(MediaType.TEXT_HTML)) .andExpect(status().is5xxServerError()).andReturn(); String content = response.getResponse().getContentAsString(); - System.out.println(content); - assertFalse("Wrong content: " + content, content.contains("injection")); + assertThat(content).doesNotContain("injection"); } public static String injectCall() { diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/DispatcherServletAutoConfigurationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/DispatcherServletAutoConfigurationTests.java index d3f03cb0cd..3c79e89998 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/DispatcherServletAutoConfigurationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/DispatcherServletAutoConfigurationTests.java @@ -22,7 +22,6 @@ import javax.servlet.http.HttpServletRequest; import org.junit.After; import org.junit.Test; -import org.springframework.beans.DirectFieldAccessor; import org.springframework.beans.factory.UnsatisfiedDependencyException; import org.springframework.boot.context.embedded.MultipartConfigFactory; import org.springframework.boot.context.embedded.ServletRegistrationBean; @@ -37,11 +36,7 @@ import org.springframework.web.multipart.MultipartHttpServletRequest; import org.springframework.web.multipart.MultipartResolver; import org.springframework.web.servlet.DispatcherServlet; -import static org.hamcrest.Matchers.instanceOf; -import static org.junit.Assert.assertEquals; -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 DispatcherServletAutoConfiguration}. @@ -66,10 +61,10 @@ public class DispatcherServletAutoConfigurationTests { DispatcherServletAutoConfiguration.class); this.context.setServletContext(new MockServletContext()); this.context.refresh(); - assertNotNull(this.context.getBean(DispatcherServlet.class)); + assertThat(this.context.getBean(DispatcherServlet.class)).isNotNull(); ServletRegistrationBean registration = this.context .getBean(ServletRegistrationBean.class); - assertEquals("[/]", registration.getUrlMappings().toString()); + assertThat(registration.getUrlMappings().toString()).isEqualTo("[/]"); } @Test @@ -82,9 +77,10 @@ public class DispatcherServletAutoConfigurationTests { this.context.refresh(); ServletRegistrationBean registration = this.context .getBean(ServletRegistrationBean.class); - assertEquals("[/foo]", registration.getUrlMappings().toString()); - assertEquals("customDispatcher", registration.getServletName()); - assertEquals(0, this.context.getBeanNamesForType(DispatcherServlet.class).length); + assertThat(registration.getUrlMappings().toString()).isEqualTo("[/foo]"); + assertThat(registration.getServletName()).isEqualTo("customDispatcher"); + assertThat(this.context.getBeanNamesForType(DispatcherServlet.class).length) + .isEqualTo(0); } // If you override either the dispatcherServlet or its registration you have to @@ -99,9 +95,10 @@ public class DispatcherServletAutoConfigurationTests { this.context.refresh(); ServletRegistrationBean registration = this.context .getBean(ServletRegistrationBean.class); - assertEquals("[/foo]", registration.getUrlMappings().toString()); - assertEquals("customDispatcher", registration.getServletName()); - assertEquals(1, this.context.getBeanNamesForType(DispatcherServlet.class).length); + assertThat(registration.getUrlMappings().toString()).isEqualTo("[/foo]"); + assertThat(registration.getServletName()).isEqualTo("customDispatcher"); + assertThat(this.context.getBeanNamesForType(DispatcherServlet.class).length) + .isEqualTo(1); } @Test @@ -112,11 +109,11 @@ public class DispatcherServletAutoConfigurationTests { DispatcherServletAutoConfiguration.class); EnvironmentTestUtils.addEnvironment(this.context, "server.servlet_path:/spring"); this.context.refresh(); - assertNotNull(this.context.getBean(DispatcherServlet.class)); + assertThat(this.context.getBean(DispatcherServlet.class)).isNotNull(); ServletRegistrationBean registration = this.context .getBean(ServletRegistrationBean.class); - assertEquals("[/spring/*]", registration.getUrlMappings().toString()); - assertNull(registration.getMultipartConfig()); + assertThat(registration.getUrlMappings().toString()).isEqualTo("[/spring/*]"); + assertThat(registration.getMultipartConfig()).isNull(); } @Test @@ -129,7 +126,7 @@ public class DispatcherServletAutoConfigurationTests { this.context.refresh(); ServletRegistrationBean registration = this.context .getBean(ServletRegistrationBean.class); - assertNotNull(registration.getMultipartConfig()); + assertThat(registration.getMultipartConfig()).isNotNull(); } @Test @@ -143,8 +140,8 @@ public class DispatcherServletAutoConfigurationTests { DispatcherServlet dispatcherServlet = this.context .getBean(DispatcherServlet.class); dispatcherServlet.onApplicationEvent(new ContextRefreshedEvent(this.context)); - assertThat(dispatcherServlet.getMultipartResolver(), - instanceOf(MockMultipartResolver.class)); + assertThat(dispatcherServlet.getMultipartResolver()) + .isInstanceOf(MockMultipartResolver.class); } @Test @@ -161,12 +158,10 @@ public class DispatcherServletAutoConfigurationTests { "spring.mvc.dispatch-trace-request:true"); this.context.refresh(); DispatcherServlet bean = this.context.getBean(DispatcherServlet.class); - assertEquals(true, new DirectFieldAccessor(bean) - .getPropertyValue("throwExceptionIfNoHandlerFound")); - assertEquals(true, - new DirectFieldAccessor(bean).getPropertyValue("dispatchOptionsRequest")); - assertEquals(true, - new DirectFieldAccessor(bean).getPropertyValue("dispatchTraceRequest")); + assertThat(bean).extracting("throwExceptionIfNoHandlerFound") + .containsExactly(true); + assertThat(bean).extracting("dispatchOptionsRequest").containsExactly(true); + assertThat(bean).extracting("dispatchTraceRequest").containsExactly(true); } @Configuration diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/EmbeddedServletContainerAutoConfigurationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/EmbeddedServletContainerAutoConfigurationTests.java index 33f9c6aadb..b4f7467ba7 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/EmbeddedServletContainerAutoConfigurationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/EmbeddedServletContainerAutoConfigurationTests.java @@ -40,8 +40,7 @@ import org.springframework.stereotype.Component; import org.springframework.web.servlet.DispatcherServlet; import org.springframework.web.servlet.FrameworkServlet; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.verify; /** @@ -72,7 +71,8 @@ public class EmbeddedServletContainerAutoConfigurationTests { this.context = new AnnotationConfigEmbeddedWebApplicationContext( SpringServletConfiguration.class, BaseConfiguration.class); verifyContext(); - assertEquals(2, this.context.getBeanNamesForType(DispatcherServlet.class).length); + assertThat(this.context.getBeanNamesForType(DispatcherServlet.class).length) + .isEqualTo(2); } @Test @@ -80,15 +80,17 @@ public class EmbeddedServletContainerAutoConfigurationTests { this.context = new AnnotationConfigEmbeddedWebApplicationContext( NonSpringServletConfiguration.class, BaseConfiguration.class); verifyContext(); // the non default servlet is still registered - assertEquals(0, this.context.getBeanNamesForType(DispatcherServlet.class).length); + assertThat(this.context.getBeanNamesForType(DispatcherServlet.class).length) + .isEqualTo(0); } @Test public void contextAlreadyHasNonServlet() throws Exception { this.context = new AnnotationConfigEmbeddedWebApplicationContext( NonServletConfiguration.class, BaseConfiguration.class); - assertEquals(0, this.context.getBeanNamesForType(DispatcherServlet.class).length); - assertEquals(0, this.context.getBeanNamesForType(Servlet.class).length); + assertThat(this.context.getBeanNamesForType(DispatcherServlet.class).length) + .isEqualTo(0); + assertThat(this.context.getBeanNamesForType(Servlet.class).length).isEqualTo(0); } @Test @@ -97,7 +99,8 @@ public class EmbeddedServletContainerAutoConfigurationTests { DispatcherServletWithRegistrationConfiguration.class, BaseConfiguration.class); verifyContext(); - assertEquals(1, this.context.getBeanNamesForType(DispatcherServlet.class).length); + assertThat(this.context.getBeanNamesForType(DispatcherServlet.class).length) + .isEqualTo(1); } @Test @@ -112,7 +115,7 @@ public class EmbeddedServletContainerAutoConfigurationTests { this.context = new AnnotationConfigEmbeddedWebApplicationContext( CallbackEmbeddedContainerCustomizer.class, BaseConfiguration.class); verifyContext(); - assertEquals(9000, getContainerFactory().getPort()); + assertThat(getContainerFactory().getPort()).isEqualTo(9000); } @Test @@ -124,8 +127,8 @@ public class EmbeddedServletContainerAutoConfigurationTests { this.context.refresh(); ServletContext servletContext = this.context.getServletContext(); - assertEquals("alpha", servletContext.getInitParameter("a")); - assertEquals("bravo", servletContext.getInitParameter("b")); + assertThat(servletContext.getInitParameter("a")).isEqualTo("alpha"); + assertThat(servletContext.getInitParameter("b")).isEqualTo("bravo"); } private void verifyContext() { @@ -229,7 +232,7 @@ public class EmbeddedServletContainerAutoConfigurationTests { throws BeansException { if (bean instanceof ConfigurableEmbeddedServletContainer) { MockEmbeddedServletContainerFactory containerFactory = (MockEmbeddedServletContainerFactory) bean; - assertNull(containerFactory.getServletContext()); + assertThat(containerFactory.getServletContext()).isNull(); } return bean; } diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/FilterOrderingIntegrationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/FilterOrderingIntegrationTests.java index b226e9812c..fd08e0347e 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/FilterOrderingIntegrationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/FilterOrderingIntegrationTests.java @@ -17,6 +17,7 @@ package org.springframework.boot.autoconfigure.web; import java.util.ArrayList; +import java.util.Iterator; import java.util.List; import javax.servlet.Filter; @@ -40,9 +41,7 @@ import org.springframework.data.redis.connection.RedisConnectionFactory; import org.springframework.security.web.FilterChainProxy; import org.springframework.session.web.http.SessionRepositoryFilter; -import static org.hamcrest.Matchers.contains; -import static org.hamcrest.Matchers.instanceOf; -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; @@ -63,7 +62,6 @@ public class FilterOrderingIntegrationTests { } @Test - @SuppressWarnings("unchecked") public void testFilterOrdering() { load(); List registeredFilters = this.context @@ -73,10 +71,13 @@ public class FilterOrderingIntegrationTests { for (RegisteredFilter registeredFilter : registeredFilters) { filters.add(registeredFilter.getFilter()); } - assertThat(filters, contains(instanceOf(OrderedCharacterEncodingFilter.class), - instanceOf(SessionRepositoryFilter.class), instanceOf(Filter.class), - instanceOf(Filter.class), instanceOf(OrderedRequestContextFilter.class), - instanceOf(FilterChainProxy.class))); + Iterator iterator = filters.iterator(); + assertThat(iterator.next()).isInstanceOf(OrderedCharacterEncodingFilter.class); + assertThat(iterator.next()).isInstanceOf(SessionRepositoryFilter.class); + assertThat(iterator.next()).isInstanceOf(Filter.class); + assertThat(iterator.next()).isInstanceOf(Filter.class); + assertThat(iterator.next()).isInstanceOf(OrderedRequestContextFilter.class); + assertThat(iterator.next()).isInstanceOf(FilterChainProxy.class); } private void load() { diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/HttpEncodingAutoConfigurationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/HttpEncodingAutoConfigurationTests.java index 8bb5c53716..34ed835e08 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/HttpEncodingAutoConfigurationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/HttpEncodingAutoConfigurationTests.java @@ -38,9 +38,7 @@ import org.springframework.core.annotation.AnnotationAwareOrderComparator; import org.springframework.web.filter.CharacterEncodingFilter; import org.springframework.web.filter.HiddenHttpMethodFilter; -import static org.hamcrest.Matchers.instanceOf; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link HttpEncodingAutoConfiguration} @@ -100,16 +98,16 @@ public class HttpEncodingAutoConfigurationTests { List beans = new ArrayList( this.context.getBeansOfType(Filter.class).values()); AnnotationAwareOrderComparator.sort(beans); - assertThat(beans.get(0), instanceOf(CharacterEncodingFilter.class)); - assertThat(beans.get(1), instanceOf(HiddenHttpMethodFilter.class)); + assertThat(beans.get(0)).isInstanceOf(CharacterEncodingFilter.class); + assertThat(beans.get(1)).isInstanceOf(HiddenHttpMethodFilter.class); } private void assertCharacterEncodingFilter(CharacterEncodingFilter actual, String encoding, boolean forceEncoding) { DirectFieldAccessor accessor = new DirectFieldAccessor(actual); - assertEquals("Wrong encoding", encoding, accessor.getPropertyValue("encoding")); - assertEquals("Wrong forceEncoding flag", forceEncoding, - accessor.getPropertyValue("forceEncoding")); + assertThat(accessor.getPropertyValue("encoding")).as("Wrong encoding") + .isEqualTo(encoding); + assertThat(accessor.getPropertyValue("forceEncoding")).isEqualTo(forceEncoding); } private void load(Class config, String... environment) { diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/HttpMessageConvertersAutoConfigurationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/HttpMessageConvertersAutoConfigurationTests.java index 91315a321f..4f3bdd8cb6 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/HttpMessageConvertersAutoConfigurationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/HttpMessageConvertersAutoConfigurationTests.java @@ -42,11 +42,7 @@ import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder; import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; import org.springframework.http.converter.xml.MappingJackson2XmlHttpMessageConverter; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.is; -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 HttpMessageConvertersAutoConfiguration}. @@ -72,11 +68,12 @@ public class HttpMessageConvertersAutoConfigurationTests { public void noObjectMapperMeansNoConverter() throws Exception { this.context.register(HttpMessageConvertersAutoConfiguration.class); this.context.refresh(); - assertTrue(this.context.getBeansOfType(ObjectMapper.class).isEmpty()); - assertTrue(this.context.getBeansOfType(MappingJackson2HttpMessageConverter.class) - .isEmpty()); - assertTrue(this.context - .getBeansOfType(MappingJackson2XmlHttpMessageConverter.class).isEmpty()); + assertThat(this.context.getBeansOfType(ObjectMapper.class)).isEmpty(); + assertThat(this.context.getBeansOfType(MappingJackson2HttpMessageConverter.class)) + .isEmpty(); + assertThat( + this.context.getBeansOfType(MappingJackson2XmlHttpMessageConverter.class)) + .isEmpty(); } @Test @@ -124,8 +121,9 @@ public class HttpMessageConvertersAutoConfigurationTests { public void noGson() throws Exception { this.context.register(HttpMessageConvertersAutoConfiguration.class); this.context.refresh(); - assertTrue(this.context.getBeansOfType(Gson.class).isEmpty()); - assertTrue(this.context.getBeansOfType(GsonHttpMessageConverter.class).isEmpty()); + assertThat(this.context.getBeansOfType(Gson.class).isEmpty()).isTrue(); + assertThat(this.context.getBeansOfType(GsonHttpMessageConverter.class).isEmpty()) + .isTrue(); } @Test @@ -149,8 +147,7 @@ public class HttpMessageConvertersAutoConfigurationTests { "mappingJackson2HttpMessageConverter"); assertConverterBeanRegisteredWithHttpMessageConverters( MappingJackson2HttpMessageConverter.class); - assertEquals(0, - this.context.getBeansOfType(GsonHttpMessageConverter.class).size()); + assertThat(this.context.getBeansOfType(GsonHttpMessageConverter.class)).isEmpty(); } @Test @@ -164,8 +161,8 @@ public class HttpMessageConvertersAutoConfigurationTests { "gsonHttpMessageConverter"); assertConverterBeanRegisteredWithHttpMessageConverters( GsonHttpMessageConverter.class); - assertEquals(0, this.context - .getBeansOfType(MappingJackson2HttpMessageConverter.class).size()); + assertThat(this.context.getBeansOfType(MappingJackson2HttpMessageConverter.class)) + .isEmpty(); } @Test @@ -212,8 +209,8 @@ public class HttpMessageConvertersAutoConfigurationTests { BeanDefinition beanDefinition = this.context .getBeanDefinition("mappingJackson2HttpMessageConverter"); - assertThat(beanDefinition.getFactoryBeanName(), is(equalTo( - MappingJackson2HttpMessageConverterConfiguration.class.getName()))); + assertThat(beanDefinition.getFactoryBeanName()).isEqualTo( + MappingJackson2HttpMessageConverterConfiguration.class.getName()); } @Test @@ -229,21 +226,21 @@ public class HttpMessageConvertersAutoConfigurationTests { System.out.println(beansOfType); BeanDefinition beanDefinition = this.context .getBeanDefinition("mappingJackson2HttpMessageConverter"); - assertThat(beanDefinition.getFactoryBeanName(), is(equalTo( - MappingJackson2HttpMessageConverterConfiguration.class.getName()))); + assertThat(beanDefinition.getFactoryBeanName()).isEqualTo( + MappingJackson2HttpMessageConverterConfiguration.class.getName()); } private void assertConverterBeanExists(Class type, String beanName) { - assertEquals(1, this.context.getBeansOfType(type).size()); + assertThat(this.context.getBeansOfType(type)).hasSize(1); List beanNames = Arrays.asList(this.context.getBeanDefinitionNames()); - assertTrue(beanName + " not found in " + beanNames, beanNames.contains(beanName)); + assertThat(beanNames).contains(beanName); } private void assertConverterBeanRegisteredWithHttpMessageConverters(Class type) { Object converter = this.context.getBean(type); HttpMessageConverters converters = this.context .getBean(HttpMessageConverters.class); - assertTrue(converters.getConverters().contains(converter)); + assertThat(converters.getConverters().contains(converter)).isTrue(); } @Configuration diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/HttpMessageConvertersTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/HttpMessageConvertersTests.java index 405e4158eb..be1583d1f6 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/HttpMessageConvertersTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/HttpMessageConvertersTests.java @@ -17,7 +17,6 @@ package org.springframework.boot.autoconfigure.web; import java.util.ArrayList; -import java.util.Arrays; import java.util.Collection; import java.util.Iterator; import java.util.List; @@ -36,11 +35,7 @@ import org.springframework.http.converter.xml.MappingJackson2XmlHttpMessageConve import org.springframework.http.converter.xml.SourceHttpMessageConverter; import org.springframework.test.util.ReflectionTestUtils; -import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotEquals; -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; /** @@ -61,14 +56,12 @@ public class HttpMessageConvertersTests { for (HttpMessageConverter converter : converters) { converterClasses.add(converter.getClass()); } - assertThat(converterClasses, - equalTo(Arrays.>asList(ByteArrayHttpMessageConverter.class, - StringHttpMessageConverter.class, - ResourceHttpMessageConverter.class, - SourceHttpMessageConverter.class, - AllEncompassingFormHttpMessageConverter.class, - MappingJackson2HttpMessageConverter.class, - MappingJackson2XmlHttpMessageConverter.class))); + assertThat(converterClasses).containsExactly(ByteArrayHttpMessageConverter.class, + StringHttpMessageConverter.class, ResourceHttpMessageConverter.class, + SourceHttpMessageConverter.class, + AllEncompassingFormHttpMessageConverter.class, + MappingJackson2HttpMessageConverter.class, + MappingJackson2XmlHttpMessageConverter.class); } @Test @@ -77,8 +70,8 @@ public class HttpMessageConvertersTests { MappingJackson2HttpMessageConverter converter2 = new MappingJackson2HttpMessageConverter(); HttpMessageConverters converters = new HttpMessageConverters(converter1, converter2); - assertTrue(converters.getConverters().contains(converter1)); - assertTrue(converters.getConverters().contains(converter2)); + assertThat(converters.getConverters().contains(converter1)).isTrue(); + assertThat(converters.getConverters().contains(converter2)).isTrue(); List httpConverters = new ArrayList(); for (HttpMessageConverter candidate : converters) { if (candidate instanceof MappingJackson2HttpMessageConverter) { @@ -86,10 +79,10 @@ public class HttpMessageConvertersTests { } } // The existing converter is still there, but with a lower priority - assertEquals(3, httpConverters.size()); - assertEquals(0, httpConverters.indexOf(converter1)); - assertEquals(1, httpConverters.indexOf(converter2)); - assertNotEquals(0, converters.getConverters().indexOf(converter1)); + assertThat(httpConverters).hasSize(3); + assertThat(httpConverters.indexOf(converter1)).isEqualTo(0); + assertThat(httpConverters.indexOf(converter2)).isEqualTo(1); + assertThat(converters.getConverters().indexOf(converter1)).isNotEqualTo(0); } @Test @@ -98,8 +91,8 @@ public class HttpMessageConvertersTests { HttpMessageConverter converter2 = mock(HttpMessageConverter.class); HttpMessageConverters converters = new HttpMessageConverters(converter1, converter2); - assertEquals(converter1, converters.getConverters().get(0)); - assertEquals(converter2, converters.getConverters().get(1)); + assertThat(converters.getConverters().get(0)).isEqualTo(converter1); + assertThat(converters.getConverters().get(1)).isEqualTo(converter2); } @Test @@ -110,8 +103,8 @@ public class HttpMessageConvertersTests { converter2).getConverters(); List> partConverters = extractFormPartConverters( converters); - assertEquals(converter1, partConverters.get(0)); - assertEquals(converter2, partConverters.get(1)); + assertThat(partConverters.get(0)).isEqualTo(converter1); + assertThat(partConverters.get(1)).isEqualTo(converter2); } @Test @@ -134,13 +127,11 @@ public class HttpMessageConvertersTests { for (HttpMessageConverter converter : converters) { converterClasses.add(converter.getClass()); } - assertThat(converterClasses, - equalTo(Arrays.>asList(ByteArrayHttpMessageConverter.class, - StringHttpMessageConverter.class, - ResourceHttpMessageConverter.class, - SourceHttpMessageConverter.class, - AllEncompassingFormHttpMessageConverter.class, - MappingJackson2HttpMessageConverter.class))); + assertThat(converterClasses).containsExactly(ByteArrayHttpMessageConverter.class, + StringHttpMessageConverter.class, ResourceHttpMessageConverter.class, + SourceHttpMessageConverter.class, + AllEncompassingFormHttpMessageConverter.class, + MappingJackson2HttpMessageConverter.class); } @Test @@ -164,12 +155,10 @@ public class HttpMessageConvertersTests { converters.getConverters())) { converterClasses.add(converter.getClass()); } - assertThat(converterClasses, - equalTo(Arrays.>asList(ByteArrayHttpMessageConverter.class, - StringHttpMessageConverter.class, - ResourceHttpMessageConverter.class, - SourceHttpMessageConverter.class, - MappingJackson2HttpMessageConverter.class))); + assertThat(converterClasses).containsExactly(ByteArrayHttpMessageConverter.class, + StringHttpMessageConverter.class, ResourceHttpMessageConverter.class, + SourceHttpMessageConverter.class, + MappingJackson2HttpMessageConverter.class); } @SuppressWarnings("unchecked") diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/JspTemplateAvailabilityProviderTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/JspTemplateAvailabilityProviderTests.java old mode 100755 new mode 100644 index 340c5e0fc3..e39e94fa12 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/JspTemplateAvailabilityProviderTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/JspTemplateAvailabilityProviderTests.java @@ -22,8 +22,7 @@ import org.springframework.core.io.DefaultResourceLoader; import org.springframework.core.io.ResourceLoader; import org.springframework.mock.env.MockEnvironment; -import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link JspTemplateAvailabilityProvider}. @@ -40,14 +39,14 @@ public class JspTemplateAvailabilityProviderTests { @Test public void availabilityOfTemplateThatDoesNotExist() { - assertThat(isTemplateAvailable("whatever"), equalTo(false)); + assertThat(isTemplateAvailable("whatever")).isFalse(); } @Test public void availabilityOfTemplateWithCustomPrefix() { this.environment.setProperty("spring.mvc.view.prefix", "classpath:/custom-templates/"); - assertThat(isTemplateAvailable("custom.jsp"), equalTo(true)); + assertThat(isTemplateAvailable("custom.jsp")).isTrue(); } @Test @@ -55,7 +54,7 @@ public class JspTemplateAvailabilityProviderTests { this.environment.setProperty("spring.mvc.view.prefix", "classpath:/custom-templates/"); this.environment.setProperty("spring.mvc.view.suffix", ".jsp"); - assertThat(isTemplateAvailable("suffixed"), equalTo(true)); + assertThat(isTemplateAvailable("suffixed")).isTrue(); } private boolean isTemplateAvailable(String view) { diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/MultipartAutoConfigurationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/MultipartAutoConfigurationTests.java index fd4ca2638a..09fc537ee3 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/MultipartAutoConfigurationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/MultipartAutoConfigurationTests.java @@ -50,14 +50,7 @@ import org.springframework.web.multipart.support.StandardServletMultipartResolve import org.springframework.web.servlet.DispatcherServlet; import org.springframework.web.servlet.config.annotation.EnableWebMvc; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.instanceOf; -import static org.hamcrest.Matchers.not; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; /** @@ -89,11 +82,10 @@ public class MultipartAutoConfigurationTests { ContainerWithNothing.class, BaseConfiguration.class); DispatcherServlet servlet = this.context.getBean(DispatcherServlet.class); verify404(); - assertNotNull(servlet.getMultipartResolver()); - assertThat(this.context.getBeansOfType(StandardServletMultipartResolver.class) - .size(), equalTo(1)); - assertThat(this.context.getBeansOfType(MultipartResolver.class).size(), - equalTo(1)); + assertThat(servlet.getMultipartResolver()).isNotNull(); + assertThat(this.context.getBeansOfType(StandardServletMultipartResolver.class)) + .hasSize(1); + assertThat(this.context.getBeansOfType(MultipartResolver.class)).hasSize(1); } @Test @@ -101,11 +93,10 @@ public class MultipartAutoConfigurationTests { this.context = new AnnotationConfigEmbeddedWebApplicationContext( ContainerWithNoMultipartJetty.class, BaseConfiguration.class); DispatcherServlet servlet = this.context.getBean(DispatcherServlet.class); - assertNotNull(servlet.getMultipartResolver()); - assertThat(this.context.getBeansOfType(StandardServletMultipartResolver.class) - .size(), equalTo(1)); - assertThat(this.context.getBeansOfType(MultipartResolver.class).size(), - equalTo(1)); + assertThat(servlet.getMultipartResolver()).isNotNull(); + assertThat(this.context.getBeansOfType(StandardServletMultipartResolver.class)) + .hasSize(1); + assertThat(this.context.getBeansOfType(MultipartResolver.class)).hasSize(1); verifyServletWorks(); } @@ -115,11 +106,10 @@ public class MultipartAutoConfigurationTests { ContainerWithNoMultipartUndertow.class, BaseConfiguration.class); DispatcherServlet servlet = this.context.getBean(DispatcherServlet.class); verifyServletWorks(); - assertNotNull(servlet.getMultipartResolver()); - assertThat(this.context.getBeansOfType(StandardServletMultipartResolver.class) - .size(), equalTo(1)); - assertThat(this.context.getBeansOfType(MultipartResolver.class).size(), - equalTo(1)); + assertThat(servlet.getMultipartResolver()).isNotNull(); + assertThat(this.context.getBeansOfType(StandardServletMultipartResolver.class)) + .hasSize(1); + assertThat(this.context.getBeansOfType(MultipartResolver.class)).hasSize(1); } @Test @@ -127,11 +117,10 @@ public class MultipartAutoConfigurationTests { this.context = new AnnotationConfigEmbeddedWebApplicationContext( ContainerWithNoMultipartTomcat.class, BaseConfiguration.class); DispatcherServlet servlet = this.context.getBean(DispatcherServlet.class); - assertNull(servlet.getMultipartResolver()); - assertThat(this.context.getBeansOfType(StandardServletMultipartResolver.class) - .size(), equalTo(1)); - assertThat(this.context.getBeansOfType(MultipartResolver.class).size(), - equalTo(1)); + assertThat(servlet.getMultipartResolver()).isNull(); + assertThat(this.context.getBeansOfType(StandardServletMultipartResolver.class)) + .hasSize(1); + assertThat(this.context.getBeansOfType(MultipartResolver.class)).hasSize(1); verifyServletWorks(); } @@ -140,8 +129,8 @@ public class MultipartAutoConfigurationTests { this.context = new AnnotationConfigEmbeddedWebApplicationContext( ContainerWithEverythingJetty.class, BaseConfiguration.class); this.context.getBean(MultipartConfigElement.class); - assertSame(this.context.getBean(DispatcherServlet.class).getMultipartResolver(), - this.context.getBean(StandardServletMultipartResolver.class)); + assertThat(this.context.getBean(StandardServletMultipartResolver.class)).isSameAs( + this.context.getBean(DispatcherServlet.class).getMultipartResolver()); verifyServletWorks(); } @@ -153,8 +142,8 @@ public class MultipartAutoConfigurationTests { + this.context.getEmbeddedServletContainer().getPort() + "/", String.class); this.context.getBean(MultipartConfigElement.class); - assertSame(this.context.getBean(DispatcherServlet.class).getMultipartResolver(), - this.context.getBean(StandardServletMultipartResolver.class)); + assertThat(this.context.getBean(StandardServletMultipartResolver.class)).isSameAs( + this.context.getBean(DispatcherServlet.class).getMultipartResolver()); verifyServletWorks(); } @@ -164,8 +153,8 @@ public class MultipartAutoConfigurationTests { ContainerWithEverythingUndertow.class, BaseConfiguration.class); this.context.getBean(MultipartConfigElement.class); verifyServletWorks(); - assertSame(this.context.getBean(DispatcherServlet.class).getMultipartResolver(), - this.context.getBean(StandardServletMultipartResolver.class)); + assertThat(this.context.getBean(StandardServletMultipartResolver.class)).isSameAs( + this.context.getBean(DispatcherServlet.class).getMultipartResolver()); } @Test @@ -189,8 +178,8 @@ public class MultipartAutoConfigurationTests { BaseConfiguration.class); this.context.refresh(); this.context.getBean(MultipartProperties.class); - assertEquals(expectedNumberOfMultipartConfigElementBeans, - this.context.getBeansOfType(MultipartConfigElement.class).size()); + assertThat(this.context.getBeansOfType(MultipartConfigElement.class)) + .hasSize(expectedNumberOfMultipartConfigElementBeans); } @Test @@ -199,8 +188,8 @@ public class MultipartAutoConfigurationTests { ContainerWithCustomMultipartResolver.class, BaseConfiguration.class); MultipartResolver multipartResolver = this.context .getBean(MultipartResolver.class); - assertThat(multipartResolver, - not(instanceOf(StandardServletMultipartResolver.class))); + assertThat(multipartResolver) + .isNotInstanceOf(StandardServletMultipartResolver.class); } private void verify404() throws Exception { @@ -210,17 +199,14 @@ public class MultipartAutoConfigurationTests { + this.context.getEmbeddedServletContainer().getPort() + "/"), HttpMethod.GET); ClientHttpResponse response = request.execute(); - assertEquals(HttpStatus.NOT_FOUND, response.getStatusCode()); + assertThat(response.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND); } private void verifyServletWorks() { RestTemplate restTemplate = new RestTemplate(); - assertEquals("Hello", - restTemplate - .getForObject( - "http://localhost:" + this.context - .getEmbeddedServletContainer().getPort() + "/", - String.class)); + String url = "http://localhost:" + + this.context.getEmbeddedServletContainer().getPort() + "/"; + assertThat(restTemplate.getForObject(url, String.class)).isEqualTo("Hello"); } @Configuration diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/NonRecursivePropertyPlaceholderHelperTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/NonRecursivePropertyPlaceholderHelperTests.java index dfcf27393e..7072605c71 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/NonRecursivePropertyPlaceholderHelperTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/NonRecursivePropertyPlaceholderHelperTests.java @@ -20,8 +20,7 @@ import java.util.Properties; 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 NonRecursivePropertyPlaceholderHelper}. @@ -38,7 +37,7 @@ public class NonRecursivePropertyPlaceholderHelperTests { Properties properties = new Properties(); properties.put("a", "b"); String result = this.helper.replacePlaceholders("${a}", properties); - assertThat(result, equalTo("b")); + assertThat(result).isEqualTo("b"); } @Test @@ -47,7 +46,7 @@ public class NonRecursivePropertyPlaceholderHelperTests { properties.put("a", "${b}"); properties.put("b", "c"); String result = this.helper.replacePlaceholders("${a}", properties); - assertThat(result, equalTo("${b}")); + assertThat(result).isEqualTo("${b}"); } } diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/RemappedErrorViewIntegrationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/RemappedErrorViewIntegrationTests.java index a168e46082..aad0390c39 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/RemappedErrorViewIntegrationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/RemappedErrorViewIntegrationTests.java @@ -38,7 +38,7 @@ import org.springframework.test.context.web.WebAppConfiguration; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.client.RestTemplate; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Dave Syer @@ -59,16 +59,16 @@ public class RemappedErrorViewIntegrationTests { public void directAccessToErrorPage() throws Exception { String content = this.template.getForObject( "http://localhost:" + this.port + "/spring/error", String.class); - assertTrue("Wrong content: " + content, content.contains("error")); - assertTrue("Wrong content: " + content, content.contains("999")); + assertThat(content).contains("error"); + assertThat(content).contains("999"); } @Test public void forwardToErrorPage() throws Exception { String content = this.template .getForObject("http://localhost:" + this.port + "/spring/", String.class); - assertTrue("Wrong content: " + content, content.contains("error")); - assertTrue("Wrong content: " + content, content.contains("500")); + assertThat(content).contains("error"); + assertThat(content).contains("500"); } @Configuration diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/ResourcePropertiesTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/ResourcePropertiesTests.java old mode 100755 new mode 100644 index cdd5437ed7..f855ca9e3e --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/ResourcePropertiesTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/ResourcePropertiesTests.java @@ -18,8 +18,6 @@ package org.springframework.boot.autoconfigure.web; import org.junit.Test; -import static org.hamcrest.CoreMatchers.nullValue; -import static org.hamcrest.Matchers.equalTo; import static org.assertj.core.api.Assertions.assertThat; /** @@ -34,25 +32,25 @@ public class ResourcePropertiesTests { @Test public void resourceChainNoCustomization() { System.out.println(this.properties.getChain().getEnabled()); - assertThat(this.properties.getChain().getEnabled(), nullValue()); + assertThat(this.properties.getChain().getEnabled()).isNull(); } @Test public void resourceChainStrategyEnabled() { this.properties.getChain().getStrategy().getFixed().setEnabled(true); - assertThat(this.properties.getChain().getEnabled(), equalTo(true)); + assertThat(this.properties.getChain().getEnabled()).isTrue(); } @Test public void resourceChainEnabled() { this.properties.getChain().setEnabled(true); - assertThat(this.properties.getChain().getEnabled(), equalTo(true)); + assertThat(this.properties.getChain().getEnabled()).isTrue(); } @Test public void resourceChainDisabled() { this.properties.getChain().setEnabled(false); - assertThat(this.properties.getChain().getEnabled(), equalTo(false)); + assertThat(this.properties.getChain().getEnabled()).isFalse(); } } diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/ServerPropertiesAutoConfigurationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/ServerPropertiesAutoConfigurationTests.java index 31f3c3332d..adc8d4d89d 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/ServerPropertiesAutoConfigurationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/ServerPropertiesAutoConfigurationTests.java @@ -39,8 +39,7 @@ import org.springframework.context.ApplicationContextException; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; @@ -79,8 +78,8 @@ public class ServerPropertiesAutoConfigurationTests { EnvironmentTestUtils.addEnvironment(this.context, "server.port:9000"); this.context.refresh(); ServerProperties server = this.context.getBean(ServerProperties.class); - assertNotNull(server); - assertEquals(9000, server.getPort().intValue()); + assertThat(server).isNotNull(); + assertThat(server.getPort().intValue()).isEqualTo(9000); verify(containerFactory).setPort(9000); } @@ -94,8 +93,8 @@ public class ServerPropertiesAutoConfigurationTests { "server.tomcat.basedir:target/foo", "server.port:9000"); this.context.refresh(); ServerProperties server = this.context.getBean(ServerProperties.class); - assertNotNull(server); - assertEquals(new File("target/foo"), server.getTomcat().getBasedir()); + assertThat(server).isNotNull(); + assertThat(server.getTomcat().getBasedir()).isEqualTo(new File("target/foo")); verify(containerFactory).setPort(9000); } @@ -109,10 +108,10 @@ public class ServerPropertiesAutoConfigurationTests { containerFactory = this.context .getBean(AbstractEmbeddedServletContainerFactory.class); ServerProperties server = this.context.getBean(ServerProperties.class); - assertNotNull(server); + assertThat(server).isNotNull(); // The server.port environment property was not explicitly set so the container // factory should take precedence... - assertEquals(3000, containerFactory.getPort()); + assertThat(containerFactory.getPort()).isEqualTo(3000); } @Test @@ -125,8 +124,8 @@ public class ServerPropertiesAutoConfigurationTests { containerFactory = this.context .getBean(AbstractEmbeddedServletContainerFactory.class); ServerProperties server = this.context.getBean(ServerProperties.class); - assertNotNull(server); - assertEquals(3000, containerFactory.getPort()); + assertThat(server).isNotNull(); + assertThat(containerFactory.getPort()).isEqualTo(3000); } @Test @@ -138,7 +137,7 @@ public class ServerPropertiesAutoConfigurationTests { PropertyPlaceholderAutoConfiguration.class); this.context.refresh(); ServerProperties server = this.context.getBean(ServerProperties.class); - assertNotNull(server); + assertThat(server).isNotNull(); // The server.port environment property was not explicitly set so the container // customizer should take precedence... verify(containerFactory).setPort(3000); diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/ServerPropertiesTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/ServerPropertiesTests.java index a12f8fb3a4..185bb702ba 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/ServerPropertiesTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/ServerPropertiesTests.java @@ -46,12 +46,7 @@ import org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletCon import org.springframework.boot.context.embedded.undertow.UndertowEmbeddedServletContainerFactory; import org.springframework.mock.env.MockEnvironment; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.instanceOf; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNull; -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.atLeastOnce; import static org.mockito.Mockito.mock; @@ -85,20 +80,21 @@ public class ServerPropertiesTests { RelaxedDataBinder binder = new RelaxedDataBinder(this.properties, "server"); binder.bind(new MutablePropertyValues( Collections.singletonMap("server.address", "127.0.0.1"))); - assertFalse(binder.getBindingResult().hasErrors()); - assertEquals(InetAddress.getByName("127.0.0.1"), this.properties.getAddress()); + assertThat(binder.getBindingResult().hasErrors()).isFalse(); + assertThat(this.properties.getAddress()) + .isEqualTo(InetAddress.getByName("127.0.0.1")); } @Test public void testPortBinding() throws Exception { new RelaxedDataBinder(this.properties, "server").bind(new MutablePropertyValues( Collections.singletonMap("server.port", "9000"))); - assertEquals(9000, this.properties.getPort().intValue()); + assertThat(this.properties.getPort().intValue()).isEqualTo(9000); } @Test public void testServerHeaderDefault() throws Exception { - assertNull(this.properties.getServerHeader()); + assertThat(this.properties.getServerHeader()).isNull(); } @Test @@ -106,7 +102,7 @@ public class ServerPropertiesTests { RelaxedDataBinder binder = new RelaxedDataBinder(this.properties, "server"); binder.bind(new MutablePropertyValues( Collections.singletonMap("server.server-header", "Custom Server"))); - assertEquals("Custom Server", this.properties.getServerHeader()); + assertThat(this.properties.getServerHeader()).isEqualTo("Custom Server"); } @Test @@ -114,9 +110,9 @@ public class ServerPropertiesTests { RelaxedDataBinder binder = new RelaxedDataBinder(this.properties, "server"); binder.bind(new MutablePropertyValues( Collections.singletonMap("server.servletPath", "/foo/*"))); - assertFalse(binder.getBindingResult().hasErrors()); - assertEquals("/foo/*", this.properties.getServletMapping()); - assertEquals("/foo", this.properties.getServletPrefix()); + assertThat(binder.getBindingResult().hasErrors()).isFalse(); + assertThat(this.properties.getServletMapping()).isEqualTo("/foo/*"); + assertThat(this.properties.getServletPrefix()).isEqualTo("/foo"); } @Test @@ -124,9 +120,9 @@ public class ServerPropertiesTests { RelaxedDataBinder binder = new RelaxedDataBinder(this.properties, "server"); binder.bind(new MutablePropertyValues( Collections.singletonMap("server.servletPath", "/foo"))); - assertFalse(binder.getBindingResult().hasErrors()); - assertEquals("/foo/*", this.properties.getServletMapping()); - assertEquals("/foo", this.properties.getServletPrefix()); + assertThat(binder.getBindingResult().hasErrors()).isFalse(); + assertThat(this.properties.getServletMapping()).isEqualTo("/foo/*"); + assertThat(this.properties.getServletPrefix()).isEqualTo("/foo"); } @Test @@ -140,26 +136,27 @@ public class ServerPropertiesTests { map.put("server.tomcat.internal_proxies", "10\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}"); bindProperties(map); ServerProperties.Tomcat tomcat = this.properties.getTomcat(); - assertEquals("%h %t '%r' %s %b", tomcat.getAccesslog().getPattern()); - assertEquals("foo", tomcat.getAccesslog().getPrefix()); - assertEquals("-bar.log", tomcat.getAccesslog().getSuffix()); - assertEquals("Remote-Ip", tomcat.getRemoteIpHeader()); - assertEquals("X-Forwarded-Protocol", tomcat.getProtocolHeader()); - assertEquals("10\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}", tomcat.getInternalProxies()); + assertThat(tomcat.getAccesslog().getPattern()).isEqualTo("%h %t '%r' %s %b"); + assertThat(tomcat.getAccesslog().getPrefix()).isEqualTo("foo"); + assertThat(tomcat.getAccesslog().getSuffix()).isEqualTo("-bar.log"); + assertThat(tomcat.getRemoteIpHeader()).isEqualTo("Remote-Ip"); + assertThat(tomcat.getProtocolHeader()).isEqualTo("X-Forwarded-Protocol"); + assertThat(tomcat.getInternalProxies()) + .isEqualTo("10\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}"); } @Test public void testTrailingSlashOfContextPathIsRemoved() { new RelaxedDataBinder(this.properties, "server").bind(new MutablePropertyValues( Collections.singletonMap("server.contextPath", "/foo/"))); - assertThat(this.properties.getContextPath(), equalTo("/foo")); + assertThat(this.properties.getContextPath()).isEqualTo("/foo"); } @Test public void testSlashOfContextPathIsDefaultValue() { new RelaxedDataBinder(this.properties, "server").bind(new MutablePropertyValues( Collections.singletonMap("server.contextPath", "/"))); - assertThat(this.properties.getContextPath(), equalTo("")); + assertThat(this.properties.getContextPath()).isEqualTo(""); } @Test @@ -249,8 +246,8 @@ public class ServerPropertiesTests { Map map = new HashMap(); map.put("server.tomcat.uriEncoding", "US-ASCII"); bindProperties(map); - assertEquals(Charset.forName("US-ASCII"), - this.properties.getTomcat().getUriEncoding()); + assertThat(this.properties.getTomcat().getUriEncoding()) + .isEqualTo(Charset.forName("US-ASCII")); } @Test @@ -258,7 +255,7 @@ public class ServerPropertiesTests { Map map = new HashMap(); map.put("server.tomcat.maxHttpHeaderSize", "9999"); bindProperties(map); - assertEquals(9999, this.properties.getTomcat().getMaxHttpHeaderSize()); + assertThat(this.properties.getTomcat().getMaxHttpHeaderSize()).isEqualTo(9999); } @Test @@ -268,7 +265,7 @@ public class ServerPropertiesTests { bindProperties(map); TomcatEmbeddedServletContainerFactory container = new TomcatEmbeddedServletContainerFactory(); this.properties.customize(container); - assertEquals("MyBootApp", container.getDisplayName()); + assertThat(container.getDisplayName()).isEqualTo("MyBootApp"); } @Test @@ -279,7 +276,7 @@ public class ServerPropertiesTests { bindProperties(map); TomcatEmbeddedServletContainerFactory container = new TomcatEmbeddedServletContainerFactory(); this.properties.customize(container); - assertEquals(0, container.getValves().size()); + assertThat(container.getValves()).isEmpty(); } @Test @@ -308,13 +305,13 @@ public class ServerPropertiesTests { private void testRemoteIpValveConfigured() { TomcatEmbeddedServletContainerFactory container = new TomcatEmbeddedServletContainerFactory(); this.properties.customize(container); - assertEquals(1, container.getValves().size()); + assertThat(container.getValves()).hasSize(1); Valve valve = container.getValves().iterator().next(); - assertThat(valve, instanceOf(RemoteIpValve.class)); + assertThat(valve).isInstanceOf(RemoteIpValve.class); RemoteIpValve remoteIpValve = (RemoteIpValve) valve; - assertEquals("X-Forwarded-Proto", remoteIpValve.getProtocolHeader()); - assertEquals("https", remoteIpValve.getProtocolHeaderHttpsValue()); - assertEquals("X-Forwarded-For", remoteIpValve.getRemoteIpHeader()); + assertThat(remoteIpValve.getProtocolHeader()).isEqualTo("X-Forwarded-Proto"); + assertThat(remoteIpValve.getProtocolHeaderHttpsValue()).isEqualTo("https"); + assertThat(remoteIpValve.getRemoteIpHeader()).isEqualTo("X-Forwarded-For"); String expectedInternalProxies = "10\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}|" // 10/8 + "192\\.168\\.\\d{1,3}\\.\\d{1,3}|" // 192.168/16 + "169\\.254\\.\\d{1,3}\\.\\d{1,3}|" // 169.254/16 @@ -322,7 +319,7 @@ public class ServerPropertiesTests { + "172\\.1[6-9]{1}\\.\\d{1,3}\\.\\d{1,3}|" // 172.16/12 + "172\\.2[0-9]{1}\\.\\d{1,3}\\.\\d{1,3}|" + "172\\.3[0-1]{1}\\.\\d{1,3}\\.\\d{1,3}"; - assertEquals(expectedInternalProxies, remoteIpValve.getInternalProxies()); + assertThat(remoteIpValve.getInternalProxies()).isEqualTo(expectedInternalProxies); } @Test @@ -338,15 +335,15 @@ public class ServerPropertiesTests { TomcatEmbeddedServletContainerFactory container = new TomcatEmbeddedServletContainerFactory(); this.properties.customize(container); - assertEquals(1, container.getValves().size()); + assertThat(container.getValves()).hasSize(1); Valve valve = container.getValves().iterator().next(); - assertThat(valve, instanceOf(RemoteIpValve.class)); + assertThat(valve).isInstanceOf(RemoteIpValve.class); RemoteIpValve remoteIpValve = (RemoteIpValve) valve; - assertEquals("x-my-protocol-header", remoteIpValve.getProtocolHeader()); - assertEquals("On", remoteIpValve.getProtocolHeaderHttpsValue()); - assertEquals("x-my-remote-ip-header", remoteIpValve.getRemoteIpHeader()); - assertEquals("x-my-forward-port", remoteIpValve.getPortHeader()); - assertEquals("192.168.0.1", remoteIpValve.getInternalProxies()); + assertThat(remoteIpValve.getProtocolHeader()).isEqualTo("x-my-protocol-header"); + assertThat(remoteIpValve.getProtocolHeaderHttpsValue()).isEqualTo("On"); + assertThat(remoteIpValve.getRemoteIpHeader()).isEqualTo("x-my-remote-ip-header"); + assertThat(remoteIpValve.getPortHeader()).isEqualTo("x-my-forward-port"); + assertThat(remoteIpValve.getInternalProxies()).isEqualTo("192.168.0.1"); } @Test diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/WebMvcAutoConfigurationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/WebMvcAutoConfigurationTests.java index 410d638e38..d378e77ce3 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/WebMvcAutoConfigurationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/WebMvcAutoConfigurationTests.java @@ -28,7 +28,6 @@ import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; -import org.hamcrest.Matcher; import org.joda.time.DateTime; import org.junit.After; import org.junit.Rule; @@ -80,18 +79,7 @@ import org.springframework.web.servlet.resource.VersionResourceResolver; import org.springframework.web.servlet.view.AbstractView; import org.springframework.web.servlet.view.ContentNegotiatingViewResolver; -import static org.hamcrest.Matchers.contains; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.instanceOf; -import static org.hamcrest.Matchers.is; -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.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; /** * Tests for {@link WebMvcAutoConfiguration}. @@ -122,78 +110,77 @@ public class WebMvcAutoConfigurationTests { @Test public void handlerAdaptersCreated() throws Exception { load(); - assertEquals(3, this.context.getBeanNamesForType(HandlerAdapter.class).length); - assertFalse(this.context.getBean(RequestMappingHandlerAdapter.class) - .getMessageConverters().isEmpty()); - assertEquals(this.context.getBean(HttpMessageConverters.class).getConverters(), - this.context.getBean(RequestMappingHandlerAdapter.class) - .getMessageConverters()); + assertThat(this.context.getBeanNamesForType(HandlerAdapter.class).length) + .isEqualTo(3); + assertThat(this.context.getBean(RequestMappingHandlerAdapter.class) + .getMessageConverters()).isNotEmpty() + .isEqualTo(this.context.getBean(HttpMessageConverters.class) + .getConverters()); } @Test public void handlerMappingsCreated() throws Exception { load(); - assertEquals(6, this.context.getBeanNamesForType(HandlerMapping.class).length); + assertThat(this.context.getBeanNamesForType(HandlerMapping.class).length) + .isEqualTo(6); } @Test public void resourceHandlerMapping() throws Exception { load(); Map> mappingLocations = getResourceMappingLocations(); - assertThat(mappingLocations.get("/**").size(), equalTo(5)); - assertThat(mappingLocations.get("/webjars/**").size(), equalTo(1)); - assertThat(mappingLocations.get("/webjars/**").get(0), equalTo( - (Resource) new ClassPathResource("/META-INF/resources/webjars/"))); - assertThat(getResourceResolvers("/webjars/**").size(), equalTo(1)); - assertThat(getResourceTransformers("/webjars/**").size(), equalTo(0)); - assertThat(getResourceResolvers("/**").size(), equalTo(1)); - assertThat(getResourceTransformers("/**").size(), equalTo(0)); + assertThat(mappingLocations.get("/**")).hasSize(5); + assertThat(mappingLocations.get("/webjars/**")).hasSize(1); + assertThat(mappingLocations.get("/webjars/**").get(0)) + .isEqualTo(new ClassPathResource("/META-INF/resources/webjars/")); + assertThat(getResourceResolvers("/webjars/**")).hasSize(1); + assertThat(getResourceTransformers("/webjars/**")).hasSize(0); + assertThat(getResourceResolvers("/**")).hasSize(1); + assertThat(getResourceTransformers("/**")).hasSize(0); } @Test public void customResourceHandlerMapping() throws Exception { load("spring.mvc.static-path-pattern:/static/**"); Map> mappingLocations = getResourceMappingLocations(); - assertThat(mappingLocations.get("/static/**").size(), equalTo(5)); - assertThat(getResourceResolvers("/static/**").size(), equalTo(1)); + assertThat(mappingLocations.get("/static/**")).hasSize(5); + assertThat(getResourceResolvers("/static/**")).hasSize(1); } @Test public void resourceHandlerMappingOverrideWebjars() throws Exception { load(WebJars.class); Map> mappingLocations = getResourceMappingLocations(); - assertThat(mappingLocations.get("/webjars/**").size(), equalTo(1)); - assertThat(mappingLocations.get("/webjars/**").get(0), - equalTo((Resource) new ClassPathResource("/foo/"))); + assertThat(mappingLocations.get("/webjars/**")).hasSize(1); + assertThat(mappingLocations.get("/webjars/**").get(0)) + .isEqualTo(new ClassPathResource("/foo/")); } @Test public void resourceHandlerMappingOverrideAll() throws Exception { load(AllResources.class); Map> mappingLocations = getResourceMappingLocations(); - assertThat(mappingLocations.get("/**").size(), equalTo(1)); - assertThat(mappingLocations.get("/**").get(0), - equalTo((Resource) new ClassPathResource("/foo/"))); + assertThat(mappingLocations.get("/**")).hasSize(1); + assertThat(mappingLocations.get("/**").get(0)) + .isEqualTo(new ClassPathResource("/foo/")); } @Test public void resourceHandlerMappingDisabled() throws Exception { load("spring.resources.add-mappings:false"); Map> mappingLocations = getResourceMappingLocations(); - assertThat(mappingLocations.size(), equalTo(0)); + assertThat(mappingLocations.size()).isEqualTo(0); } @Test public void resourceHandlerChainEnabled() throws Exception { load("spring.resources.chain.enabled:true"); - assertThat(getResourceResolvers("/webjars/**").size(), equalTo(2)); - assertThat(getResourceTransformers("/webjars/**").size(), equalTo(1)); - assertThat(getResourceResolvers("/**").size(), equalTo(2)); - assertThat(getResourceTransformers("/**").size(), equalTo(1)); - assertThat(getResourceResolvers("/**"), containsInstances( - CachingResourceResolver.class, PathResourceResolver.class)); - assertThat(getResourceTransformers("/**"), - contains(instanceOf(CachingResourceTransformer.class))); + assertThat(getResourceResolvers("/webjars/**")).hasSize(2); + assertThat(getResourceTransformers("/webjars/**")).hasSize(1); + assertThat(getResourceResolvers("/**")).extractingResultOf("getClass") + .containsOnly(CachingResourceResolver.class, PathResourceResolver.class); + assertThat(getResourceTransformers("/**")).extractingResultOf("getClass") + .containsOnly(CachingResourceTransformer.class); } @Test @@ -201,38 +188,36 @@ public class WebMvcAutoConfigurationTests { load("spring.resources.chain.strategy.fixed.enabled:true", "spring.resources.chain.strategy.fixed.version:test", "spring.resources.chain.strategy.fixed.paths:/**/*.js"); - assertThat(getResourceResolvers("/webjars/**").size(), equalTo(3)); - assertThat(getResourceTransformers("/webjars/**").size(), equalTo(2)); - assertThat(getResourceResolvers("/**").size(), equalTo(3)); - assertThat(getResourceTransformers("/**").size(), equalTo(2)); - assertThat(getResourceResolvers("/**"), - containsInstances(CachingResourceResolver.class, - VersionResourceResolver.class, PathResourceResolver.class)); - assertThat(getResourceTransformers("/**"), containsInstances( - CachingResourceTransformer.class, CssLinkResourceTransformer.class)); + assertThat(getResourceResolvers("/webjars/**")).hasSize(3); + assertThat(getResourceTransformers("/webjars/**")).hasSize(2); + assertThat(getResourceResolvers("/**")).extractingResultOf("getClass") + .containsOnly(CachingResourceResolver.class, + VersionResourceResolver.class, PathResourceResolver.class); + assertThat(getResourceTransformers("/**")).extractingResultOf("getClass") + .containsOnly(CachingResourceTransformer.class, + CssLinkResourceTransformer.class); VersionResourceResolver resolver = (VersionResourceResolver) getResourceResolvers( "/**").get(1); - assertThat(resolver.getStrategyMap().get("/**/*.js"), - instanceOf(FixedVersionStrategy.class)); + assertThat(resolver.getStrategyMap().get("/**/*.js")) + .isInstanceOf(FixedVersionStrategy.class); } @Test public void resourceHandlerContentStrategyEnabled() throws Exception { load("spring.resources.chain.strategy.content.enabled:true", "spring.resources.chain.strategy.content.paths:/**,/*.png"); - assertThat(getResourceResolvers("/webjars/**").size(), equalTo(3)); - assertThat(getResourceTransformers("/webjars/**").size(), equalTo(2)); - assertThat(getResourceResolvers("/**").size(), equalTo(3)); - assertThat(getResourceTransformers("/**").size(), equalTo(2)); - assertThat(getResourceResolvers("/**"), - containsInstances(CachingResourceResolver.class, - VersionResourceResolver.class, PathResourceResolver.class)); - assertThat(getResourceTransformers("/**"), containsInstances( - CachingResourceTransformer.class, CssLinkResourceTransformer.class)); + assertThat(getResourceResolvers("/webjars/**")).hasSize(3); + assertThat(getResourceTransformers("/webjars/**")).hasSize(2); + assertThat(getResourceResolvers("/**")).extractingResultOf("getClass") + .containsOnly(CachingResourceResolver.class, + VersionResourceResolver.class, PathResourceResolver.class); + assertThat(getResourceTransformers("/**")).extractingResultOf("getClass") + .containsOnly(CachingResourceTransformer.class, + CssLinkResourceTransformer.class); VersionResourceResolver resolver = (VersionResourceResolver) getResourceResolvers( "/**").get(1); - assertThat(resolver.getStrategyMap().get("/*.png"), - instanceOf(ContentVersionStrategy.class)); + assertThat(resolver.getStrategyMap().get("/*.png")) + .isInstanceOf(ContentVersionStrategy.class); } @Test @@ -244,20 +229,19 @@ public class WebMvcAutoConfigurationTests { "spring.resources.chain.strategy.fixed.version:test", "spring.resources.chain.strategy.fixed.paths:/**/*.js", "spring.resources.chain.html-application-cache:true"); - assertThat(getResourceResolvers("/webjars/**").size(), equalTo(2)); - assertThat(getResourceTransformers("/webjars/**").size(), equalTo(2)); - assertThat(getResourceResolvers("/**").size(), equalTo(2)); - assertThat(getResourceTransformers("/**").size(), equalTo(2)); - assertThat(getResourceResolvers("/**"), containsInstances( - VersionResourceResolver.class, PathResourceResolver.class)); - assertThat(getResourceTransformers("/**"), containsInstances( - CssLinkResourceTransformer.class, AppCacheManifestTransformer.class)); + assertThat(getResourceResolvers("/webjars/**")).hasSize(2); + assertThat(getResourceTransformers("/webjars/**")).hasSize(2); + assertThat(getResourceResolvers("/**")).extractingResultOf("getClass") + .containsOnly(VersionResourceResolver.class, PathResourceResolver.class); + assertThat(getResourceTransformers("/**")).extractingResultOf("getClass") + .containsOnly(CssLinkResourceTransformer.class, + AppCacheManifestTransformer.class); VersionResourceResolver resolver = (VersionResourceResolver) getResourceResolvers( "/**").get(0); - assertThat(resolver.getStrategyMap().get("/*.png"), - instanceOf(ContentVersionStrategy.class)); - assertThat(resolver.getStrategyMap().get("/**/*.js"), - instanceOf(FixedVersionStrategy.class)); + assertThat(resolver.getStrategyMap().get("/*.png")) + .isInstanceOf(ContentVersionStrategy.class); + assertThat(resolver.getStrategyMap().get("/**/*.js")) + .isInstanceOf(FixedVersionStrategy.class); } @Test @@ -270,15 +254,14 @@ public class WebMvcAutoConfigurationTests { @Test public void overrideLocale() throws Exception { load(AllResources.class, "spring.mvc.locale:en_UK"); - // mock request and set user preferred locale MockHttpServletRequest request = new MockHttpServletRequest(); request.addPreferredLocale(StringUtils.parseLocaleString("nl_NL")); LocaleResolver localeResolver = this.context.getBean(LocaleResolver.class); Locale locale = localeResolver.resolveLocale(request); - assertThat(localeResolver, instanceOf(FixedLocaleResolver.class)); + assertThat(localeResolver).isInstanceOf(FixedLocaleResolver.class); // test locale resolver uses fixed locale and not user preferred locale - assertThat(locale.toString(), equalTo("en_UK")); + assertThat(locale.toString()).isEqualTo("en_UK"); } @Test @@ -288,7 +271,7 @@ public class WebMvcAutoConfigurationTests { .getBean(FormattingConversionService.class); Date date = new DateTime(1988, 6, 25, 20, 30).toDate(); // formatting cs should use simple toString() - assertThat(cs.convert(date, String.class), equalTo(date.toString())); + assertThat(cs.convert(date, String.class)).isEqualTo(date.toString()); } @Test @@ -297,22 +280,22 @@ public class WebMvcAutoConfigurationTests { FormattingConversionService cs = this.context .getBean(FormattingConversionService.class); Date date = new DateTime(1988, 6, 25, 20, 30).toDate(); - assertThat(cs.convert(date, String.class), equalTo("25*06*1988")); + assertThat(cs.convert(date, String.class)).isEqualTo("25*06*1988"); } @Test public void noMessageCodesResolver() throws Exception { load(AllResources.class); - assertNull(this.context.getBean(WebMvcAutoConfigurationAdapter.class) - .getMessageCodesResolver()); + assertThat(this.context.getBean(WebMvcAutoConfigurationAdapter.class) + .getMessageCodesResolver()).isNull(); } @Test public void overrideMessageCodesFormat() throws Exception { load(AllResources.class, "spring.mvc.messageCodesResolverFormat:POSTFIX_ERROR_CODE"); - assertNotNull(this.context.getBean(WebMvcAutoConfigurationAdapter.class) - .getMessageCodesResolver()); + assertThat(this.context.getBean(WebMvcAutoConfigurationAdapter.class) + .getMessageCodesResolver()).isNotNull(); } protected Map> getFaviconMappingLocations() @@ -369,8 +352,8 @@ public class WebMvcAutoConfigurationTests { load(); RequestMappingHandlerAdapter adapter = this.context .getBean(RequestMappingHandlerAdapter.class); - assertEquals(true, - ReflectionTestUtils.getField(adapter, "ignoreDefaultModelOnRedirect")); + assertThat(adapter).extracting("ignoreDefaultModelOnRedirect") + .containsExactly(true); } @Test @@ -384,15 +367,15 @@ public class WebMvcAutoConfigurationTests { this.context.refresh(); RequestMappingHandlerAdapter adapter = this.context .getBean(RequestMappingHandlerAdapter.class); - assertEquals(false, - ReflectionTestUtils.getField(adapter, "ignoreDefaultModelOnRedirect")); + assertThat(adapter).extracting("ignoreDefaultModelOnRedirect") + .containsExactly(false); } @Test public void customViewResolver() throws Exception { load(CustomViewResolver.class); - assertThat(this.context.getBean("viewResolver"), - instanceOf(MyViewResolver.class)); + assertThat(this.context.getBean("viewResolver")) + .isInstanceOf(MyViewResolver.class); } @Test @@ -400,28 +383,28 @@ public class WebMvcAutoConfigurationTests { load(CustomContentNegotiatingViewResolver.class); Map beans = this.context .getBeansOfType(ContentNegotiatingViewResolver.class); - assertThat(beans.size(), equalTo(1)); - assertThat(beans.keySet().iterator().next(), equalTo("myViewResolver")); + assertThat(beans.size()).isEqualTo(1); + assertThat(beans.keySet().iterator().next()).isEqualTo("myViewResolver"); } @Test public void faviconMapping() throws IllegalAccessException { load(); assertThat(this.context.getBeansOfType(ResourceHttpRequestHandler.class) - .get("faviconRequestHandler"), is(notNullValue())); + .get("faviconRequestHandler")).isNotNull(); assertThat(this.context.getBeansOfType(SimpleUrlHandlerMapping.class) - .get("faviconHandlerMapping"), is(notNullValue())); + .get("faviconHandlerMapping")).isNotNull(); Map> mappingLocations = getFaviconMappingLocations(); - assertThat(mappingLocations.get("/**/favicon.ico").size(), equalTo(5)); + assertThat(mappingLocations.get("/**/favicon.ico")).hasSize(5); } @Test public void faviconMappingDisabled() throws IllegalAccessException { load("spring.mvc.favicon.enabled:false"); assertThat(this.context.getBeansOfType(ResourceHttpRequestHandler.class) - .get("faviconRequestHandler"), is(nullValue())); + .get("faviconRequestHandler")).isNull(); assertThat(this.context.getBeansOfType(SimpleUrlHandlerMapping.class) - .get("faviconHandlerMapping"), is(nullValue())); + .get("faviconHandlerMapping")).isNull(); } @Test @@ -429,7 +412,7 @@ public class WebMvcAutoConfigurationTests { load(); RequestMappingHandlerAdapter adapter = this.context .getBean(RequestMappingHandlerAdapter.class); - assertNull(ReflectionTestUtils.getField(adapter, "asyncRequestTimeout")); + assertThat(ReflectionTestUtils.getField(adapter, "asyncRequestTimeout")).isNull(); } @Test @@ -438,7 +421,7 @@ public class WebMvcAutoConfigurationTests { RequestMappingHandlerAdapter adapter = this.context .getBean(RequestMappingHandlerAdapter.class); Object actual = ReflectionTestUtils.getField(adapter, "asyncRequestTimeout"); - assertEquals(123456L, actual); + assertThat(actual).isEqualTo(123456L); } @Test @@ -448,34 +431,31 @@ public class WebMvcAutoConfigurationTests { .getBean(RequestMappingHandlerAdapter.class); ContentNegotiationManager actual = (ContentNegotiationManager) ReflectionTestUtils .getField(adapter, "contentNegotiationManager"); - assertTrue(actual.getAllFileExtensions().contains("yaml")); + assertThat(actual.getAllFileExtensions().contains("yaml")).isTrue(); } @Test public void httpPutFormContentFilterIsAutoConfigured() { load(); - assertThat( - this.context.getBeansOfType(OrderedHttpPutFormContentFilter.class).size(), - is(equalTo(1))); + assertThat(this.context.getBeansOfType(OrderedHttpPutFormContentFilter.class)) + .hasSize(1); } @Test public void httpPutFormContentFilterCanBeOverridden() { load(CustomHttpPutFormContentFilter.class); - assertThat( - this.context.getBeansOfType(OrderedHttpPutFormContentFilter.class).size(), - is(equalTo(0))); - assertThat(this.context.getBeansOfType(HttpPutFormContentFilter.class).size(), - is(equalTo(1))); + assertThat(this.context.getBeansOfType(OrderedHttpPutFormContentFilter.class)) + .hasSize(0); + assertThat(this.context.getBeansOfType(HttpPutFormContentFilter.class)) + .hasSize(1); } @Test public void customConfigurableWebBindingInitializer() { load(CustomConfigurableWebBindingInitializer.class); - assertThat( - this.context.getBean(RequestMappingHandlerAdapter.class) - .getWebBindingInitializer(), - is(instanceOf(CustomWebBindingInitializer.class))); + assertThat(this.context.getBean(RequestMappingHandlerAdapter.class) + .getWebBindingInitializer()) + .isInstanceOf(CustomWebBindingInitializer.class); } private void load(Class config, String... environment) { @@ -492,15 +472,6 @@ public class WebMvcAutoConfigurationTests { this.context.refresh(); } - @SuppressWarnings({ "unchecked", "rawtypes" }) - private Matcher containsInstances(Class... types) { - Matcher[] instances = new Matcher[types.length]; - for (int i = 0; i < instances.length; i++) { - instances[i] = instanceOf(types[i]); - } - return contains(instances); - } - private void load(String... environment) { load(null, environment); } diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/websocket/WebSocketAutoConfigurationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/websocket/WebSocketAutoConfigurationTests.java index f4681dce7b..08db516855 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/websocket/WebSocketAutoConfigurationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/websocket/WebSocketAutoConfigurationTests.java @@ -30,9 +30,7 @@ import org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletCon import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; -import static org.hamcrest.Matchers.instanceOf; -import static org.hamcrest.Matchers.is; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link WebSocketAutoConfiguration} @@ -73,7 +71,7 @@ public class WebSocketAutoConfigurationTests { this.context.refresh(); Object serverContainer = this.context.getServletContext() .getAttribute("javax.websocket.server.ServerContainer"); - assertThat(serverContainer, is(instanceOf(ServerContainer.class))); + assertThat(serverContainer).isInstanceOf(ServerContainer.class); } diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/websocket/WebSocketMessagingAutoConfigurationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/websocket/WebSocketMessagingAutoConfigurationTests.java index 52853053d6..a560edd0ab 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/websocket/WebSocketMessagingAutoConfigurationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/websocket/WebSocketMessagingAutoConfigurationTests.java @@ -61,9 +61,7 @@ import org.springframework.web.socket.sockjs.client.SockJsClient; import org.springframework.web.socket.sockjs.client.Transport; import org.springframework.web.socket.sockjs.client.WebSocketTransport; -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.junit.Assert.fail; /** @@ -151,12 +149,10 @@ public class WebSocketMessagingAutoConfigurationTests { if (failure.get() != null) { throw failure.get(); } - else { - fail("Response was not received within 30 seconds"); - } + fail("Response was not received within 30 seconds"); } - assertThat(new String((byte[]) result.get()), - is(equalTo(String.format("{%n \"foo\" : 5,%n \"bar\" : \"baz\"%n}")))); + assertThat(new String((byte[]) result.get())) + .isEqualTo(String.format("{%n \"foo\" : 5,%n \"bar\" : \"baz\"%n}")); } @Configuration From 94677b35f81ec08129e9291d2bf005d0ebbe994c Mon Sep 17 00:00:00 2001 From: Phillip Webb Date: Sat, 6 Feb 2016 14:49:04 -0800 Subject: [PATCH 03/10] Use AssertJ in spring-boot-actuator See gh-5083 --- .../boot/actuate/audit/AuditEventTests.java | 15 +- .../InMemoryAuditEventRepositoryTests.java | 31 ++-- .../AuditAutoConfigurationTests.java | 22 ++- ...CacheStatisticsAutoConfigurationTests.java | 12 +- .../CrshAutoConfigurationTests.java | 124 ++++++--------- .../EndpointAutoConfigurationTests.java | 64 ++++---- ...ointMBeanExportAutoConfigurationTests.java | 45 ++---- .../EndpointMvcIntegrationTests.java | 13 +- .../EndpointWebMvcAutoConfigurationTests.java | 69 ++++----- ...HealthIndicatorAutoConfigurationTests.java | 143 +++++++++--------- ...althMvcEndpointAutoConfigurationTests.java | 10 +- .../JolokiaAutoConfigurationTests.java | 14 +- ...erverPropertiesAutoConfigurationTests.java | 16 +- ...mentWebSecurityAutoConfigurationTests.java | 47 +++--- .../MetricExportAutoConfigurationTests.java | 10 +- .../MetricFilterAutoConfigurationTests.java | 9 +- ...etricRepositoryAutoConfigurationTests.java | 27 ++-- .../PublicMetricsAutoConfigurationTests.java | 28 ++-- .../autoconfigure/ShellPropertiesTests.java | 91 +++++------ ...TraceRepositoryAutoConfigurationTests.java | 11 +- .../TraceWebFilterAutoConfigurationTests.java | 4 +- .../endpoint/AbstractEndpointTests.java | 25 ++- .../AutoConfigurationReportEndpointTests.java | 8 +- .../actuate/endpoint/BeansEndpointTests.java | 8 +- ...sReportEndpointMethodAnnotationsTests.java | 15 +- ...onPropertiesReportEndpointParentTests.java | 11 +- ...ionPropertiesReportEndpointProxyTests.java | 5 +- ...rtiesReportEndpointSerializationTests.java | 71 +++++---- ...gurationPropertiesReportEndpointTests.java | 60 ++++---- .../actuate/endpoint/DumpEndpointTests.java | 5 +- .../endpoint/EnvironmentEndpointTests.java | 82 +++++----- .../actuate/endpoint/FlywayEndpointTests.java | 5 +- .../actuate/endpoint/HealthEndpointTests.java | 5 +- .../actuate/endpoint/InfoEndpointTests.java | 5 +- .../endpoint/LiquibaseEndpointTests.java | 5 +- .../MetricReaderPublicMetricsTests.java | 4 +- .../endpoint/MetricsEndpointTests.java | 15 +- .../endpoint/RequestMappingEndpointTests.java | 27 ++-- .../RichGaugeReaderPublicMetricsTests.java | 28 ++-- .../boot/actuate/endpoint/SanitizerTests.java | 23 ++- .../endpoint/ShutdownEndpointTests.java | 15 +- .../endpoint/ShutdownParentEndpointTests.java | 20 ++- .../endpoint/SystemPublicMetricsTests.java | 46 +++--- .../endpoint/TomcatPublicMetricsTests.java | 9 +- .../actuate/endpoint/TraceEndpointTests.java | 5 +- .../jmx/EndpointMBeanExporterTests.java | 60 ++++---- .../mvc/EndpointHandlerMappingTests.java | 57 +++---- ...vcEndpointBrowserPathIntegrationTests.java | 5 +- ...erMvcEndpointDisabledIntegrationTests.java | 5 +- ...ointEndpointsDisabledIntegrationTests.java | 5 +- ...ointServerContextPathIntegrationTests.java | 23 ++- ...MvcEndpointServerPortIntegrationTests.java | 24 ++- ...serMvcEndpointVanillaIntegrationTests.java | 5 +- .../endpoint/mvc/HealthMvcEndpointTests.java | 85 +++++------ .../endpoint/mvc/JolokiaMvcEndpointTests.java | 8 +- .../endpoint/mvc/LogFileMvcEndpointTests.java | 16 +- .../endpoint/mvc/MvcEndpointsTests.java | 14 +- .../endpoint/mvc/NamePatternFilterTests.java | 42 +++-- .../mvc/ShutdownMvcEndpointTests.java | 4 +- .../ApplicationHealthIndicatorTests.java | 4 +- .../health/CompositeHealthIndicatorTests.java | 48 +++--- .../DataSourceHealthIndicatorTests.java | 47 +++--- .../health/DiskSpaceHealthIndicatorTests.java | 18 +-- .../ElasticsearchHealthIndicatorTests.java | 34 ++--- .../boot/actuate/health/HealthTests.java | 72 +++++---- .../health/JmsHealthIndicatorTests.java | 14 +- .../health/MailHealthIndicatorTests.java | 16 +- .../health/MongoHealthIndicatorTests.java | 22 ++- .../health/OrderedHealthAggregatorTests.java | 15 +- .../health/RabbitHealthIndicatorTests.java | 8 +- .../health/RedisHealthIndicatorTests.java | 24 ++- .../health/SolrHealthIndicatorTests.java | 20 ++- .../aggregate/AggregateMetricReaderTests.java | 27 ++-- .../buffer/BufferGaugeServiceSpeedTests.java | 6 +- .../buffer/BufferMetricReaderTests.java | 13 +- .../metrics/buffer/CounterBuffersTests.java | 9 +- .../buffer/CounterServiceSpeedTests.java | 6 +- .../DefaultCounterServiceSpeedTests.java | 4 +- .../buffer/DefaultGaugeServiceSpeedTests.java | 4 +- .../DropwizardCounterServiceSpeedTests.java | 4 +- .../DropwizardMetricServicesTests.java | 20 +-- .../export/MetricCopyExporterTests.java | 20 +-- .../metrics/export/MetricExportersTests.java | 15 +- .../PrefixMetricGroupExporterTests.java | 12 +- .../export/RichGaugeExporterTests.java | 4 +- .../SpringIntegrationMetricReaderTests.java | 4 +- .../jmx/DefaultMetricNamingStrategyTests.java | 28 ++-- .../MetricRegistryMetricReaderTests.java | 13 +- .../InMemoryMetricRepositoryTests.java | 9 +- .../InMemoryPrefixMetricRepositoryTests.java | 25 ++- .../redis/RedisMetricRepositoryTests.java | 29 ++-- .../RedisMultiMetricRepositoryTests.java | 32 ++-- .../InMemoryRichGaugeRepositoryTests.java | 7 +- .../rich/MultiMetricRichGaugeReaderTests.java | 17 +-- .../statsd/StatsdMetricWriterTests.java | 50 +++--- ...ava => SimpleInMemoryRepositoryTests.java} | 88 +++++------ .../writer/DefaultCounterServiceTests.java | 21 +-- .../writer/DefaultGaugeServiceTests.java | 8 +- .../AuthenticationAuditListenerTests.java | 7 +- .../system/ApplicationPidFileWriterTests.java | 26 ++-- .../EmbeddedServerPortFileWriterTests.java | 34 ++--- .../trace/InMemoryTraceRepositoryTests.java | 14 +- .../trace/WebRequestTraceFilterTests.java | 44 +++--- 103 files changed, 1197 insertions(+), 1405 deletions(-) rename spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/util/{InMemoryRepositoryTests.java => SimpleInMemoryRepositoryTests.java} (62%) mode change 100644 => 100755 diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/audit/AuditEventTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/audit/AuditEventTests.java index 844cbc4428..b0820f5d9c 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/audit/AuditEventTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/audit/AuditEventTests.java @@ -20,8 +20,7 @@ import java.util.Collections; import org.junit.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link AuditEvent}. @@ -34,17 +33,17 @@ public class AuditEventTests { public void testNowEvent() throws Exception { AuditEvent event = new AuditEvent("phil", "UNKNOWN", Collections.singletonMap("a", (Object) "b")); - assertEquals("b", event.getData().get("a")); - assertEquals("UNKNOWN", event.getType()); - assertEquals("phil", event.getPrincipal()); - assertNotNull(event.getTimestamp()); + assertThat(event.getData().get("a")).isEqualTo("b"); + assertThat(event.getType()).isEqualTo("UNKNOWN"); + assertThat(event.getPrincipal()).isEqualTo("phil"); + assertThat(event.getTimestamp()).isNotNull(); } @Test public void testConvertStringsToData() throws Exception { AuditEvent event = new AuditEvent("phil", "UNKNOWN", "a=b", "c=d"); - assertEquals("b", event.getData().get("a")); - assertEquals("d", event.getData().get("c")); + assertThat(event.getData().get("a")).isEqualTo("b"); + assertThat(event.getData().get("c")).isEqualTo("d"); } } diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/audit/InMemoryAuditEventRepositoryTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/audit/InMemoryAuditEventRepositoryTests.java index 0383e03051..4c7f05f3ee 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/audit/InMemoryAuditEventRepositoryTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/audit/InMemoryAuditEventRepositoryTests.java @@ -24,8 +24,7 @@ import java.util.Map; 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 InMemoryAuditEventRepository}. @@ -41,9 +40,9 @@ public class InMemoryAuditEventRepositoryTests { repository.add(new AuditEvent("dave", "a")); repository.add(new AuditEvent("dave", "b")); List events = repository.find("dave", null); - assertThat(events.size(), equalTo(2)); - assertThat(events.get(0).getType(), equalTo("a")); - assertThat(events.get(1).getType(), equalTo("b")); + assertThat(events.size()).isEqualTo(2); + assertThat(events.get(0).getType()).isEqualTo("a"); + assertThat(events.get(1).getType()).isEqualTo("b"); } @@ -54,9 +53,9 @@ public class InMemoryAuditEventRepositoryTests { repository.add(new AuditEvent("dave", "b")); repository.add(new AuditEvent("dave", "c")); List events = repository.find("dave", null); - assertThat(events.size(), equalTo(2)); - assertThat(events.get(0).getType(), equalTo("b")); - assertThat(events.get(1).getType(), equalTo("c")); + assertThat(events.size()).isEqualTo(2); + assertThat(events.get(0).getType()).isEqualTo("b"); + assertThat(events.get(1).getType()).isEqualTo("c"); } @Test @@ -67,9 +66,9 @@ public class InMemoryAuditEventRepositoryTests { repository.add(new AuditEvent("dave", "c")); repository.add(new AuditEvent("phil", "d")); List events = repository.find("dave", null); - assertThat(events.size(), equalTo(2)); - assertThat(events.get(0).getType(), equalTo("a")); - assertThat(events.get(1).getType(), equalTo("c")); + assertThat(events.size()).isEqualTo(2); + assertThat(events.get(0).getType()).isEqualTo("a"); + assertThat(events.get(1).getType()).isEqualTo("c"); } @Test @@ -89,12 +88,12 @@ public class InMemoryAuditEventRepositoryTests { repository.add(new AuditEvent(calendar.getTime(), "phil", "d", data)); calendar.add(Calendar.DAY_OF_YEAR, 1); List events = repository.find(null, after); - assertThat(events.size(), equalTo(2)); - assertThat(events.get(0).getType(), equalTo("c")); - assertThat(events.get(1).getType(), equalTo("d")); + assertThat(events.size()).isEqualTo(2); + assertThat(events.get(0).getType()).isEqualTo("c"); + assertThat(events.get(1).getType()).isEqualTo("d"); events = repository.find("dave", after); - assertThat(events.size(), equalTo(1)); - assertThat(events.get(0).getType(), equalTo("c")); + assertThat(events.size()).isEqualTo(1); + assertThat(events.get(0).getType()).isEqualTo("c"); } } diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/AuditAutoConfigurationTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/AuditAutoConfigurationTests.java index 4bae931068..7c3ea637ac 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/AuditAutoConfigurationTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/AuditAutoConfigurationTests.java @@ -31,9 +31,7 @@ import org.springframework.context.annotation.Configuration; import org.springframework.security.access.event.AbstractAuthorizationEvent; import org.springframework.security.authentication.event.AbstractAuthenticationEvent; -import static org.hamcrest.Matchers.instanceOf; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link AuditAutoConfiguration}. @@ -48,33 +46,33 @@ public class AuditAutoConfigurationTests { @Test public void testTraceConfiguration() throws Exception { registerAndRefresh(AuditAutoConfiguration.class); - assertNotNull(this.context.getBean(AuditEventRepository.class)); - assertNotNull(this.context.getBean(AuthenticationAuditListener.class)); - assertNotNull(this.context.getBean(AuthorizationAuditListener.class)); + assertThat(this.context.getBean(AuditEventRepository.class)).isNotNull(); + assertThat(this.context.getBean(AuthenticationAuditListener.class)).isNotNull(); + assertThat(this.context.getBean(AuthorizationAuditListener.class)).isNotNull(); } @Test public void ownAutoRepository() throws Exception { registerAndRefresh(CustomAuditEventRepositoryConfiguration.class, AuditAutoConfiguration.class); - assertThat(this.context.getBean(AuditEventRepository.class), - instanceOf(TestAuditEventRepository.class)); + assertThat(this.context.getBean(AuditEventRepository.class)) + .isInstanceOf(TestAuditEventRepository.class); } @Test public void ownAuthenticationAuditListener() throws Exception { registerAndRefresh(CustomAuthenticationAuditListenerConfiguration.class, AuditAutoConfiguration.class); - assertThat(this.context.getBean(AbstractAuthenticationAuditListener.class), - instanceOf(TestAuthenticationAuditListener.class)); + assertThat(this.context.getBean(AbstractAuthenticationAuditListener.class)) + .isInstanceOf(TestAuthenticationAuditListener.class); } @Test public void ownAuthorizationAuditListener() throws Exception { registerAndRefresh(CustomAuthorizationAuditListenerConfiguration.class, AuditAutoConfiguration.class); - assertThat(this.context.getBean(AbstractAuthorizationAuditListener.class), - instanceOf(TestAuthorizationAuditListener.class)); + assertThat(this.context.getBean(AbstractAuthorizationAuditListener.class)) + .isInstanceOf(TestAuthorizationAuditListener.class); } private void registerAndRefresh(Class... annotatedClasses) { diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/CacheStatisticsAutoConfigurationTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/CacheStatisticsAutoConfigurationTests.java index 9025d375c4..6c350fbf13 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/CacheStatisticsAutoConfigurationTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/CacheStatisticsAutoConfigurationTests.java @@ -53,8 +53,8 @@ import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.Resource; import org.springframework.util.Assert; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.offset; /** * Tests for {@link CacheStatisticsAutoConfiguration}. @@ -160,8 +160,8 @@ public class CacheStatisticsAutoConfigurationTests { private void assertCoreStatistics(CacheStatistics metrics, Long size, Double hitRatio, Double missRatio) { - assertNotNull("Cache metrics must not be null", metrics); - assertEquals("Wrong size for metrics " + metrics, size, metrics.getSize()); + assertThat(metrics).isNotNull(); + assertThat(metrics.getSize()).isEqualTo(size); checkRatio("Wrong hit ratio for metrics " + metrics, hitRatio, metrics.getHitRatio()); checkRatio("Wrong miss ratio for metrics " + metrics, missRatio, @@ -170,10 +170,10 @@ public class CacheStatisticsAutoConfigurationTests { private void checkRatio(String message, Double expected, Double actual) { if (expected == null || actual == null) { - assertEquals(message, expected, actual); + assertThat(actual).as(message).isEqualTo(expected); } else { - assertEquals(message, expected, actual, 0.01D); + assertThat(actual).as(message).isEqualTo(expected, offset(0.01D)); } } diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/CrshAutoConfigurationTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/CrshAutoConfigurationTests.java index b0fce565e4..5684852049 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/CrshAutoConfigurationTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/CrshAutoConfigurationTests.java @@ -51,11 +51,7 @@ import org.springframework.security.core.AuthenticationException; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.web.context.support.AnnotationConfigWebApplicationContext; -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.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link CrshAutoConfiguration}. @@ -82,13 +78,12 @@ public class CrshAutoConfigurationTests { env.setProperty("shell.disabled_plugins", "GroovyREPL, termIOHandler, org.crsh.auth.AuthenticationPlugin"); load(env); - PluginLifeCycle lifeCycle = this.context.getBean(PluginLifeCycle.class); - assertNotNull(lifeCycle); - - assertNull(lifeCycle.getContext().getPlugin(GroovyRepl.class)); - assertNull(lifeCycle.getContext().getPlugin(ProcessorIOHandler.class)); - assertNull(lifeCycle.getContext().getPlugin(JaasAuthenticationPlugin.class)); + assertThat(lifeCycle).isNotNull(); + assertThat(lifeCycle.getContext().getPlugin(GroovyRepl.class)).isNull(); + assertThat(lifeCycle.getContext().getPlugin(ProcessorIOHandler.class)).isNull(); + assertThat(lifeCycle.getContext().getPlugin(JaasAuthenticationPlugin.class)) + .isNull(); } @Test @@ -96,13 +91,12 @@ public class CrshAutoConfigurationTests { this.context = new AnnotationConfigWebApplicationContext(); this.context.register(CrshAutoConfiguration.class); this.context.refresh(); - PluginLifeCycle lifeCycle = this.context.getBean(PluginLifeCycle.class); - Map attributes = lifeCycle.getContext().getAttributes(); - assertTrue(attributes.containsKey("spring.version")); - assertTrue(attributes.containsKey("spring.beanfactory")); - assertEquals(this.context.getBeanFactory(), attributes.get("spring.beanfactory")); + assertThat(attributes.containsKey("spring.version")).isTrue(); + assertThat(attributes.containsKey("spring.beanfactory")).isTrue(); + assertThat(attributes.get("spring.beanfactory")) + .isEqualTo(this.context.getBeanFactory()); } @Test @@ -113,12 +107,11 @@ public class CrshAutoConfigurationTests { load(env); PluginLifeCycle lifeCycle = this.context.getBean(PluginLifeCycle.class); - - assertEquals("3333", lifeCycle.getConfig().getProperty("crash.ssh.port")); - assertEquals("600000", - lifeCycle.getConfig().getProperty("crash.ssh.auth_timeout")); - assertEquals("600000", - lifeCycle.getConfig().getProperty("crash.ssh.idle_timeout")); + assertThat(lifeCycle.getConfig().getProperty("crash.ssh.port")).isEqualTo("3333"); + assertThat(lifeCycle.getConfig().getProperty("crash.ssh.auth_timeout")) + .isEqualTo("600000"); + assertThat(lifeCycle.getConfig().getProperty("crash.ssh.idle_timeout")) + .isEqualTo("600000"); } @Test @@ -127,11 +120,9 @@ public class CrshAutoConfigurationTests { env.setProperty("shell.ssh.enabled", "true"); env.setProperty("shell.ssh.key_path", "~/.ssh/id.pem"); load(env); - PluginLifeCycle lifeCycle = this.context.getBean(PluginLifeCycle.class); - - assertEquals("~/.ssh/id.pem", - lifeCycle.getConfig().getProperty("crash.ssh.keypath")); + assertThat(lifeCycle.getConfig().getProperty("crash.ssh.keypath")) + .isEqualTo("~/.ssh/id.pem"); } @Test @@ -141,13 +132,11 @@ public class CrshAutoConfigurationTests { env.setProperty("shell.ssh.auth-timeout", "300000"); env.setProperty("shell.ssh.idle-timeout", "400000"); load(env); - PluginLifeCycle lifeCycle = this.context.getBean(PluginLifeCycle.class); - - assertEquals("300000", - lifeCycle.getConfig().getProperty("crash.ssh.auth_timeout")); - assertEquals("400000", - lifeCycle.getConfig().getProperty("crash.ssh.idle_timeout")); + assertThat(lifeCycle.getConfig().getProperty("crash.ssh.auth_timeout")) + .isEqualTo("300000"); + assertThat(lifeCycle.getConfig().getProperty("crash.ssh.idle_timeout")) + .isEqualTo("400000"); } private void load(MockEnvironment env) { @@ -162,9 +151,7 @@ public class CrshAutoConfigurationTests { this.context = new AnnotationConfigWebApplicationContext(); this.context.register(CrshAutoConfiguration.class); this.context.refresh(); - PluginLifeCycle lifeCycle = this.context.getBean(PluginLifeCycle.class); - int count = 0; Iterator resources = lifeCycle.getContext() .loadResources("login", ResourceKind.LIFECYCLE).iterator(); @@ -172,8 +159,7 @@ public class CrshAutoConfigurationTests { count++; resources.next(); } - assertEquals(1, count); - + assertThat(count).isEqualTo(1); count = 0; resources = lifeCycle.getContext() .loadResources("sleep.groovy", ResourceKind.COMMAND).iterator(); @@ -181,7 +167,7 @@ public class CrshAutoConfigurationTests { count++; resources.next(); } - assertEquals(1, count); + assertThat(count).isEqualTo(1); } @Test @@ -189,9 +175,7 @@ public class CrshAutoConfigurationTests { this.context = new AnnotationConfigWebApplicationContext(); this.context.register(CrshAutoConfiguration.class); this.context.refresh(); - PluginLifeCycle lifeCycle = this.context.getBean(PluginLifeCycle.class); - int count = 0; Iterator resources = lifeCycle.getContext() .loadResources("jdbc.groovy", ResourceKind.COMMAND).iterator(); @@ -199,7 +183,7 @@ public class CrshAutoConfigurationTests { count++; resources.next(); } - assertEquals(0, count); + assertThat(count).isEqualTo(0); } @Test @@ -209,10 +193,8 @@ public class CrshAutoConfigurationTests { this.context.register(SecurityConfiguration.class); this.context.register(CrshAutoConfiguration.class); this.context.refresh(); - PluginLifeCycle lifeCycle = this.context.getBean(PluginLifeCycle.class); PluginContext pluginContext = lifeCycle.getContext(); - int count = 0; Iterator plugins = pluginContext .getPlugins(AuthenticationPlugin.class).iterator(); @@ -220,7 +202,7 @@ public class CrshAutoConfigurationTests { count++; plugins.next(); } - assertEquals(3, count); + assertThat(count).isEqualTo(3); } @Test @@ -231,9 +213,8 @@ public class CrshAutoConfigurationTests { this.context.setServletContext(new MockServletContext()); this.context.register(CrshAutoConfiguration.class); this.context.refresh(); - PluginLifeCycle lifeCycle = this.context.getBean(PluginLifeCycle.class); - assertEquals("simple", lifeCycle.getConfig().get("crash.auth")); + assertThat(lifeCycle.getConfig().get("crash.auth")).isEqualTo("simple"); } @Test @@ -247,11 +228,10 @@ public class CrshAutoConfigurationTests { this.context.register(SecurityConfiguration.class); this.context.register(CrshAutoConfiguration.class); this.context.refresh(); - PluginLifeCycle lifeCycle = this.context.getBean(PluginLifeCycle.class); - assertEquals("jaas", lifeCycle.getConfig().get("crash.auth")); - assertEquals("my-test-domain", - lifeCycle.getConfig().get("crash.auth.jaas.domain")); + assertThat(lifeCycle.getConfig().get("crash.auth")).isEqualTo("jaas"); + assertThat(lifeCycle.getConfig().get("crash.auth.jaas.domain")) + .isEqualTo("my-test-domain"); } @Test @@ -265,10 +245,10 @@ public class CrshAutoConfigurationTests { this.context.register(SecurityConfiguration.class); this.context.register(CrshAutoConfiguration.class); this.context.refresh(); - PluginLifeCycle lifeCycle = this.context.getBean(PluginLifeCycle.class); - assertEquals("key", lifeCycle.getConfig().get("crash.auth")); - assertEquals("~/test.pem", lifeCycle.getConfig().get("crash.auth.key.path")); + assertThat(lifeCycle.getConfig().get("crash.auth")).isEqualTo("key"); + assertThat(lifeCycle.getConfig().get("crash.auth.key.path")) + .isEqualTo("~/test.pem"); } @Test @@ -283,13 +263,11 @@ public class CrshAutoConfigurationTests { this.context.register(SecurityConfiguration.class); this.context.register(CrshAutoConfiguration.class); this.context.refresh(); - PluginLifeCycle lifeCycle = this.context.getBean(PluginLifeCycle.class); - assertEquals("simple", lifeCycle.getConfig().get("crash.auth")); - + assertThat(lifeCycle.getConfig().get("crash.auth")).isEqualTo("simple"); AuthenticationPlugin authenticationPlugin = null; String authentication = lifeCycle.getConfig().getProperty("crash.auth"); - assertNotNull(authentication); + assertThat(authentication).isNotNull(); for (AuthenticationPlugin plugin : lifeCycle.getContext() .getPlugins(AuthenticationPlugin.class)) { if (authentication.equals(plugin.getName())) { @@ -297,10 +275,10 @@ public class CrshAutoConfigurationTests { break; } } - assertNotNull(authenticationPlugin); - assertTrue(authenticationPlugin.authenticate("user", "password")); - assertFalse(authenticationPlugin.authenticate(UUID.randomUUID().toString(), - "password")); + assertThat(authenticationPlugin).isNotNull(); + assertThat(authenticationPlugin.authenticate("user", "password")).isTrue(); + assertThat(authenticationPlugin.authenticate(UUID.randomUUID().toString(), + "password")).isFalse(); } @Test @@ -313,12 +291,10 @@ public class CrshAutoConfigurationTests { this.context.register(SecurityConfiguration.class); this.context.register(CrshAutoConfiguration.class); this.context.refresh(); - PluginLifeCycle lifeCycle = this.context.getBean(PluginLifeCycle.class); - AuthenticationPlugin authenticationPlugin = null; String authentication = lifeCycle.getConfig().getProperty("crash.auth"); - assertNotNull(authentication); + assertThat(authentication).isNotNull(); for (AuthenticationPlugin plugin : lifeCycle.getContext() .getPlugins(AuthenticationPlugin.class)) { if (authentication.equals(plugin.getName())) { @@ -326,11 +302,10 @@ public class CrshAutoConfigurationTests { break; } } - assertTrue(authenticationPlugin.authenticate(SecurityConfiguration.USERNAME, - SecurityConfiguration.PASSWORD)); - - assertFalse(authenticationPlugin.authenticate(UUID.randomUUID().toString(), - SecurityConfiguration.PASSWORD)); + assertThat(authenticationPlugin.authenticate(SecurityConfiguration.USERNAME, + SecurityConfiguration.PASSWORD)).isTrue(); + assertThat(authenticationPlugin.authenticate(UUID.randomUUID().toString(), + SecurityConfiguration.PASSWORD)).isFalse(); } @Test @@ -343,12 +318,10 @@ public class CrshAutoConfigurationTests { this.context.register(SecurityConfiguration.class); this.context.register(CrshAutoConfiguration.class); this.context.refresh(); - PluginLifeCycle lifeCycle = this.context.getBean(PluginLifeCycle.class); - AuthenticationPlugin authenticationPlugin = null; String authentication = lifeCycle.getConfig().getProperty("crash.auth"); - assertNotNull(authentication); + assertThat(authentication).isNotNull(); for (AuthenticationPlugin plugin : lifeCycle.getContext() .getPlugins(AuthenticationPlugin.class)) { if (authentication.equals(plugin.getName())) { @@ -356,11 +329,10 @@ public class CrshAutoConfigurationTests { break; } } - assertTrue(authenticationPlugin.authenticate(SecurityConfiguration.USERNAME, - SecurityConfiguration.PASSWORD)); - - assertFalse(authenticationPlugin.authenticate(UUID.randomUUID().toString(), - SecurityConfiguration.PASSWORD)); + assertThat(authenticationPlugin.authenticate(SecurityConfiguration.USERNAME, + SecurityConfiguration.PASSWORD)).isTrue(); + assertThat(authenticationPlugin.authenticate(UUID.randomUUID().toString(), + SecurityConfiguration.PASSWORD)).isFalse(); } @Configuration diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/EndpointAutoConfigurationTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/EndpointAutoConfigurationTests.java index e171e0e120..3bc2b3eef9 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/EndpointAutoConfigurationTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/EndpointAutoConfigurationTests.java @@ -47,10 +47,7 @@ import org.springframework.context.annotation.AnnotationConfigApplicationContext import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; -import static org.junit.Assert.assertEquals; -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 EndpointAutoConfiguration}. @@ -76,15 +73,15 @@ public class EndpointAutoConfigurationTests { @Test public void endpoints() throws Exception { load(EndpointAutoConfiguration.class); - assertNotNull(this.context.getBean(BeansEndpoint.class)); - assertNotNull(this.context.getBean(DumpEndpoint.class)); - assertNotNull(this.context.getBean(EnvironmentEndpoint.class)); - assertNotNull(this.context.getBean(HealthEndpoint.class)); - assertNotNull(this.context.getBean(InfoEndpoint.class)); - assertNotNull(this.context.getBean(MetricsEndpoint.class)); - assertNotNull(this.context.getBean(ShutdownEndpoint.class)); - assertNotNull(this.context.getBean(TraceEndpoint.class)); - assertNotNull(this.context.getBean(RequestMappingEndpoint.class)); + assertThat(this.context.getBean(BeansEndpoint.class)).isNotNull(); + assertThat(this.context.getBean(DumpEndpoint.class)).isNotNull(); + assertThat(this.context.getBean(EnvironmentEndpoint.class)).isNotNull(); + assertThat(this.context.getBean(HealthEndpoint.class)).isNotNull(); + assertThat(this.context.getBean(InfoEndpoint.class)).isNotNull(); + assertThat(this.context.getBean(MetricsEndpoint.class)).isNotNull(); + assertThat(this.context.getBean(ShutdownEndpoint.class)).isNotNull(); + assertThat(this.context.getBean(TraceEndpoint.class)).isNotNull(); + assertThat(this.context.getBean(RequestMappingEndpoint.class)).isNotNull(); } @Test @@ -92,19 +89,19 @@ public class EndpointAutoConfigurationTests { load(EmbeddedDataSourceConfiguration.class, EndpointAutoConfiguration.class, HealthIndicatorAutoConfiguration.class); HealthEndpoint bean = this.context.getBean(HealthEndpoint.class); - assertNotNull(bean); + assertThat(bean).isNotNull(); Health result = bean.invoke(); - assertNotNull(result); - assertTrue("Wrong result: " + result, result.getDetails().containsKey("db")); + assertThat(result).isNotNull(); + assertThat(result.getDetails().containsKey("db")).isTrue(); } @Test public void healthEndpointWithDefaultHealthIndicator() { load(EndpointAutoConfiguration.class, HealthIndicatorAutoConfiguration.class); HealthEndpoint bean = this.context.getBean(HealthEndpoint.class); - assertNotNull(bean); + assertThat(bean).isNotNull(); Health result = bean.invoke(); - assertNotNull(result); + assertThat(result).isNotNull(); } @Test @@ -112,8 +109,8 @@ public class EndpointAutoConfigurationTests { load(PublicMetricsAutoConfiguration.class, EndpointAutoConfiguration.class); MetricsEndpoint endpoint = this.context.getBean(MetricsEndpoint.class); Map metrics = endpoint.invoke(); - assertTrue(metrics.containsKey("mem")); - assertTrue(metrics.containsKey("heap.used")); + assertThat(metrics.containsKey("mem")).isTrue(); + assertThat(metrics.containsKey("heap.used")).isTrue(); } @Test @@ -124,18 +121,19 @@ public class EndpointAutoConfigurationTests { Map metrics = endpoint.invoke(); // Custom metrics - assertTrue(metrics.containsKey("foo")); + assertThat(metrics.containsKey("foo")).isTrue(); // System metrics still available - assertTrue(metrics.containsKey("mem")); - assertTrue(metrics.containsKey("heap.used")); + assertThat(metrics.containsKey("mem")).isTrue(); + assertThat(metrics.containsKey("heap.used")).isTrue(); } @Test public void autoConfigurationAuditEndpoints() { load(EndpointAutoConfiguration.class, ConditionEvaluationReport.class); - assertNotNull(this.context.getBean(AutoConfigurationReportEndpoint.class)); + assertThat(this.context.getBean(AutoConfigurationReportEndpoint.class)) + .isNotNull(); } @Test @@ -145,9 +143,9 @@ public class EndpointAutoConfigurationTests { this.context.register(EndpointAutoConfiguration.class); this.context.refresh(); InfoEndpoint endpoint = this.context.getBean(InfoEndpoint.class); - assertNotNull(endpoint); - assertNotNull(endpoint.invoke().get("git")); - assertEquals("bar", endpoint.invoke().get("foo")); + assertThat(endpoint).isNotNull(); + assertThat(endpoint.invoke().get("git")).isNotNull(); + assertThat(endpoint.invoke().get("foo")).isEqualTo("bar"); } @Test @@ -158,8 +156,8 @@ public class EndpointAutoConfigurationTests { this.context.register(EndpointAutoConfiguration.class); this.context.refresh(); InfoEndpoint endpoint = this.context.getBean(InfoEndpoint.class); - assertNotNull(endpoint); - assertNull(endpoint.invoke().get("git")); + assertThat(endpoint).isNotNull(); + assertThat(endpoint.invoke().get("git")).isNull(); } @Test @@ -169,8 +167,8 @@ public class EndpointAutoConfigurationTests { FlywayAutoConfiguration.class, EndpointAutoConfiguration.class); this.context.refresh(); FlywayEndpoint endpoint = this.context.getBean(FlywayEndpoint.class); - assertNotNull(endpoint); - assertEquals(1, endpoint.invoke().size()); + assertThat(endpoint).isNotNull(); + assertThat(endpoint.invoke()).hasSize(1); } @Test @@ -180,8 +178,8 @@ public class EndpointAutoConfigurationTests { LiquibaseAutoConfiguration.class, EndpointAutoConfiguration.class); this.context.refresh(); LiquibaseEndpoint endpoint = this.context.getBean(LiquibaseEndpoint.class); - assertNotNull(endpoint); - assertEquals(1, endpoint.invoke().size()); + assertThat(endpoint).isNotNull(); + assertThat(endpoint.invoke()).hasSize(1); } private void load(Class... config) { diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/EndpointMBeanExportAutoConfigurationTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/EndpointMBeanExportAutoConfigurationTests.java index 62c6c22d7d..de974e32fb 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/EndpointMBeanExportAutoConfigurationTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/EndpointMBeanExportAutoConfigurationTests.java @@ -43,10 +43,7 @@ import org.springframework.mock.env.MockEnvironment; import org.springframework.stereotype.Component; import org.springframework.util.ObjectUtils; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link EndpointMBeanExportAutoConfiguration}. @@ -71,11 +68,10 @@ public class EndpointMBeanExportAutoConfigurationTests { EndpointMBeanExportAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); this.context.refresh(); - assertNotNull(this.context.getBean(EndpointMBeanExporter.class)); + assertThat(this.context.getBean(EndpointMBeanExporter.class)).isNotNull(); MBeanExporter mbeanExporter = this.context.getBean(EndpointMBeanExporter.class); - - assertFalse(mbeanExporter.getServer() - .queryNames(getObjectName("*", "*,*", this.context), null).isEmpty()); + assertThat(mbeanExporter.getServer() + .queryNames(getObjectName("*", "*,*", this.context), null)).isNotEmpty(); } @Test @@ -86,12 +82,10 @@ public class EndpointMBeanExportAutoConfigurationTests { ManagedEndpoint.class, EndpointMBeanExportAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); this.context.refresh(); - assertNotNull(this.context.getBean(EndpointMBeanExporter.class)); - + assertThat(this.context.getBean(EndpointMBeanExporter.class)).isNotNull(); MBeanExporter mbeanExporter = this.context.getBean(EndpointMBeanExporter.class); - - assertTrue(mbeanExporter.getServer() - .queryNames(getObjectName("*", "*,*", this.context), null).isEmpty()); + assertThat(mbeanExporter.getServer() + .queryNames(getObjectName("*", "*,*", this.context), null)).isEmpty(); } @Test @@ -102,12 +96,10 @@ public class EndpointMBeanExportAutoConfigurationTests { NestedInManagedEndpoint.class, EndpointMBeanExportAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); this.context.refresh(); - assertNotNull(this.context.getBean(EndpointMBeanExporter.class)); - + assertThat(this.context.getBean(EndpointMBeanExporter.class)).isNotNull(); MBeanExporter mbeanExporter = this.context.getBean(EndpointMBeanExporter.class); - - assertTrue(mbeanExporter.getServer() - .queryNames(getObjectName("*", "*,*", this.context), null).isEmpty()); + assertThat(mbeanExporter.getServer() + .queryNames(getObjectName("*", "*,*", this.context), null)).isEmpty(); } @Test(expected = NoSuchBeanDefinitionException.class) @@ -120,7 +112,6 @@ public class EndpointMBeanExportAutoConfigurationTests { EndpointMBeanExportAutoConfiguration.class); this.context.refresh(); this.context.getBean(EndpointMBeanExporter.class); - fail(); } @Test @@ -138,11 +129,9 @@ public class EndpointMBeanExportAutoConfigurationTests { this.context.getBean(EndpointMBeanExporter.class); MBeanExporter mbeanExporter = this.context.getBean(EndpointMBeanExporter.class); - - assertNotNull(mbeanExporter.getServer() - .getMBeanInfo(ObjectNameManager.getInstance( - getObjectName("test-domain", "healthEndpoint", this.context) - .toString() + ",key1=value1,key2=value2"))); + assertThat(mbeanExporter.getServer().getMBeanInfo(ObjectNameManager.getInstance( + getObjectName("test-domain", "healthEndpoint", this.context).toString() + + ",key1=value1,key2=value2"))).isNotNull(); } @Test @@ -151,15 +140,12 @@ public class EndpointMBeanExportAutoConfigurationTests { this.context = new AnnotationConfigApplicationContext(); this.context.register(JmxAutoConfiguration.class, EndpointAutoConfiguration.class, EndpointMBeanExportAutoConfiguration.class); - AnnotationConfigApplicationContext parent = new AnnotationConfigApplicationContext(); parent.register(JmxAutoConfiguration.class, EndpointAutoConfiguration.class, EndpointMBeanExportAutoConfiguration.class); this.context.setParent(parent); - parent.refresh(); this.context.refresh(); - parent.close(); } @@ -178,9 +164,7 @@ public class EndpointMBeanExportAutoConfigurationTests { return ObjectNameManager.getInstance(String.format(name, domain, beanKey, ObjectUtils.getIdentityHexString(applicationContext))); } - else { - return ObjectNameManager.getInstance(String.format(name, domain, beanKey)); - } + return ObjectNameManager.getInstance(String.format(name, domain, beanKey)); } @Configuration @@ -223,6 +207,7 @@ public class EndpointMBeanExportAutoConfigurationTests { public Boolean invoke() { return true; } + } } diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/EndpointMvcIntegrationTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/EndpointMvcIntegrationTests.java index c06db14e24..34aa43725d 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/EndpointMvcIntegrationTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/EndpointMvcIntegrationTests.java @@ -64,8 +64,7 @@ import org.springframework.web.bind.annotation.RestController; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * Integration tests for MVC {@link Endpoint}s. @@ -89,18 +88,16 @@ public class EndpointMvcIntegrationTests { public void envEndpointHidden() throws InterruptedException { String body = new TestRestTemplate().getForObject( "http://localhost:" + this.port + "/env/user.dir", String.class); - assertNotNull(body); - assertTrue("Wrong body: \n" + body, body.contains("spring-boot-actuator")); - assertTrue(this.interceptor.invoked()); + assertThat(body).isNotNull().contains("spring-boot-actuator"); + assertThat(this.interceptor.invoked()).isTrue(); } @Test public void healthEndpointNotHidden() throws InterruptedException { String body = new TestRestTemplate() .getForObject("http://localhost:" + this.port + "/health", String.class); - assertNotNull(body); - assertTrue("Wrong body: \n" + body, body.contains("status")); - assertTrue(this.interceptor.invoked()); + assertThat(body).isNotNull().contains("status"); + assertThat(this.interceptor.invoked()).isTrue(); } @Target(ElementType.TYPE) diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/EndpointWebMvcAutoConfigurationTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/EndpointWebMvcAutoConfigurationTests.java index f43a17bb26..18be090dc9 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/EndpointWebMvcAutoConfigurationTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/EndpointWebMvcAutoConfigurationTests.java @@ -60,6 +60,7 @@ import org.springframework.boot.context.embedded.EmbeddedServletContainerExcepti import org.springframework.boot.context.embedded.EmbeddedServletContainerInitializedEvent; import org.springframework.boot.context.web.ServerPortInfoApplicationContextInitializer; import org.springframework.boot.test.EnvironmentTestUtils; +import org.springframework.boot.test.assertj.Matched; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationListener; import org.springframework.context.annotation.Bean; @@ -79,16 +80,9 @@ import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; import org.springframework.web.servlet.mvc.method.RequestMappingInfoHandlerMapping; -import static org.hamcrest.Matchers.equalTo; +import static org.assertj.core.api.Assertions.assertThat; 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.hamcrest.Matchers.startsWith; -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.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; @@ -136,8 +130,10 @@ public class EndpointWebMvcAutoConfigurationTests { assertContent("/endpoint", ports.get().server, "endpointoutput"); assertContent("/controller", ports.get().management, null); assertContent("/endpoint", ports.get().management, null); - assertTrue(hasHeader("/endpoint", ports.get().server, "X-Application-Context")); - assertTrue(this.applicationContext.containsBean("applicationContextIdFilter")); + assertThat(hasHeader("/endpoint", ports.get().server, "X-Application-Context")) + .isTrue(); + assertThat(this.applicationContext.containsBean("applicationContextIdFilter")) + .isTrue(); this.applicationContext.close(); assertAllClosed(); } @@ -150,8 +146,10 @@ public class EndpointWebMvcAutoConfigurationTests { BaseConfiguration.class, ServerPortConfig.class, EndpointWebMvcAutoConfiguration.class); this.applicationContext.refresh(); - assertFalse(hasHeader("/endpoint", ports.get().server, "X-Application-Context")); - assertFalse(this.applicationContext.containsBean("applicationContextIdFilter")); + assertThat(hasHeader("/endpoint", ports.get().server, "X-Application-Context")) + .isFalse(); + assertThat(this.applicationContext.containsBean("applicationContextIdFilter")) + .isFalse(); this.applicationContext.close(); assertAllClosed(); } @@ -171,7 +169,7 @@ public class EndpointWebMvcAutoConfigurationTests { .getBean(ManagementContextResolver.class).getApplicationContext(); List interceptors = (List) ReflectionTestUtils.getField( managementContext.getBean(EndpointHandlerMapping.class), "interceptors"); - assertEquals(1, interceptors.size()); + assertThat(interceptors).hasSize(1); this.applicationContext.close(); assertAllClosed(); } @@ -244,7 +242,7 @@ public class EndpointWebMvcAutoConfigurationTests { this.applicationContext.addApplicationListener(grabManagementPort); this.applicationContext.refresh(); int managementPort = grabManagementPort.getServletContainer().getPort(); - assertThat(managementPort, not(equalTo(ports.get().server))); + assertThat(managementPort).isNotEqualTo(ports.get().server); assertContent("/controller", ports.get().server, "controlleroutput"); assertContent("/endpoint", ports.get().server, null); assertContent("/controller", managementPort, null); @@ -337,8 +335,9 @@ public class EndpointWebMvcAutoConfigurationTests { EndpointWebMvcAutoConfiguration.class); this.applicationContext.refresh(); assertContent("/controller", ports.get().server, "controlleroutput"); - assertEquals("foo", - this.applicationContext.getBean(ServerProperties.class).getDisplayName()); + ServerProperties serverProperties = this.applicationContext + .getBean(ServerProperties.class); + assertThat(serverProperties.getDisplayName()).isEqualTo("foo"); this.applicationContext.close(); assertAllClosed(); } @@ -354,9 +353,9 @@ public class EndpointWebMvcAutoConfigurationTests { .getProperty("local.server.port", Integer.class); Integer localManagementPort = this.applicationContext.getEnvironment() .getProperty("local.management.port", Integer.class); - assertThat(localServerPort, notNullValue()); - assertThat(localManagementPort, notNullValue()); - assertThat(localServerPort, equalTo(localManagementPort)); + assertThat(localServerPort).isNotNull(); + assertThat(localManagementPort).isNotNull(); + assertThat(localServerPort).isEqualTo(localManagementPort); this.applicationContext.close(); assertAllClosed(); } @@ -373,11 +372,11 @@ public class EndpointWebMvcAutoConfigurationTests { .getProperty("local.server.port", Integer.class); Integer localManagementPort = this.applicationContext.getEnvironment() .getProperty("local.management.port", Integer.class); - assertThat(localServerPort, notNullValue()); - assertThat(localManagementPort, notNullValue()); - assertThat(localServerPort, not(equalTo(localManagementPort))); - assertThat(this.applicationContext.getBean(ServerPortConfig.class).getCount(), - equalTo(2)); + assertThat(localServerPort).isNotNull(); + assertThat(localManagementPort).isNotNull(); + assertThat(localServerPort).isNotEqualTo(localManagementPort); + assertThat(this.applicationContext.getBean(ServerPortConfig.class).getCount()) + .isEqualTo(2); this.applicationContext.close(); assertAllClosed(); } @@ -389,7 +388,7 @@ public class EndpointWebMvcAutoConfigurationTests { this.applicationContext.refresh(); RequestMappingInfoHandlerMapping mapping = this.applicationContext .getBean(RequestMappingInfoHandlerMapping.class); - assertThat(mapping, not(instanceOf(EndpointHandlerMapping.class))); + assertThat(mapping).isNotEqualTo(instanceOf(EndpointHandlerMapping.class)); } @Test @@ -398,8 +397,7 @@ public class EndpointWebMvcAutoConfigurationTests { ServerPortConfig.class, EndpointWebMvcAutoConfiguration.class); this.applicationContext.refresh(); // /health, /metrics, /env, /actuator (/shutdown is disabled by default) - assertThat(this.applicationContext.getBeansOfType(MvcEndpoint.class).size(), - is(equalTo(4))); + assertThat(this.applicationContext.getBeansOfType(MvcEndpoint.class)).hasSize(4); } @Test @@ -409,8 +407,7 @@ public class EndpointWebMvcAutoConfigurationTests { EnvironmentTestUtils.addEnvironment(this.applicationContext, "ENDPOINTS_ENABLED:false"); this.applicationContext.refresh(); - assertThat(this.applicationContext.getBeansOfType(MvcEndpoint.class).size(), - is(equalTo(0))); + assertThat(this.applicationContext.getBeansOfType(MvcEndpoint.class)).isEmpty(); } @Test @@ -450,9 +447,8 @@ public class EndpointWebMvcAutoConfigurationTests { EnvironmentTestUtils.addEnvironment(this.applicationContext, "endpoints.shutdown.enabled:true"); this.applicationContext.refresh(); - assertThat( - this.applicationContext.getBeansOfType(ShutdownMvcEndpoint.class).size(), - is(equalTo(1))); + assertThat(this.applicationContext.getBeansOfType(ShutdownMvcEndpoint.class)) + .hasSize(1); } private void endpointDisabled(String name, Class type) { @@ -461,7 +457,7 @@ public class EndpointWebMvcAutoConfigurationTests { EnvironmentTestUtils.addEnvironment(this.applicationContext, String.format("endpoints.%s.enabled:false", name)); this.applicationContext.refresh(); - assertThat(this.applicationContext.getBeansOfType(type).size(), is(equalTo(0))); + assertThat(this.applicationContext.getBeansOfType(type)).isEmpty(); } private void endpointEnabledOverride(String name, Class type) @@ -472,7 +468,7 @@ public class EndpointWebMvcAutoConfigurationTests { "endpoints.enabled:false", String.format("endpoints_%s_enabled:true", name)); this.applicationContext.refresh(); - assertThat(this.applicationContext.getBeansOfType(type).size(), is(equalTo(1))); + assertThat(this.applicationContext.getBeansOfType(type)).hasSize(1); } private void assertAllClosed() throws Exception { @@ -482,7 +478,6 @@ public class EndpointWebMvcAutoConfigurationTests { assertContent("/endpoint", ports.get().management, null); } - @SuppressWarnings("unchecked") public void assertContent(String url, int port, Object expected) throws Exception { SimpleClientHttpRequestFactory clientHttpRequestFactory = new SimpleClientHttpRequestFactory(); ClientHttpRequest request = clientHttpRequestFactory @@ -493,10 +488,10 @@ public class EndpointWebMvcAutoConfigurationTests { String actual = StreamUtils.copyToString(response.getBody(), Charset.forName("UTF-8")); if (expected instanceof Matcher) { - assertThat(actual, is((Matcher) expected)); + assertThat(actual).is(Matched.by((Matcher) expected)); } else { - assertThat(actual, equalTo(expected)); + assertThat(actual).isEqualTo(expected); } } finally { diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/HealthIndicatorAutoConfigurationTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/HealthIndicatorAutoConfigurationTests.java index 829066b958..d5dbcd4d5b 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/HealthIndicatorAutoConfigurationTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/HealthIndicatorAutoConfigurationTests.java @@ -57,8 +57,7 @@ import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.cassandra.core.CassandraOperations; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertSame; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; /** @@ -88,9 +87,9 @@ public class HealthIndicatorAutoConfigurationTests { this.context.refresh(); Map beans = this.context .getBeansOfType(HealthIndicator.class); - assertEquals(1, beans.size()); - assertEquals(ApplicationHealthIndicator.class, - beans.values().iterator().next().getClass()); + assertThat(beans).hasSize(1); + assertThat(beans.values().iterator().next().getClass()) + .isEqualTo(ApplicationHealthIndicator.class); } @Test @@ -102,9 +101,9 @@ public class HealthIndicatorAutoConfigurationTests { this.context.refresh(); Map beans = this.context .getBeansOfType(HealthIndicator.class); - assertEquals(1, beans.size()); - assertEquals(ApplicationHealthIndicator.class, - beans.values().iterator().next().getClass()); + assertThat(beans).hasSize(1); + assertThat(beans.values().iterator().next().getClass()) + .isEqualTo(ApplicationHealthIndicator.class); } @Test @@ -116,9 +115,9 @@ public class HealthIndicatorAutoConfigurationTests { this.context.refresh(); Map beans = this.context .getBeansOfType(HealthIndicator.class); - assertEquals(1, beans.size()); - assertSame(this.context.getBean("customHealthIndicator"), - beans.values().iterator().next()); + assertThat(beans).hasSize(1); + assertThat(this.context.getBean("customHealthIndicator")) + .isSameAs(beans.values().iterator().next()); } @Test @@ -131,9 +130,9 @@ public class HealthIndicatorAutoConfigurationTests { this.context.refresh(); Map beans = this.context .getBeansOfType(HealthIndicator.class); - assertEquals(1, beans.size()); - assertEquals(DiskSpaceHealthIndicator.class, - beans.values().iterator().next().getClass()); + assertThat(beans).hasSize(1); + assertThat(beans.values().iterator().next().getClass()) + .isEqualTo(DiskSpaceHealthIndicator.class); } @Test @@ -145,9 +144,9 @@ public class HealthIndicatorAutoConfigurationTests { this.context.refresh(); Map beans = this.context .getBeansOfType(HealthIndicator.class); - assertEquals(1, beans.size()); - assertEquals(RedisHealthIndicator.class, - beans.values().iterator().next().getClass()); + assertThat(beans).hasSize(1); + assertThat(beans.values().iterator().next().getClass()) + .isEqualTo(RedisHealthIndicator.class); } @Test @@ -160,9 +159,9 @@ public class HealthIndicatorAutoConfigurationTests { this.context.refresh(); Map beans = this.context .getBeansOfType(HealthIndicator.class); - assertEquals(1, beans.size()); - assertEquals(ApplicationHealthIndicator.class, - beans.values().iterator().next().getClass()); + assertThat(beans).hasSize(1); + assertThat(beans.values().iterator().next().getClass()) + .isEqualTo(ApplicationHealthIndicator.class); } @Test @@ -175,9 +174,9 @@ public class HealthIndicatorAutoConfigurationTests { this.context.refresh(); Map beans = this.context .getBeansOfType(HealthIndicator.class); - assertEquals(1, beans.size()); - assertEquals(MongoHealthIndicator.class, - beans.values().iterator().next().getClass()); + assertThat(beans).hasSize(1); + assertThat(beans.values().iterator().next().getClass()) + .isEqualTo(MongoHealthIndicator.class); } @Test @@ -191,9 +190,9 @@ public class HealthIndicatorAutoConfigurationTests { this.context.refresh(); Map beans = this.context .getBeansOfType(HealthIndicator.class); - assertEquals(1, beans.size()); - assertEquals(ApplicationHealthIndicator.class, - beans.values().iterator().next().getClass()); + assertThat(beans).hasSize(1); + assertThat(beans.values().iterator().next().getClass()) + .isEqualTo(ApplicationHealthIndicator.class); } @Test @@ -204,7 +203,7 @@ public class HealthIndicatorAutoConfigurationTests { this.context.refresh(); Map beans = this.context .getBeansOfType(HealthIndicator.class); - assertEquals(4, beans.size()); + assertThat(beans).hasSize(4); } @Test @@ -216,9 +215,9 @@ public class HealthIndicatorAutoConfigurationTests { this.context.refresh(); Map beans = this.context .getBeansOfType(HealthIndicator.class); - assertEquals(1, beans.size()); - assertEquals(DataSourceHealthIndicator.class, - beans.values().iterator().next().getClass()); + assertThat(beans).hasSize(1); + assertThat(beans.values().iterator().next().getClass()) + .isEqualTo(DataSourceHealthIndicator.class); } @Test @@ -234,11 +233,11 @@ public class HealthIndicatorAutoConfigurationTests { this.context.refresh(); Map beans = this.context .getBeansOfType(HealthIndicator.class); - assertEquals(1, beans.size()); + assertThat(beans).hasSize(1); HealthIndicator healthIndicator = beans.values().iterator().next(); - assertEquals(DataSourceHealthIndicator.class, healthIndicator.getClass()); + assertThat(healthIndicator.getClass()).isEqualTo(DataSourceHealthIndicator.class); DataSourceHealthIndicator dataSourceHealthIndicator = (DataSourceHealthIndicator) healthIndicator; - assertEquals("SELECT from FOOBAR", dataSourceHealthIndicator.getQuery()); + assertThat(dataSourceHealthIndicator.getQuery()).isEqualTo("SELECT from FOOBAR"); } @Test @@ -251,9 +250,9 @@ public class HealthIndicatorAutoConfigurationTests { this.context.refresh(); Map beans = this.context .getBeansOfType(HealthIndicator.class); - assertEquals(1, beans.size()); - assertEquals(ApplicationHealthIndicator.class, - beans.values().iterator().next().getClass()); + assertThat(beans).hasSize(1); + assertThat(beans.values().iterator().next().getClass()) + .isEqualTo(ApplicationHealthIndicator.class); } @Test @@ -265,9 +264,9 @@ public class HealthIndicatorAutoConfigurationTests { this.context.refresh(); Map beans = this.context .getBeansOfType(HealthIndicator.class); - assertEquals(1, beans.size()); - assertEquals(RabbitHealthIndicator.class, - beans.values().iterator().next().getClass()); + assertThat(beans).hasSize(1); + assertThat(beans.values().iterator().next().getClass()) + .isEqualTo(RabbitHealthIndicator.class); } @Test @@ -280,9 +279,9 @@ public class HealthIndicatorAutoConfigurationTests { this.context.refresh(); Map beans = this.context .getBeansOfType(HealthIndicator.class); - assertEquals(1, beans.size()); - assertEquals(ApplicationHealthIndicator.class, - beans.values().iterator().next().getClass()); + assertThat(beans).hasSize(1); + assertThat(beans.values().iterator().next().getClass()) + .isEqualTo(ApplicationHealthIndicator.class); } @Test @@ -294,9 +293,9 @@ public class HealthIndicatorAutoConfigurationTests { this.context.refresh(); Map beans = this.context .getBeansOfType(HealthIndicator.class); - assertEquals(1, beans.size()); - assertEquals(SolrHealthIndicator.class, - beans.values().iterator().next().getClass()); + assertThat(beans).hasSize(1); + assertThat(beans.values().iterator().next().getClass()) + .isEqualTo(SolrHealthIndicator.class); } @Test @@ -309,9 +308,9 @@ public class HealthIndicatorAutoConfigurationTests { this.context.refresh(); Map beans = this.context .getBeansOfType(HealthIndicator.class); - assertEquals(1, beans.size()); - assertEquals(ApplicationHealthIndicator.class, - beans.values().iterator().next().getClass()); + assertThat(beans).hasSize(1); + assertThat(beans.values().iterator().next().getClass()) + .isEqualTo(ApplicationHealthIndicator.class); } @Test @@ -320,9 +319,9 @@ public class HealthIndicatorAutoConfigurationTests { this.context.refresh(); Map beans = this.context .getBeansOfType(HealthIndicator.class); - assertEquals(1, beans.size()); - assertEquals(DiskSpaceHealthIndicator.class, - beans.values().iterator().next().getClass()); + assertThat(beans).hasSize(1); + assertThat(beans.values().iterator().next().getClass()) + .isEqualTo(DiskSpaceHealthIndicator.class); } @Test @@ -336,9 +335,9 @@ public class HealthIndicatorAutoConfigurationTests { Map beans = this.context .getBeansOfType(HealthIndicator.class); - assertEquals(1, beans.size()); - assertEquals(MailHealthIndicator.class, - beans.values().iterator().next().getClass()); + assertThat(beans).hasSize(1); + assertThat(beans.values().iterator().next().getClass()) + .isEqualTo(MailHealthIndicator.class); } @Test @@ -352,9 +351,9 @@ public class HealthIndicatorAutoConfigurationTests { Map beans = this.context .getBeansOfType(HealthIndicator.class); - assertEquals(1, beans.size()); - assertEquals(ApplicationHealthIndicator.class, - beans.values().iterator().next().getClass()); + assertThat(beans).hasSize(1); + assertThat(beans.values().iterator().next().getClass()) + .isEqualTo(ApplicationHealthIndicator.class); } @Test @@ -367,9 +366,9 @@ public class HealthIndicatorAutoConfigurationTests { Map beans = this.context .getBeansOfType(HealthIndicator.class); - assertEquals(1, beans.size()); - assertEquals(JmsHealthIndicator.class, - beans.values().iterator().next().getClass()); + assertThat(beans).hasSize(1); + assertThat(beans.values().iterator().next().getClass()) + .isEqualTo(JmsHealthIndicator.class); } @Test @@ -383,9 +382,9 @@ public class HealthIndicatorAutoConfigurationTests { Map beans = this.context .getBeansOfType(HealthIndicator.class); - assertEquals(1, beans.size()); - assertEquals(ApplicationHealthIndicator.class, - beans.values().iterator().next().getClass()); + assertThat(beans).hasSize(1); + assertThat(beans.values().iterator().next().getClass()) + .isEqualTo(ApplicationHealthIndicator.class); } @Test @@ -400,9 +399,9 @@ public class HealthIndicatorAutoConfigurationTests { Map beans = this.context .getBeansOfType(HealthIndicator.class); - assertEquals(1, beans.size()); - assertEquals(ElasticsearchHealthIndicator.class, - beans.values().iterator().next().getClass()); + assertThat(beans).hasSize(1); + assertThat(beans.values().iterator().next().getClass()) + .isEqualTo(ElasticsearchHealthIndicator.class); } @Test @@ -418,9 +417,9 @@ public class HealthIndicatorAutoConfigurationTests { Map beans = this.context .getBeansOfType(HealthIndicator.class); - assertEquals(1, beans.size()); - assertEquals(ApplicationHealthIndicator.class, - beans.values().iterator().next().getClass()); + assertThat(beans).hasSize(1); + assertThat(beans.values().iterator().next().getClass()) + .isEqualTo(ApplicationHealthIndicator.class); } @Test @@ -432,9 +431,9 @@ public class HealthIndicatorAutoConfigurationTests { this.context.refresh(); Map beans = this.context .getBeansOfType(HealthIndicator.class); - assertEquals(1, beans.size()); - assertEquals(CassandraHealthIndicator.class, - beans.values().iterator().next().getClass()); + assertThat(beans).hasSize(1); + assertThat(beans.values().iterator().next().getClass()) + .isEqualTo(CassandraHealthIndicator.class); } @Configuration diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/HealthMvcEndpointAutoConfigurationTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/HealthMvcEndpointAutoConfigurationTests.java index 0c00865d86..d886083736 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/HealthMvcEndpointAutoConfigurationTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/HealthMvcEndpointAutoConfigurationTests.java @@ -35,7 +35,7 @@ import org.springframework.context.annotation.Configuration; import org.springframework.mock.web.MockServletContext; import org.springframework.web.context.support.AnnotationConfigWebApplicationContext; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link EndpointWebMvcAutoConfiguration} of the {@link HealthMvcEndpoint}. @@ -62,8 +62,8 @@ public class HealthMvcEndpointAutoConfigurationTests { this.context.refresh(); Health health = (Health) this.context.getBean(HealthMvcEndpoint.class) .invoke(null); - assertEquals(Status.UP, health.getStatus()); - assertEquals(null, health.getDetails().get("foo")); + assertThat(health.getStatus()).isEqualTo(Status.UP); + assertThat(health.getDetails().get("foo")).isNull(); } @Test @@ -76,9 +76,9 @@ public class HealthMvcEndpointAutoConfigurationTests { this.context.refresh(); Health health = (Health) this.context.getBean(HealthMvcEndpoint.class) .invoke(null); - assertEquals(Status.UP, health.getStatus()); + assertThat(health.getStatus()).isEqualTo(Status.UP); Health map = (Health) health.getDetails().get("test"); - assertEquals("bar", map.getDetails().get("foo")); + assertThat(map.getDetails().get("foo")).isEqualTo("bar"); } @Configuration diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/JolokiaAutoConfigurationTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/JolokiaAutoConfigurationTests.java index b0172767db..48619e7df1 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/JolokiaAutoConfigurationTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/JolokiaAutoConfigurationTests.java @@ -41,7 +41,7 @@ import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import org.springframework.test.web.servlet.result.MockMvcResultMatchers; import org.springframework.test.web.servlet.setup.MockMvcBuilders; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link JolokiaAutoConfiguration}. @@ -74,8 +74,7 @@ public class JolokiaAutoConfigurationTests { HttpMessageConvertersAutoConfiguration.class, JolokiaAutoConfiguration.class); this.context.refresh(); - assertEquals(1, - this.context.getBeanNamesForType(JolokiaMvcEndpoint.class).length); + assertThat(this.context.getBeanNamesForType(JolokiaMvcEndpoint.class)).hasSize(1); } @Test @@ -89,8 +88,7 @@ public class JolokiaAutoConfigurationTests { HttpMessageConvertersAutoConfiguration.class, JolokiaAutoConfiguration.class); this.context.refresh(); - assertEquals(1, - this.context.getBeanNamesForType(JolokiaMvcEndpoint.class).length); + assertThat(this.context.getBeanNamesForType(JolokiaMvcEndpoint.class)).hasSize(1); MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(this.context).build(); mockMvc.perform(MockMvcRequestBuilders.get("/foo/bar")) .andExpect(MockMvcResultMatchers.content() @@ -122,8 +120,7 @@ public class JolokiaAutoConfigurationTests { HttpMessageConvertersAutoConfiguration.class, JolokiaAutoConfiguration.class); this.context.refresh(); - assertEquals(0, - this.context.getBeanNamesForType(JolokiaMvcEndpoint.class).length); + assertThat(this.context.getBeanNamesForType(JolokiaMvcEndpoint.class)).isEmpty(); } private void assertEndpointEnabled(String... pairs) { @@ -135,8 +132,7 @@ public class JolokiaAutoConfigurationTests { HttpMessageConvertersAutoConfiguration.class, JolokiaAutoConfiguration.class); this.context.refresh(); - assertEquals(1, - this.context.getBeanNamesForType(JolokiaMvcEndpoint.class).length); + assertThat(this.context.getBeanNamesForType(JolokiaMvcEndpoint.class)).hasSize(1); } @Configuration diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/ManagementServerPropertiesAutoConfigurationTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/ManagementServerPropertiesAutoConfigurationTests.java index 96917c57c3..295afb6d55 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/ManagementServerPropertiesAutoConfigurationTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/ManagementServerPropertiesAutoConfigurationTests.java @@ -18,9 +18,7 @@ package org.springframework.boot.actuate.autoconfigure; import org.junit.Test; -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 ManagementServerPropertiesAutoConfiguration}. @@ -33,8 +31,8 @@ public class ManagementServerPropertiesAutoConfigurationTests { @Test public void defaultManagementServerProperties() { ManagementServerProperties properties = new ManagementServerProperties(); - assertThat(properties.getPort(), nullValue()); - assertThat(properties.getContextPath(), equalTo("")); + assertThat(properties.getPort()).isNull(); + assertThat(properties.getContextPath()).isEqualTo(""); } @Test @@ -42,22 +40,22 @@ public class ManagementServerPropertiesAutoConfigurationTests { ManagementServerProperties properties = new ManagementServerProperties(); properties.setPort(123); properties.setContextPath("/foo"); - assertThat(properties.getPort(), equalTo(123)); - assertThat(properties.getContextPath(), equalTo("/foo")); + assertThat(properties.getPort()).isEqualTo(123); + assertThat(properties.getContextPath()).isEqualTo("/foo"); } @Test public void trailingSlashOfContextPathIsRemoved() { ManagementServerProperties properties = new ManagementServerProperties(); properties.setContextPath("/foo/"); - assertThat(properties.getContextPath(), equalTo("/foo")); + assertThat(properties.getContextPath()).isEqualTo("/foo"); } @Test public void slashOfContextPathIsDefaultValue() { ManagementServerProperties properties = new ManagementServerProperties(); properties.setContextPath("/"); - assertThat(properties.getContextPath(), equalTo("")); + assertThat(properties.getContextPath()).isEqualTo(""); } } diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/ManagementWebSecurityAutoConfigurationTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/ManagementWebSecurityAutoConfigurationTests.java index 40b806ca18..804a6bfaeb 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/ManagementWebSecurityAutoConfigurationTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/ManagementWebSecurityAutoConfigurationTests.java @@ -16,6 +16,8 @@ package org.springframework.boot.actuate.autoconfigure; +import java.util.ArrayList; + import javax.servlet.Filter; import org.hamcrest.Matchers; @@ -42,6 +44,7 @@ import org.springframework.security.config.annotation.authentication.builders.Au import org.springframework.security.config.annotation.authentication.configuration.EnableGlobalAuthentication; import org.springframework.security.core.Authentication; import org.springframework.security.core.AuthenticationException; +import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.AuthorityUtils; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; @@ -55,12 +58,7 @@ import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.util.StringUtils; import org.springframework.web.context.support.AnnotationConfigWebApplicationContext; -import static org.hamcrest.Matchers.greaterThan; -import static org.hamcrest.Matchers.hasSize; -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.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers.springSecurity; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @@ -96,21 +94,20 @@ public class ManagementWebSecurityAutoConfigurationTests { PropertyPlaceholderAutoConfiguration.class); EnvironmentTestUtils.addEnvironment(this.context, "security.basic.enabled:false"); this.context.refresh(); - assertNotNull(this.context.getBean(AuthenticationManagerBuilder.class)); + assertThat(this.context.getBean(AuthenticationManagerBuilder.class)).isNotNull(); FilterChainProxy filterChainProxy = this.context.getBean(FilterChainProxy.class); // 1 for static resources, one for management endpoints and one for the rest - assertThat(filterChainProxy.getFilterChains(), hasSize(3)); - assertThat(filterChainProxy.getFilters("/beans"), hasSize(greaterThan(0))); - assertThat(filterChainProxy.getFilters("/beans/"), hasSize(greaterThan(0))); - assertThat(filterChainProxy.getFilters("/beans.foo"), hasSize(greaterThan(0))); - assertThat(filterChainProxy.getFilters("/beans/foo/bar"), - hasSize(greaterThan(0))); + assertThat(filterChainProxy.getFilterChains()).hasSize(3); + assertThat(filterChainProxy.getFilters("/beans")).isNotEmpty(); + assertThat(filterChainProxy.getFilters("/beans/")).isNotEmpty(); + assertThat(filterChainProxy.getFilters("/beans.foo")).isNotEmpty(); + assertThat(filterChainProxy.getFilters("/beans/foo/bar")).isNotEmpty(); } @Test public void testPathNormalization() throws Exception { String path = "admin/./error"; - assertEquals("admin/error", StringUtils.cleanPath(path)); + assertThat(StringUtils.cleanPath(path)).isEqualTo("admin/error"); } @Test @@ -120,8 +117,10 @@ public class ManagementWebSecurityAutoConfigurationTests { this.context.register(WebConfiguration.class); this.context.refresh(); UserDetails user = getUser(); - assertTrue(user.getAuthorities().containsAll(AuthorityUtils - .commaSeparatedStringToAuthorityList("ROLE_USER,ROLE_ADMIN"))); + ArrayList authorities = new ArrayList( + user.getAuthorities()); + assertThat(authorities).containsAll(AuthorityUtils + .commaSeparatedStringToAuthorityList("ROLE_USER,ROLE_ADMIN")); } private UserDetails getUser() { @@ -147,8 +146,8 @@ public class ManagementWebSecurityAutoConfigurationTests { EnvironmentTestUtils.addEnvironment(this.context, "security.ignored:none"); this.context.refresh(); // Just the application and management endpoints now - assertEquals(2, - this.context.getBean(FilterChainProxy.class).getFilterChains().size()); + assertThat(this.context.getBean(FilterChainProxy.class).getFilterChains()) + .hasSize(2); } @Test @@ -160,8 +159,8 @@ public class ManagementWebSecurityAutoConfigurationTests { this.context.refresh(); // Just the management endpoints (one filter) and ignores now plus the backup // filter on app endpoints - assertEquals(3, - this.context.getBean(FilterChainProxy.class).getFilterChains().size()); + assertThat(this.context.getBean(FilterChainProxy.class).getFilterChains()) + .hasSize(3); } @Test @@ -174,8 +173,8 @@ public class ManagementWebSecurityAutoConfigurationTests { ManagementServerPropertiesAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); this.context.refresh(); - assertEquals(this.context.getBean(TestConfiguration.class).authenticationManager, - this.context.getBean(AuthenticationManager.class)); + assertThat(this.context.getBean(AuthenticationManager.class)).isEqualTo( + this.context.getBean(TestConfiguration.class).authenticationManager); } @Test @@ -188,8 +187,8 @@ public class ManagementWebSecurityAutoConfigurationTests { ManagementServerPropertiesAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); this.context.refresh(); - assertEquals(this.context.getBean(TestConfiguration.class).authenticationManager, - this.context.getBean(AuthenticationManager.class)); + assertThat(this.context.getBean(AuthenticationManager.class)).isEqualTo( + this.context.getBean(TestConfiguration.class).authenticationManager); } // gh-2466 diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/MetricExportAutoConfigurationTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/MetricExportAutoConfigurationTests.java index 288d9bf1a1..1b61424566 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/MetricExportAutoConfigurationTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/MetricExportAutoConfigurationTests.java @@ -42,9 +42,7 @@ import org.springframework.messaging.MessageHandler; import org.springframework.messaging.MessagingException; import org.springframework.messaging.SubscribableChannel; -import static org.hamcrest.Matchers.notNullValue; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link MetricExportAutoConfiguration}. @@ -76,7 +74,7 @@ public class MetricExportAutoConfigurationTests { MetricExportAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); MetricExporters exporter = this.context.getBean(MetricExporters.class); - assertNotNull(exporter); + assertThat(exporter).isNotNull(); } @Test @@ -86,7 +84,7 @@ public class MetricExportAutoConfigurationTests { MetricExportAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); GaugeService gaugeService = this.context.getBean(GaugeService.class); - assertNotNull(gaugeService); + assertThat(gaugeService).isNotNull(); gaugeService.submit("foo", 2.7); MetricExporters exporters = this.context.getBean(MetricExporters.class); MetricCopyExporter exporter = (MetricCopyExporter) exporters.getExporters() @@ -132,7 +130,7 @@ public class MetricExportAutoConfigurationTests { MetricExportAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); this.context.refresh(); - assertThat(this.context.getBean(StatsdMetricWriter.class), notNullValue()); + assertThat(this.context.getBean(StatsdMetricWriter.class)).isNotNull(); } @Configuration diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/MetricFilterAutoConfigurationTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/MetricFilterAutoConfigurationTests.java index ff31fa1584..19c96adaf7 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/MetricFilterAutoConfigurationTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/MetricFilterAutoConfigurationTests.java @@ -53,11 +53,10 @@ import org.springframework.web.context.request.async.DeferredResult; import org.springframework.web.filter.OncePerRequestFilter; import org.springframework.web.util.NestedServletException; -import static org.hamcrest.Matchers.equalTo; +import static org.assertj.core.api.Assertions.assertThat; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.notNullValue; import static org.hamcrest.Matchers.nullValue; -import static org.junit.Assert.assertThat; import static org.junit.Assert.fail; import static org.mockito.BDDMockito.willAnswer; import static org.mockito.BDDMockito.willThrow; @@ -173,7 +172,7 @@ public class MetricFilterAutoConfigurationTests { public void skipsFilterIfMissingServices() throws Exception { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext( MetricFilterAutoConfiguration.class); - assertThat(context.getBeansOfType(Filter.class).size(), equalTo(0)); + assertThat(context.getBeansOfType(Filter.class).size()).isEqualTo(0); context.close(); } @@ -184,7 +183,7 @@ public class MetricFilterAutoConfigurationTests { "endpoints.metrics.filter.enabled:false"); context.register(Config.class, MetricFilterAutoConfiguration.class); context.refresh(); - assertThat(context.getBeansOfType(Filter.class).size(), equalTo(0)); + assertThat(context.getBeansOfType(Filter.class).size()).isEqualTo(0); context.close(); } @@ -269,7 +268,7 @@ public class MetricFilterAutoConfigurationTests { fail(); } catch (Exception ex) { - assertThat(result.getRequest().getAttribute(attributeName), is(nullValue())); + assertThat(result.getRequest().getAttribute(attributeName)).isNull(); verify(context.getBean(CounterService.class)) .increment("status.500.createFailure"); } diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/MetricRepositoryAutoConfigurationTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/MetricRepositoryAutoConfigurationTests.java index 33298b2d4b..44fb330da1 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/MetricRepositoryAutoConfigurationTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/MetricRepositoryAutoConfigurationTests.java @@ -33,10 +33,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.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; /** @@ -61,12 +58,12 @@ public class MetricRepositoryAutoConfigurationTests { this.context = new AnnotationConfigApplicationContext( MetricRepositoryAutoConfiguration.class); GaugeService gaugeService = this.context.getBean(BufferGaugeService.class); - assertNotNull(gaugeService); - assertNotNull(this.context.getBean(BufferCounterService.class)); - assertNotNull(this.context.getBean(PrefixMetricReader.class)); + assertThat(gaugeService).isNotNull(); + assertThat(this.context.getBean(BufferCounterService.class)).isNotNull(); + assertThat(this.context.getBean(PrefixMetricReader.class)).isNotNull(); gaugeService.submit("foo", 2.7); - assertEquals(2.7, - this.context.getBean(MetricReader.class).findOne("gauge.foo").getValue()); + MetricReader bean = this.context.getBean(MetricReader.class); + assertThat(bean.findOne("gauge.foo").getValue()).isEqualTo(2.7); } @Test @@ -75,25 +72,23 @@ public class MetricRepositoryAutoConfigurationTests { MetricsDropwizardAutoConfiguration.class, MetricRepositoryAutoConfiguration.class, AopAutoConfiguration.class); GaugeService gaugeService = this.context.getBean(GaugeService.class); - assertNotNull(gaugeService); + assertThat(gaugeService).isNotNull(); gaugeService.submit("foo", 2.7); DropwizardMetricServices exporter = this.context .getBean(DropwizardMetricServices.class); - assertEquals(gaugeService, exporter); + assertThat(exporter).isEqualTo(gaugeService); MetricRegistry registry = this.context.getBean(MetricRegistry.class); @SuppressWarnings("unchecked") Gauge gauge = (Gauge) registry.getMetrics().get("gauge.foo"); - assertEquals(new Double(2.7), gauge.getValue()); + assertThat(gauge.getValue()).isEqualTo(new Double(2.7)); } @Test public void skipsIfBeansExist() throws Exception { this.context = new AnnotationConfigApplicationContext(Config.class, MetricRepositoryAutoConfiguration.class); - assertThat(this.context.getBeansOfType(BufferGaugeService.class).size(), - equalTo(0)); - assertThat(this.context.getBeansOfType(BufferCounterService.class).size(), - equalTo(0)); + assertThat(this.context.getBeansOfType(BufferGaugeService.class)).isEmpty(); + assertThat(this.context.getBeansOfType(BufferCounterService.class)).isEmpty(); } @Configuration diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/PublicMetricsAutoConfigurationTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/PublicMetricsAutoConfigurationTests.java index 1d5c45c265..f46f111ed5 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/PublicMetricsAutoConfigurationTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/PublicMetricsAutoConfigurationTests.java @@ -59,10 +59,7 @@ import org.springframework.jdbc.core.ConnectionCallback; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.util.SocketUtils; -import static org.hamcrest.Matchers.hasKey; -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; import static org.junit.Assert.fail; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; @@ -88,14 +85,14 @@ public class PublicMetricsAutoConfigurationTests { @Test public void systemPublicMetrics() throws Exception { load(); - assertEquals(1, this.context.getBeansOfType(SystemPublicMetrics.class).size()); + assertThat(this.context.getBeansOfType(SystemPublicMetrics.class)).hasSize(1); } @Test public void metricReaderPublicMetrics() throws Exception { load(); - assertEquals(1, - this.context.getBeansOfType(MetricReaderPublicMetrics.class).size()); + assertThat(this.context.getBeansOfType(MetricReaderPublicMetrics.class)) + .hasSize(1); } @Test @@ -104,15 +101,15 @@ public class PublicMetricsAutoConfigurationTests { RichGaugeReaderConfig.class, MetricRepositoryAutoConfiguration.class, PublicMetricsAutoConfiguration.class); RichGaugeReader richGaugeReader = context.getBean(RichGaugeReader.class); - assertNotNull(richGaugeReader); + assertThat(richGaugeReader).isNotNull(); given(richGaugeReader.findAll()) .willReturn(Collections.singletonList(new RichGauge("bar", 3.7d))); RichGaugeReaderPublicMetrics publicMetrics = context .getBean(RichGaugeReaderPublicMetrics.class); - assertNotNull(publicMetrics); + assertThat(publicMetrics).isNotNull(); Collection> metrics = publicMetrics.metrics(); - assertNotNull(metrics); - assertEquals(metrics.size(), 6); + assertThat(metrics).isNotNull(); + assertThat(6).isEqualTo(metrics.size()); assertHasMetric(metrics, new Metric("bar.val", 3.7d)); assertHasMetric(metrics, new Metric("bar.avg", 3.7d)); assertHasMetric(metrics, new Metric("bar.min", 3.7d)); @@ -125,8 +122,7 @@ public class PublicMetricsAutoConfigurationTests { @Test public void noDataSource() { load(); - assertEquals(0, - this.context.getBeansOfType(DataSourcePublicMetrics.class).size()); + assertThat(this.context.getBeansOfType(DataSourcePublicMetrics.class)).isEmpty(); } @Test @@ -194,13 +190,13 @@ public class PublicMetricsAutoConfigurationTests { @Test public void tomcatMetrics() throws Exception { loadWeb(TomcatConfiguration.class); - assertEquals(1, this.context.getBeansOfType(TomcatPublicMetrics.class).size()); + assertThat(this.context.getBeansOfType(TomcatPublicMetrics.class)).hasSize(1); } @Test public void noCacheMetrics() { load(); - assertEquals(0, this.context.getBeansOfType(CachePublicMetrics.class).size()); + assertThat(this.context.getBeansOfType(CachePublicMetrics.class)).isEmpty(); } @Test @@ -236,7 +232,7 @@ public class PublicMetricsAutoConfigurationTests { content.put(metric.getName(), metric.getValue()); } for (String key : keys) { - assertThat(content, hasKey(key)); + assertThat(content).containsKey(key); } } diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/ShellPropertiesTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/ShellPropertiesTests.java index d442f92f5c..a10e3bc5ba 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/ShellPropertiesTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/ShellPropertiesTests.java @@ -40,11 +40,7 @@ import org.springframework.mock.env.MockEnvironment; import org.springframework.mock.web.MockServletContext; import org.springframework.web.context.support.AnnotationConfigWebApplicationContext; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link ShellProperties}. @@ -59,8 +55,8 @@ public class ShellPropertiesTests { RelaxedDataBinder binder = new RelaxedDataBinder(props, "shell"); binder.bind(new MutablePropertyValues( Collections.singletonMap("shell.auth", "spring"))); - assertFalse(binder.getBindingResult().hasErrors()); - assertEquals("spring", props.getAuth()); + assertThat(binder.getBindingResult().hasErrors()).isFalse(); + assertThat(props.getAuth()).isEqualTo("spring"); } @Test @@ -69,8 +65,8 @@ public class ShellPropertiesTests { RelaxedDataBinder binder = new RelaxedDataBinder(props, "shell"); binder.bind( new MutablePropertyValues(Collections.singletonMap("shell.auth", ""))); - assertTrue(binder.getBindingResult().hasErrors()); - assertEquals("simple", props.getAuth()); + assertThat(binder.getBindingResult().hasErrors()).isTrue(); + assertThat(props.getAuth()).isEqualTo("simple"); } @Test @@ -80,8 +76,8 @@ public class ShellPropertiesTests { binder.setConversionService(new DefaultConversionService()); binder.bind(new MutablePropertyValues( Collections.singletonMap("shell.command_refresh_interval", "1"))); - assertFalse(binder.getBindingResult().hasErrors()); - assertEquals(1, props.getCommandRefreshInterval()); + assertThat(binder.getBindingResult().hasErrors()).isFalse(); + assertThat(props.getCommandRefreshInterval()).isEqualTo(1); } @Test @@ -91,8 +87,8 @@ public class ShellPropertiesTests { binder.setConversionService(new DefaultConversionService()); binder.bind(new MutablePropertyValues(Collections .singletonMap("shell.command_path_patterns", "pattern1, pattern2"))); - assertFalse(binder.getBindingResult().hasErrors()); - assertEquals(2, props.getCommandPathPatterns().length); + assertThat(binder.getBindingResult().hasErrors()).isFalse(); + assertThat(props.getCommandPathPatterns().length).isEqualTo(2); Assert.assertArrayEquals(new String[] { "pattern1", "pattern2" }, props.getCommandPathPatterns()); } @@ -104,8 +100,8 @@ public class ShellPropertiesTests { binder.setConversionService(new DefaultConversionService()); binder.bind(new MutablePropertyValues(Collections .singletonMap("shell.config_path_patterns", "pattern1, pattern2"))); - assertFalse(binder.getBindingResult().hasErrors()); - assertEquals(2, props.getConfigPathPatterns().length); + assertThat(binder.getBindingResult().hasErrors()).isFalse(); + assertThat(props.getConfigPathPatterns().length).isEqualTo(2); Assert.assertArrayEquals(new String[] { "pattern1", "pattern2" }, props.getConfigPathPatterns()); } @@ -117,10 +113,9 @@ public class ShellPropertiesTests { binder.setConversionService(new DefaultConversionService()); binder.bind(new MutablePropertyValues(Collections .singletonMap("shell.disabled_plugins", "pattern1, pattern2"))); - assertFalse(binder.getBindingResult().hasErrors()); - assertEquals(2, props.getDisabledPlugins().length); - assertArrayEquals(new String[] { "pattern1", "pattern2" }, - props.getDisabledPlugins()); + assertThat(binder.getBindingResult().hasErrors()).isFalse(); + assertThat(props.getDisabledPlugins().length).isEqualTo(2); + assertThat(props.getDisabledPlugins()).containsExactly("pattern1", "pattern2"); } @Test @@ -130,10 +125,8 @@ public class ShellPropertiesTests { binder.setConversionService(new DefaultConversionService()); binder.bind(new MutablePropertyValues(Collections .singletonMap("shell.disabled_commands", "pattern1, pattern2"))); - assertFalse(binder.getBindingResult().hasErrors()); - assertEquals(2, props.getDisabledCommands().length); - assertArrayEquals(new String[] { "pattern1", "pattern2" }, - props.getDisabledCommands()); + assertThat(binder.getBindingResult().hasErrors()).isFalse(); + assertThat(props.getDisabledCommands()).containsExactly("pattern1", "pattern2"); } @Test @@ -146,12 +139,12 @@ public class ShellPropertiesTests { map.put("shell.ssh.port", "2222"); map.put("shell.ssh.key_path", "~/.ssh/test.pem"); binder.bind(new MutablePropertyValues(map)); - assertFalse(binder.getBindingResult().hasErrors()); + assertThat(binder.getBindingResult().hasErrors()).isFalse(); Properties p = props.asCrshShellConfig(); - assertEquals("2222", p.get("crash.ssh.port")); - assertEquals("~/.ssh/test.pem", p.get("crash.ssh.keypath")); + assertThat(p.get("crash.ssh.port")).isEqualTo("2222"); + assertThat(p.get("crash.ssh.keypath")).isEqualTo("~/.ssh/test.pem"); } @Test @@ -164,12 +157,12 @@ public class ShellPropertiesTests { map.put("shell.ssh.port", "2222"); map.put("shell.ssh.key_path", "~/.ssh/test.pem"); binder.bind(new MutablePropertyValues(map)); - assertFalse(binder.getBindingResult().hasErrors()); + assertThat(binder.getBindingResult().hasErrors()).isFalse(); Properties p = props.asCrshShellConfig(); - assertNull(p.get("crash.ssh.port")); - assertNull(p.get("crash.ssh.keypath")); + assertThat(p.get("crash.ssh.port")).isNull(); + assertThat(p.get("crash.ssh.keypath")).isNull(); } @Test @@ -181,11 +174,11 @@ public class ShellPropertiesTests { map.put("shell.telnet.enabled", "true"); map.put("shell.telnet.port", "2222"); binder.bind(new MutablePropertyValues(map)); - assertFalse(binder.getBindingResult().hasErrors()); + assertThat(binder.getBindingResult().hasErrors()).isFalse(); Properties p = props.asCrshShellConfig(); - assertEquals("2222", p.get("crash.telnet.port")); + assertThat(p.get("crash.telnet.port")).isEqualTo("2222"); } @Test @@ -197,11 +190,11 @@ public class ShellPropertiesTests { map.put("shell.telnet.enabled", "false"); map.put("shell.telnet.port", "2222"); binder.bind(new MutablePropertyValues(map)); - assertFalse(binder.getBindingResult().hasErrors()); + assertThat(binder.getBindingResult().hasErrors()).isFalse(); Properties p = props.asCrshShellConfig(); - assertNull(p.get("crash.telnet.port")); + assertThat(p.get("crash.telnet.port")).isNull(); } @Test @@ -212,12 +205,12 @@ public class ShellPropertiesTests { Map map = new HashMap(); map.put("shell.auth.jaas.domain", "my-test-domain"); binder.bind(new MutablePropertyValues(map)); - assertFalse(binder.getBindingResult().hasErrors()); + assertThat(binder.getBindingResult().hasErrors()).isFalse(); Properties p = new Properties(); props.applyToCrshShellConfig(p); - assertEquals("my-test-domain", p.get("crash.auth.jaas.domain")); + assertThat(p.get("crash.auth.jaas.domain")).isEqualTo("my-test-domain"); } @Test @@ -228,12 +221,12 @@ public class ShellPropertiesTests { Map map = new HashMap(); map.put("shell.auth.key.path", "~/.ssh/test.pem"); binder.bind(new MutablePropertyValues(map)); - assertFalse(binder.getBindingResult().hasErrors()); + assertThat(binder.getBindingResult().hasErrors()).isFalse(); Properties p = new Properties(); props.applyToCrshShellConfig(p); - assertEquals("~/.ssh/test.pem", p.get("crash.auth.key.path")); + assertThat(p.get("crash.auth.key.path")).isEqualTo("~/.ssh/test.pem"); } @Test @@ -243,12 +236,12 @@ public class ShellPropertiesTests { binder.setConversionService(new DefaultConversionService()); Map map = new HashMap(); binder.bind(new MutablePropertyValues(map)); - assertFalse(binder.getBindingResult().hasErrors()); + assertThat(binder.getBindingResult().hasErrors()).isFalse(); Properties p = new Properties(); props.applyToCrshShellConfig(p); - assertNull(p.get("crash.auth.key.path")); + assertThat(p.get("crash.auth.key.path")).isNull(); } @Test @@ -260,13 +253,13 @@ public class ShellPropertiesTests { map.put("shell.auth.simple.user.name", "username123"); map.put("shell.auth.simple.user.password", "password123"); binder.bind(new MutablePropertyValues(map)); - assertFalse(binder.getBindingResult().hasErrors()); + assertThat(binder.getBindingResult().hasErrors()).isFalse(); Properties p = new Properties(); props.applyToCrshShellConfig(p); - assertEquals("username123", p.get("crash.auth.simple.username")); - assertEquals("password123", p.get("crash.auth.simple.password")); + assertThat(p.get("crash.auth.simple.username")).isEqualTo("username123"); + assertThat(p.get("crash.auth.simple.password")).isEqualTo("password123"); } @Test @@ -275,8 +268,8 @@ public class ShellPropertiesTests { RelaxedDataBinder binder = new RelaxedDataBinder(security, "security"); binder.bind(new MutablePropertyValues(Collections .singletonMap("shell.auth.simple.user.password", "${ADMIN_PASSWORD}"))); - assertFalse(binder.getBindingResult().hasErrors()); - assertTrue(security.getUser().isDefaultPassword()); + assertThat(binder.getBindingResult().hasErrors()).isFalse(); + assertThat(security.getUser().isDefaultPassword()).isTrue(); } @Test @@ -285,8 +278,8 @@ public class ShellPropertiesTests { RelaxedDataBinder binder = new RelaxedDataBinder(security, "security"); binder.bind(new MutablePropertyValues( Collections.singletonMap("shell.auth.simple.user.password", ""))); - assertFalse(binder.getBindingResult().hasErrors()); - assertTrue(security.getUser().isDefaultPassword()); + assertThat(binder.getBindingResult().hasErrors()).isFalse(); + assertThat(security.getUser().isDefaultPassword()).isTrue(); } @Test @@ -295,12 +288,12 @@ public class ShellPropertiesTests { RelaxedDataBinder binder = new RelaxedDataBinder(props, "shell.auth.spring"); binder.bind(new MutablePropertyValues( Collections.singletonMap("shell.auth.spring.roles", "role1, role2"))); - assertFalse(binder.getBindingResult().hasErrors()); + assertThat(binder.getBindingResult().hasErrors()).isFalse(); Properties p = new Properties(); props.applyToCrshShellConfig(p); - assertEquals("role1,role2", p.get("crash.auth.spring.roles")); + assertThat(p.get("crash.auth.spring.roles")).isEqualTo("role1,role2"); } @Test @@ -316,7 +309,7 @@ public class ShellPropertiesTests { PluginLifeCycle lifeCycle = context.getBean(PluginLifeCycle.class); String uuid = lifeCycle.getConfig().getProperty("test.uuid"); - assertEquals(TestShellConfiguration.uuid, uuid); + assertThat(uuid).isEqualTo(TestShellConfiguration.uuid); context.close(); } diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/TraceRepositoryAutoConfigurationTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/TraceRepositoryAutoConfigurationTests.java index cec5c97a9d..bd0523fc79 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/TraceRepositoryAutoConfigurationTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/TraceRepositoryAutoConfigurationTests.java @@ -24,9 +24,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.assertNotNull; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; /** @@ -40,7 +38,7 @@ public class TraceRepositoryAutoConfigurationTests { public void configuresInMemoryTraceRepository() throws Exception { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext( TraceRepositoryAutoConfiguration.class); - assertNotNull(context.getBean(InMemoryTraceRepository.class)); + assertThat(context.getBean(InMemoryTraceRepository.class)).isNotNull(); context.close(); } @@ -48,9 +46,8 @@ public class TraceRepositoryAutoConfigurationTests { public void skipsIfRepositoryExists() throws Exception { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext( Config.class, TraceRepositoryAutoConfiguration.class); - assertThat(context.getBeansOfType(InMemoryTraceRepository.class).size(), - equalTo(0)); - assertThat(context.getBeansOfType(TraceRepository.class).size(), equalTo(1)); + assertThat(context.getBeansOfType(InMemoryTraceRepository.class)).isEmpty(); + assertThat(context.getBeansOfType(TraceRepository.class)).hasSize(1); context.close(); } diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/TraceWebFilterAutoConfigurationTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/TraceWebFilterAutoConfigurationTests.java index 9f6e0196f8..8352919763 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/TraceWebFilterAutoConfigurationTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/TraceWebFilterAutoConfigurationTests.java @@ -22,7 +22,7 @@ import org.springframework.boot.actuate.trace.WebRequestTraceFilter; import org.springframework.boot.autoconfigure.PropertyPlaceholderAutoConfiguration; import org.springframework.context.annotation.AnnotationConfigApplicationContext; -import static org.junit.Assert.assertNotNull; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link TraceWebFilterAutoConfiguration}. @@ -37,7 +37,7 @@ public class TraceWebFilterAutoConfigurationTests { PropertyPlaceholderAutoConfiguration.class, TraceRepositoryAutoConfiguration.class, TraceWebFilterAutoConfiguration.class); - assertNotNull(context.getBean(WebRequestTraceFilter.class)); + assertThat(context.getBean(WebRequestTraceFilter.class)).isNotNull(); context.close(); } diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/AbstractEndpointTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/AbstractEndpointTests.java index b65ac25bfd..f587f7ea55 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/AbstractEndpointTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/AbstractEndpointTests.java @@ -31,8 +31,7 @@ import org.springframework.context.annotation.AnnotationConfigApplicationContext import org.springframework.core.env.MapPropertySource; import org.springframework.core.env.PropertySource; -import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; /** * Abstract base class for endpoint tests. @@ -79,12 +78,12 @@ public abstract class AbstractEndpointTests> { @Test public void getId() throws Exception { - assertThat(getEndpointBean().getId(), equalTo(this.id)); + assertThat(getEndpointBean().getId()).isEqualTo(this.id); } @Test public void isSensitive() throws Exception { - assertThat(getEndpointBean().isSensitive(), equalTo(this.sensitive)); + assertThat(getEndpointBean().isSensitive()).isEqualTo(this.sensitive); } @Test @@ -93,7 +92,7 @@ public abstract class AbstractEndpointTests> { EnvironmentTestUtils.addEnvironment(this.context, this.property + ".id:myid"); this.context.register(this.configClass); this.context.refresh(); - assertThat(getEndpointBean().getId(), equalTo("myid")); + assertThat(getEndpointBean().getId()).isEqualTo("myid"); } @Test @@ -105,7 +104,7 @@ public abstract class AbstractEndpointTests> { this.context.getEnvironment().getPropertySources().addFirst(propertySource); this.context.register(this.configClass); this.context.refresh(); - assertThat(getEndpointBean().isSensitive(), equalTo(!this.sensitive)); + assertThat(getEndpointBean().isSensitive()).isEqualTo(!this.sensitive); } @Test @@ -118,12 +117,12 @@ public abstract class AbstractEndpointTests> { this.context.getEnvironment().getPropertySources().addFirst(propertySource); this.context.register(this.configClass); this.context.refresh(); - assertThat(getEndpointBean().isSensitive(), equalTo(!this.sensitive)); + assertThat(getEndpointBean().isSensitive()).isEqualTo(!this.sensitive); } @Test public void isEnabledByDefault() throws Exception { - assertThat(getEndpointBean().isEnabled(), equalTo(true)); + assertThat(getEndpointBean().isEnabled()).isTrue(); } @Test @@ -134,7 +133,7 @@ public abstract class AbstractEndpointTests> { this.context.getEnvironment().getPropertySources().addFirst(propertySource); this.context.register(this.configClass); this.context.refresh(); - assertThat(getEndpointBean().isEnabled(), equalTo(false)); + assertThat(getEndpointBean().isEnabled()).isFalse(); } @Test @@ -147,7 +146,7 @@ public abstract class AbstractEndpointTests> { this.context.register(this.configClass); this.context.refresh(); ((AbstractEndpoint) getEndpointBean()).setEnabled(true); - assertThat(getEndpointBean().isEnabled(), equalTo(true)); + assertThat(getEndpointBean().isEnabled()).isTrue(); } @Test @@ -158,7 +157,7 @@ public abstract class AbstractEndpointTests> { this.context.getEnvironment().getPropertySources().addFirst(propertySource); this.context.register(this.configClass); this.context.refresh(); - assertThat(getEndpointBean().isEnabled(), equalTo(false)); + assertThat(getEndpointBean().isEnabled()).isFalse(); } @Test @@ -171,7 +170,7 @@ public abstract class AbstractEndpointTests> { this.context.getEnvironment().getPropertySources().addFirst(propertySource); this.context.register(this.configClass); this.context.refresh(); - assertThat(getEndpointBean().isEnabled(), equalTo(true)); + assertThat(getEndpointBean().isEnabled()).isTrue(); } @Test @@ -199,7 +198,7 @@ public abstract class AbstractEndpointTests> { this.context.getEnvironment().getPropertySources().addFirst(propertySource); this.context.register(this.configClass); this.context.refresh(); - assertThat(getEndpointBean().isSensitive(), equalTo(sensitive)); + assertThat(getEndpointBean().isSensitive()).isEqualTo(sensitive); } @SuppressWarnings("unchecked") diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/AutoConfigurationReportEndpointTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/AutoConfigurationReportEndpointTests.java index c9c6bda7f1..42511f1dea 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/AutoConfigurationReportEndpointTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/AutoConfigurationReportEndpointTests.java @@ -33,7 +33,7 @@ import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Condition; import org.springframework.context.annotation.Configuration; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; /** @@ -57,9 +57,9 @@ public class AutoConfigurationReportEndpointTests this.context.register(this.configClass); this.context.refresh(); Report report = getEndpointBean().invoke(); - assertTrue(report.getPositiveMatches().isEmpty()); - assertTrue(report.getNegativeMatches().containsKey("a")); - assertTrue(report.getExclusions().contains("com.foo.Bar")); + assertThat(report.getPositiveMatches()).isEmpty(); + assertThat(report.getNegativeMatches()).containsKey("a"); + assertThat(report.getExclusions()).contains("com.foo.Bar"); } @Configuration diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/BeansEndpointTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/BeansEndpointTests.java index 9f13c4f63c..37bed9056f 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/BeansEndpointTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/BeansEndpointTests.java @@ -25,8 +25,7 @@ import org.springframework.boot.context.properties.EnableConfigurationProperties import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link BeansEndpoint}. @@ -42,8 +41,8 @@ public class BeansEndpointTests extends AbstractEndpointTests { @Test public void invoke() throws Exception { List result = getEndpointBean().invoke(); - assertEquals(1, result.size()); - assertTrue(result.get(0) instanceof Map); + assertThat(result).hasSize(1); + assertThat(result.get(0)).isInstanceOf(Map.class); } @Configuration @@ -56,4 +55,5 @@ public class BeansEndpointTests extends AbstractEndpointTests { } } + } diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/ConfigurationPropertiesReportEndpointMethodAnnotationsTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/ConfigurationPropertiesReportEndpointMethodAnnotationsTests.java index 9d56e8e4da..31557c84c2 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/ConfigurationPropertiesReportEndpointMethodAnnotationsTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/ConfigurationPropertiesReportEndpointMethodAnnotationsTests.java @@ -29,8 +29,7 @@ import org.springframework.context.annotation.AnnotationConfigApplicationContext import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link ConfigurationPropertiesReportEndpoint} when used with bean methods. @@ -65,9 +64,9 @@ public class ConfigurationPropertiesReportEndpointMethodAnnotationsTests { Map properties = report.invoke(); Map nestedProperties = (Map) properties .get("other"); - assertNotNull(nestedProperties); - assertEquals("other", nestedProperties.get("prefix")); - assertNotNull(nestedProperties.get("properties")); + assertThat(nestedProperties).isNotNull(); + assertThat(nestedProperties.get("prefix")).isEqualTo("other"); + assertThat(nestedProperties.get("properties")).isNotNull(); } @Test @@ -81,9 +80,9 @@ public class ConfigurationPropertiesReportEndpointMethodAnnotationsTests { Map properties = report.invoke(); Map nestedProperties = (Map) properties .get("bar"); - assertNotNull(nestedProperties); - assertEquals("other", nestedProperties.get("prefix")); - assertNotNull(nestedProperties.get("properties")); + assertThat(nestedProperties).isNotNull(); + assertThat(nestedProperties.get("prefix")).isEqualTo("other"); + assertThat(nestedProperties.get("properties")).isNotNull(); } @Configuration diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/ConfigurationPropertiesReportEndpointParentTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/ConfigurationPropertiesReportEndpointParentTests.java index 0ae3cdbe28..241bec9e9d 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/ConfigurationPropertiesReportEndpointParentTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/ConfigurationPropertiesReportEndpointParentTests.java @@ -28,8 +28,7 @@ import org.springframework.context.annotation.AnnotationConfigApplicationContext import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link ConfigurationPropertiesReportEndpoint} when used with a parent @@ -63,8 +62,8 @@ public class ConfigurationPropertiesReportEndpointParentTests { ConfigurationPropertiesReportEndpoint endpoint = this.context .getBean(ConfigurationPropertiesReportEndpoint.class); Map result = endpoint.invoke(); - assertTrue(result.containsKey("parent")); - assertEquals(3, result.size()); // the endpoint, the test props and the parent + assertThat(result).containsKey("parent"); + assertThat(result).hasSize(3); // the endpoint, the test props and the parent // System.err.println(result); } @@ -80,8 +79,8 @@ public class ConfigurationPropertiesReportEndpointParentTests { ConfigurationPropertiesReportEndpoint endpoint = this.context .getBean(ConfigurationPropertiesReportEndpoint.class); Map result = endpoint.invoke(); - assertTrue(result.containsKey("parent")); - assertEquals(3, result.size()); // the endpoint, the test props and the parent + assertThat(result.containsKey("parent")).isTrue(); + assertThat(result).hasSize(3); // the endpoint, the test props and the parent // System.err.println(result); } diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/ConfigurationPropertiesReportEndpointProxyTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/ConfigurationPropertiesReportEndpointProxyTests.java index 636cdcad2f..222002b31c 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/ConfigurationPropertiesReportEndpointProxyTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/ConfigurationPropertiesReportEndpointProxyTests.java @@ -38,8 +38,7 @@ import org.springframework.transaction.annotation.EnableTransactionManagement; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; -import static org.hamcrest.Matchers.containsString; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link ConfigurationPropertiesReportEndpoint} when used against a proxy @@ -69,7 +68,7 @@ public class ConfigurationPropertiesReportEndpointProxyTests { this.context.refresh(); Map report = this.context .getBean(ConfigurationPropertiesReportEndpoint.class).invoke(); - assertThat(report.toString(), containsString("prefix=executor.sql")); + assertThat(report.toString()).contains("prefix=executor.sql"); } @Configuration diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/ConfigurationPropertiesReportEndpointSerializationTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/ConfigurationPropertiesReportEndpointSerializationTests.java index 015bc27f2f..41bf5a0149 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/ConfigurationPropertiesReportEndpointSerializationTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/ConfigurationPropertiesReportEndpointSerializationTests.java @@ -32,8 +32,7 @@ import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link ConfigurationPropertiesReportEndpoint} serialization. @@ -67,13 +66,13 @@ public class ConfigurationPropertiesReportEndpointSerializationTests { Map properties = report.invoke(); Map nestedProperties = (Map) properties .get("foo"); - assertNotNull(nestedProperties); - assertEquals("foo", nestedProperties.get("prefix")); + assertThat(nestedProperties).isNotNull(); + assertThat(nestedProperties.get("prefix")).isEqualTo("foo"); Map map = (Map) nestedProperties .get("properties"); - assertNotNull(map); - assertEquals(2, map.size()); - assertEquals("foo", map.get("name")); + assertThat(map).isNotNull(); + assertThat(map).hasSize(2); + assertThat(map.get("name")).isEqualTo("foo"); } @Test @@ -87,12 +86,12 @@ public class ConfigurationPropertiesReportEndpointSerializationTests { Map properties = report.invoke(); Map nestedProperties = (Map) properties .get("foo"); - assertNotNull(nestedProperties); + assertThat(nestedProperties).isNotNull(); Map map = (Map) nestedProperties .get("properties"); - assertNotNull(map); - assertEquals(2, map.size()); - assertEquals("foo", ((Map) map.get("bar")).get("name")); + assertThat(map).isNotNull(); + assertThat(map).hasSize(2); + assertThat(((Map) map.get("bar")).get("name")).isEqualTo("foo"); } @Test @@ -106,13 +105,13 @@ public class ConfigurationPropertiesReportEndpointSerializationTests { Map properties = report.invoke(); Map nestedProperties = (Map) properties .get("foo"); - assertNotNull(nestedProperties); - assertEquals("foo", nestedProperties.get("prefix")); + assertThat(nestedProperties).isNotNull(); + assertThat(nestedProperties.get("prefix")).isEqualTo("foo"); Map map = (Map) nestedProperties .get("properties"); - assertNotNull(map); - assertEquals(1, map.size()); - assertEquals("Cannot serialize 'foo'", map.get("error")); + assertThat(map).isNotNull(); + assertThat(map).hasSize(1); + assertThat(map.get("error")).isEqualTo("Cannot serialize 'foo'"); } @Test @@ -126,13 +125,13 @@ public class ConfigurationPropertiesReportEndpointSerializationTests { Map properties = report.invoke(); Map nestedProperties = (Map) properties .get("foo"); - assertNotNull(nestedProperties); - assertEquals("foo", nestedProperties.get("prefix")); + assertThat(nestedProperties).isNotNull(); + assertThat(nestedProperties.get("prefix")).isEqualTo("foo"); Map map = (Map) nestedProperties .get("properties"); - assertNotNull(map); - assertEquals(3, map.size()); - assertEquals("foo", ((Map) map.get("map")).get("name")); + assertThat(map).isNotNull(); + assertThat(map).hasSize(3); + assertThat(((Map) map.get("map")).get("name")).isEqualTo("foo"); } @Test @@ -145,14 +144,14 @@ public class ConfigurationPropertiesReportEndpointSerializationTests { Map properties = report.invoke(); Map nestedProperties = (Map) properties .get("foo"); - assertNotNull(nestedProperties); + assertThat(nestedProperties).isNotNull(); System.err.println(nestedProperties); - assertEquals("foo", nestedProperties.get("prefix")); + assertThat(nestedProperties.get("prefix")).isEqualTo("foo"); Map map = (Map) nestedProperties .get("properties"); - assertNotNull(map); - assertEquals(3, map.size()); - assertEquals(null, (map.get("map"))); + assertThat(map).isNotNull(); + assertThat(map).hasSize(3); + assertThat((map.get("map"))).isNull(); } @Test @@ -166,13 +165,13 @@ public class ConfigurationPropertiesReportEndpointSerializationTests { Map properties = report.invoke(); Map nestedProperties = (Map) properties .get("foo"); - assertNotNull(nestedProperties); - assertEquals("foo", nestedProperties.get("prefix")); + assertThat(nestedProperties).isNotNull(); + assertThat(nestedProperties.get("prefix")).isEqualTo("foo"); Map map = (Map) nestedProperties .get("properties"); - assertNotNull(map); - assertEquals(3, map.size()); - assertEquals("foo", ((List) map.get("list")).get(0)); + assertThat(map).isNotNull(); + assertThat(map).hasSize(3); + assertThat(((List) map.get("list")).get(0)).isEqualTo("foo"); } @Test @@ -186,14 +185,14 @@ public class ConfigurationPropertiesReportEndpointSerializationTests { Map properties = report.invoke(); Map nestedProperties = (Map) properties .get("foo"); - assertNotNull(nestedProperties); + assertThat(nestedProperties).isNotNull(); System.err.println(nestedProperties); - assertEquals("foo", nestedProperties.get("prefix")); + assertThat(nestedProperties.get("prefix")).isEqualTo("foo"); Map map = (Map) nestedProperties .get("properties"); - assertNotNull(map); - assertEquals(3, map.size()); - assertEquals("192.168.1.10", map.get("address")); + assertThat(map).isNotNull(); + assertThat(map).hasSize(3); + assertThat(map.get("address")).isEqualTo("192.168.1.10"); } @Configuration diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/ConfigurationPropertiesReportEndpointTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/ConfigurationPropertiesReportEndpointTests.java index 350e8e5c71..0c41f2348b 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/ConfigurationPropertiesReportEndpointTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/ConfigurationPropertiesReportEndpointTests.java @@ -28,11 +28,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.hamcrest.Matchers.greaterThan; -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 ConfigurationPropertiesReportEndpoint}. @@ -49,7 +45,7 @@ public class ConfigurationPropertiesReportEndpointTests @Test public void testInvoke() throws Exception { - assertThat(getEndpointBean().invoke().size(), greaterThan(0)); + assertThat(getEndpointBean().invoke().size()).isGreaterThan(0); } @Test @@ -59,9 +55,9 @@ public class ConfigurationPropertiesReportEndpointTests Map properties = report.invoke(); Map nestedProperties = (Map) properties .get("testProperties"); - assertNotNull(nestedProperties); - assertEquals("test", nestedProperties.get("prefix")); - assertNotNull(nestedProperties.get("properties")); + assertThat(nestedProperties).isNotNull(); + assertThat(nestedProperties.get("prefix")).isEqualTo("test"); + assertThat(nestedProperties.get("properties")).isNotNull(); } @Test @@ -71,9 +67,9 @@ public class ConfigurationPropertiesReportEndpointTests Map properties = report.invoke(); Map nestedProperties = (Map) ((Map) properties .get("testProperties")).get("properties"); - assertNotNull(nestedProperties); - assertEquals("******", nestedProperties.get("dbPassword")); - assertEquals("654321", nestedProperties.get("myTestProperty")); + assertThat(nestedProperties).isNotNull(); + assertThat(nestedProperties.get("dbPassword")).isEqualTo("******"); + assertThat(nestedProperties.get("myTestProperty")).isEqualTo("654321"); } @Test @@ -84,9 +80,9 @@ public class ConfigurationPropertiesReportEndpointTests Map properties = report.invoke(); Map nestedProperties = (Map) ((Map) properties .get("testProperties")).get("properties"); - assertNotNull(nestedProperties); - assertEquals("123456", nestedProperties.get("dbPassword")); - assertEquals("******", nestedProperties.get("myTestProperty")); + assertThat(nestedProperties).isNotNull(); + assertThat(nestedProperties.get("dbPassword")).isEqualTo("123456"); + assertThat(nestedProperties.get("myTestProperty")).isEqualTo("******"); } @SuppressWarnings("unchecked") @@ -97,9 +93,9 @@ public class ConfigurationPropertiesReportEndpointTests Map properties = report.invoke(); Map nestedProperties = (Map) ((Map) properties .get("testProperties")).get("properties"); - assertNotNull(nestedProperties); - assertEquals("******", nestedProperties.get("dbPassword")); - assertEquals("654321", nestedProperties.get("myTestProperty")); + assertThat(nestedProperties).isNotNull(); + assertThat(nestedProperties.get("dbPassword")).isEqualTo("******"); + assertThat(nestedProperties.get("myTestProperty")).isEqualTo("654321"); } @SuppressWarnings("unchecked") @@ -114,9 +110,9 @@ public class ConfigurationPropertiesReportEndpointTests Map properties = report.invoke(); Map nestedProperties = (Map) ((Map) properties .get("testProperties")).get("properties"); - assertNotNull(nestedProperties); - assertEquals("123456", nestedProperties.get("dbPassword")); - assertEquals("******", nestedProperties.get("myTestProperty")); + assertThat(nestedProperties).isNotNull(); + assertThat(nestedProperties.get("dbPassword")).isEqualTo("123456"); + assertThat(nestedProperties.get("myTestProperty")).isEqualTo("******"); } @SuppressWarnings("unchecked") @@ -131,9 +127,9 @@ public class ConfigurationPropertiesReportEndpointTests Map properties = report.invoke(); Map nestedProperties = (Map) ((Map) properties .get("testProperties")).get("properties"); - assertNotNull(nestedProperties); - assertEquals("******", nestedProperties.get("dbPassword")); - assertEquals("654321", nestedProperties.get("myTestProperty")); + assertThat(nestedProperties).isNotNull(); + assertThat(nestedProperties.get("dbPassword")).isEqualTo("******"); + assertThat(nestedProperties.get("myTestProperty")).isEqualTo("654321"); } @Test @@ -149,9 +145,9 @@ public class ConfigurationPropertiesReportEndpointTests Map properties = report.invoke(); Map nestedProperties = (Map) ((Map) properties .get("testProperties")).get("properties"); - assertNotNull(nestedProperties); - assertEquals("******", nestedProperties.get("dbPassword")); - assertEquals("******", nestedProperties.get("myTestProperty")); + assertThat(nestedProperties).isNotNull(); + assertThat(nestedProperties.get("dbPassword")).isEqualTo("******"); + assertThat(nestedProperties.get("myTestProperty")).isEqualTo("******"); } @Test @@ -168,13 +164,13 @@ public class ConfigurationPropertiesReportEndpointTests Map properties = report.invoke(); Map nestedProperties = (Map) ((Map) properties .get("testProperties")).get("properties"); - assertNotNull(nestedProperties); + assertThat(nestedProperties).isNotNull(); Map secrets = (Map) nestedProperties .get("secrets"); Map hidden = (Map) nestedProperties.get("hidden"); - assertEquals("******", secrets.get("mine")); - assertEquals("******", secrets.get("yours")); - assertEquals("******", hidden.get("mine")); + assertThat(secrets.get("mine")).isEqualTo("******"); + assertThat(secrets.get("yours")).isEqualTo("******"); + assertThat(hidden.get("mine")).isEqualTo("******"); } @Test @@ -184,7 +180,7 @@ public class ConfigurationPropertiesReportEndpointTests Map properties = report.invoke(); Map nestedProperties = (Map) ((Map) properties .get("testProperties")).get("properties"); - assertThat(nestedProperties.get("mixedBoolean"), equalTo((Object) true)); + assertThat(nestedProperties.get("mixedBoolean")).isEqualTo(true); } @Configuration diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/DumpEndpointTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/DumpEndpointTests.java index 2aecbb8c64..4815885c51 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/DumpEndpointTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/DumpEndpointTests.java @@ -25,8 +25,7 @@ import org.springframework.boot.context.properties.EnableConfigurationProperties import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; -import static org.hamcrest.Matchers.greaterThan; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link DumpEndpoint}. @@ -42,7 +41,7 @@ public class DumpEndpointTests extends AbstractEndpointTests { @Test public void invoke() throws Exception { List threadInfo = getEndpointBean().invoke(); - assertThat(threadInfo.size(), greaterThan(0)); + assertThat(threadInfo.size()).isGreaterThan(0); } @Configuration diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/EnvironmentEndpointTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/EnvironmentEndpointTests.java index bdc79501e6..0f3536f1c8 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/EnvironmentEndpointTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/EnvironmentEndpointTests.java @@ -29,9 +29,7 @@ import org.springframework.context.annotation.Configuration; import org.springframework.core.env.CompositePropertySource; import org.springframework.core.env.MapPropertySource; -import static org.hamcrest.Matchers.greaterThan; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link EnvironmentEndpoint}. @@ -49,7 +47,7 @@ public class EnvironmentEndpointTests extends AbstractEndpointTests env = report.invoke(); - assertEquals("bar", ((Map) env.get("composite:one")).get("foo")); + assertThat(((Map) env.get("composite:one")).get("foo")) + .isEqualTo("bar"); } @SuppressWarnings("unchecked") @@ -76,16 +75,13 @@ public class EnvironmentEndpointTests extends AbstractEndpointTests env = report.invoke(); - assertEquals("******", - ((Map) env.get("systemProperties")).get("dbPassword")); - assertEquals("******", - ((Map) env.get("systemProperties")).get("apiKey")); - assertEquals("******", - ((Map) env.get("systemProperties")).get("mySecret")); - assertEquals("******", - ((Map) env.get("systemProperties")).get("myCredentials")); - assertEquals("******", - ((Map) env.get("systemProperties")).get("VCAP_SERVICES")); + Map systemProperties = (Map) env + .get("systemProperties"); + assertThat(systemProperties.get("dbPassword")).isEqualTo("******"); + assertThat(systemProperties.get("apiKey")).isEqualTo("******"); + assertThat(systemProperties.get("mySecret")).isEqualTo("******"); + assertThat(systemProperties.get("myCredentials")).isEqualTo("******"); + assertThat(systemProperties.get("VCAP_SERVICES")).isEqualTo("******"); } @SuppressWarnings("unchecked") @@ -97,14 +93,14 @@ public class EnvironmentEndpointTests extends AbstractEndpointTests env = report.invoke(); - assertEquals("******", ((Map) env.get("systemProperties")) - .get("my.services.amqp-free.credentials.uri")); - assertEquals("******", ((Map) env.get("systemProperties")) - .get("credentials.http_api_uri")); - assertEquals("******", ((Map) env.get("systemProperties")) - .get("my.services.cleardb-free.credentials")); - assertEquals("******", ((Map) env.get("systemProperties")) - .get("foo.mycredentials.uri")); + Map systemProperties = (Map) env + .get("systemProperties"); + assertThat(systemProperties.get("my.services.amqp-free.credentials.uri")) + .isEqualTo("******"); + assertThat(systemProperties.get("credentials.http_api_uri")).isEqualTo("******"); + assertThat(systemProperties.get("my.services.cleardb-free.credentials")) + .isEqualTo("******"); + assertThat(systemProperties.get("foo.mycredentials.uri")).isEqualTo("******"); } @@ -116,10 +112,10 @@ public class EnvironmentEndpointTests extends AbstractEndpointTests env = report.invoke(); - assertEquals("123456", - ((Map) env.get("systemProperties")).get("dbPassword")); - assertEquals("******", - ((Map) env.get("systemProperties")).get("apiKey")); + Map systemProperties = (Map) env + .get("systemProperties"); + assertThat(systemProperties.get("dbPassword")).isEqualTo("123456"); + assertThat(systemProperties.get("apiKey")).isEqualTo("******"); } @SuppressWarnings("unchecked") @@ -130,10 +126,10 @@ public class EnvironmentEndpointTests extends AbstractEndpointTests env = report.invoke(); - assertEquals("******", - ((Map) env.get("systemProperties")).get("dbPassword")); - assertEquals("123456", - ((Map) env.get("systemProperties")).get("apiKey")); + Map systemProperties = (Map) env + .get("systemProperties"); + assertThat(systemProperties.get("dbPassword")).isEqualTo("******"); + assertThat(systemProperties.get("apiKey")).isEqualTo("123456"); } @SuppressWarnings("unchecked") @@ -148,10 +144,10 @@ public class EnvironmentEndpointTests extends AbstractEndpointTests env = report.invoke(); - assertEquals("123456", - ((Map) env.get("systemProperties")).get("dbPassword")); - assertEquals("******", - ((Map) env.get("systemProperties")).get("apiKey")); + Map systemProperties = (Map) env + .get("systemProperties"); + assertThat(systemProperties.get("dbPassword")).isEqualTo("123456"); + assertThat(systemProperties.get("apiKey")).isEqualTo("******"); } @SuppressWarnings("unchecked") @@ -166,10 +162,10 @@ public class EnvironmentEndpointTests extends AbstractEndpointTests env = report.invoke(); - assertEquals("******", - ((Map) env.get("systemProperties")).get("dbPassword")); - assertEquals("123456", - ((Map) env.get("systemProperties")).get("apiKey")); + Map systemProperties = (Map) env + .get("systemProperties"); + assertThat(systemProperties.get("dbPassword")).isEqualTo("******"); + assertThat(systemProperties.get("apiKey")).isEqualTo("123456"); } @SuppressWarnings("unchecked") @@ -185,10 +181,10 @@ public class EnvironmentEndpointTests extends AbstractEndpointTests env = report.invoke(); - assertEquals("******", - ((Map) env.get("systemProperties")).get("dbPassword")); - assertEquals("******", - ((Map) env.get("systemProperties")).get("apiKey")); + Map systemProperties = (Map) env + .get("systemProperties"); + assertThat(systemProperties.get("dbPassword")).isEqualTo("******"); + assertThat(systemProperties.get("apiKey")).isEqualTo("******"); } @Configuration diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/FlywayEndpointTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/FlywayEndpointTests.java index 48f468a25a..c10579ce91 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/FlywayEndpointTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/FlywayEndpointTests.java @@ -26,8 +26,7 @@ import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; -import static org.hamcrest.Matchers.is; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link FlywayEndpoint}. @@ -42,7 +41,7 @@ public class FlywayEndpointTests extends AbstractEndpointTests { @Test public void invoke() throws Exception { - assertThat(getEndpointBean().invoke().size(), is(1)); + assertThat(getEndpointBean().invoke()).hasSize(1); } @Configuration diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/HealthEndpointTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/HealthEndpointTests.java index 3087538780..21b4537393 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/HealthEndpointTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/HealthEndpointTests.java @@ -29,8 +29,7 @@ import org.springframework.boot.context.properties.EnableConfigurationProperties 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.assertj.core.api.Assertions.assertThat; /** * Tests for {@link HealthEndpoint}. @@ -47,7 +46,7 @@ public class HealthEndpointTests extends AbstractEndpointTests { @Test public void invoke() throws Exception { // As FINE isn't configured in the order we get UNKNOWN - assertThat(getEndpointBean().invoke().getStatus(), equalTo(Status.UNKNOWN)); + assertThat(getEndpointBean().invoke().getStatus()).isEqualTo(Status.UNKNOWN); } @Configuration diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/InfoEndpointTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/InfoEndpointTests.java index 7c99a739a7..3cb1abdbcb 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/InfoEndpointTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/InfoEndpointTests.java @@ -24,8 +24,7 @@ import org.springframework.boot.context.properties.EnableConfigurationProperties 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.assertj.core.api.Assertions.assertThat; /** * Tests for {@link InfoEndpoint}. @@ -41,7 +40,7 @@ public class InfoEndpointTests extends AbstractEndpointTests { @Test public void invoke() throws Exception { - assertThat(getEndpointBean().invoke().get("a"), equalTo((Object) "b")); + assertThat(getEndpointBean().invoke().get("a")).isEqualTo("b"); } @Configuration diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/LiquibaseEndpointTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/LiquibaseEndpointTests.java index 9b63b602dc..c5fde156f6 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/LiquibaseEndpointTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/LiquibaseEndpointTests.java @@ -26,8 +26,7 @@ import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; -import static org.hamcrest.Matchers.is; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link LiquibaseEndpoint}. @@ -43,7 +42,7 @@ public class LiquibaseEndpointTests extends AbstractEndpointTests @Test public void invoke() throws Exception { - assertThat(getEndpointBean().invoke().get("a"), equalTo((Object) 0.5f)); + assertThat(getEndpointBean().invoke().get("a")).isEqualTo(0.5f); } @Test @@ -68,10 +65,10 @@ public class MetricsEndpointTests extends AbstractEndpointTests publicMetrics.add(new TestPublicMetrics(1, this.metric1)); Map metrics = new MetricsEndpoint(publicMetrics).invoke(); Iterator> iterator = metrics.entrySet().iterator(); - assertEquals("a", iterator.next().getKey()); - assertEquals("b", iterator.next().getKey()); - assertEquals("c", iterator.next().getKey()); - assertFalse(iterator.hasNext()); + assertThat(iterator.next().getKey()).isEqualTo("a"); + assertThat(iterator.next().getKey()).isEqualTo("b"); + assertThat(iterator.next().getKey()).isEqualTo("c"); + assertThat(iterator.hasNext()).isFalse(); } private static class TestPublicMetrics implements PublicMetrics, Ordered { diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/RequestMappingEndpointTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/RequestMappingEndpointTests.java index 6d81434254..667989b67e 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/RequestMappingEndpointTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/RequestMappingEndpointTests.java @@ -35,8 +35,7 @@ import org.springframework.web.servlet.handler.AbstractHandlerMethodMapping; import org.springframework.web.servlet.handler.AbstractUrlHandlerMapping; import org.springframework.web.servlet.handler.SimpleUrlHandlerMapping; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link RequestMappingEndpoint}. @@ -56,10 +55,10 @@ public class RequestMappingEndpointTests { this.endpoint.setHandlerMappings( Collections.singletonList(mapping)); Map result = this.endpoint.invoke(); - assertEquals(1, result.size()); + assertThat(result).hasSize(1); @SuppressWarnings("unchecked") Map map = (Map) result.get("/foo"); - assertEquals("java.lang.Object", map.get("type")); + assertThat(map.get("type")).isEqualTo("java.lang.Object"); } @Test @@ -72,10 +71,10 @@ public class RequestMappingEndpointTests { context.getDefaultListableBeanFactory().registerSingleton("mapping", mapping); this.endpoint.setApplicationContext(context); Map result = this.endpoint.invoke(); - assertEquals(1, result.size()); + assertThat(result).hasSize(1); @SuppressWarnings("unchecked") Map map = (Map) result.get("/foo"); - assertEquals("mapping", map.get("bean")); + assertThat(map.get("bean")).isEqualTo("mapping"); } @Test @@ -84,10 +83,10 @@ public class RequestMappingEndpointTests { MappingConfiguration.class); this.endpoint.setApplicationContext(context); Map result = this.endpoint.invoke(); - assertEquals(1, result.size()); + assertThat(result).hasSize(1); @SuppressWarnings("unchecked") Map map = (Map) result.get("/foo"); - assertEquals("scopedTarget.mapping", map.get("bean")); + assertThat(map.get("bean")).isEqualTo("scopedTarget.mapping"); } @Test @@ -100,12 +99,12 @@ public class RequestMappingEndpointTests { context.getDefaultListableBeanFactory().registerSingleton("mapping", mapping); this.endpoint.setApplicationContext(context); Map result = this.endpoint.invoke(); - assertEquals(1, result.size()); - assertTrue(result.keySet().iterator().next().contains("/dump")); + assertThat(result).hasSize(1); + assertThat(result.keySet().iterator().next().contains("/dump")).isTrue(); @SuppressWarnings("unchecked") Map handler = (Map) result.values().iterator() .next(); - assertTrue(handler.containsKey("method")); + assertThat(handler.containsKey("method")).isTrue(); } @Test @@ -117,12 +116,12 @@ public class RequestMappingEndpointTests { this.endpoint.setMethodMappings( Collections.>singletonList(mapping)); Map result = this.endpoint.invoke(); - assertEquals(1, result.size()); - assertTrue(result.keySet().iterator().next().contains("/dump")); + assertThat(result).hasSize(1); + assertThat(result.keySet().iterator().next().contains("/dump")).isTrue(); @SuppressWarnings("unchecked") Map handler = (Map) result.values().iterator() .next(); - assertTrue(handler.containsKey("method")); + assertThat(handler.containsKey("method")).isTrue(); } @Configuration diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/RichGaugeReaderPublicMetricsTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/RichGaugeReaderPublicMetricsTests.java index 5e9ca0fd34..492ebeef95 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/RichGaugeReaderPublicMetricsTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/RichGaugeReaderPublicMetricsTests.java @@ -25,9 +25,7 @@ import org.junit.Test; import org.springframework.boot.actuate.metrics.Metric; import org.springframework.boot.actuate.metrics.rich.InMemoryRichGaugeRepository; -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 RichGaugeReaderPublicMetrics}. @@ -50,23 +48,23 @@ public class RichGaugeReaderPublicMetricsTests { for (Metric metric : metrics.metrics()) { results.put(metric.getName(), metric); } - assertTrue(results.containsKey("a.val")); - assertThat(results.get("a.val").getValue().doubleValue(), equalTo(0.5d)); + assertThat(results.containsKey("a.val")).isTrue(); + assertThat(results.get("a.val").getValue().doubleValue()).isEqualTo(0.5d); - assertTrue(results.containsKey("a.avg")); - assertThat(results.get("a.avg").getValue().doubleValue(), equalTo(0.25d)); + assertThat(results.containsKey("a.avg")).isTrue(); + assertThat(results.get("a.avg").getValue().doubleValue()).isEqualTo(0.25d); - assertTrue(results.containsKey("a.min")); - assertThat(results.get("a.min").getValue().doubleValue(), equalTo(0.0d)); + assertThat(results.containsKey("a.min")).isTrue(); + assertThat(results.get("a.min").getValue().doubleValue()).isEqualTo(0.0d); - assertTrue(results.containsKey("a.max")); - assertThat(results.get("a.max").getValue().doubleValue(), equalTo(0.5d)); + assertThat(results.containsKey("a.max")).isTrue(); + assertThat(results.get("a.max").getValue().doubleValue()).isEqualTo(0.5d); - assertTrue(results.containsKey("a.count")); - assertThat(results.get("a.count").getValue().longValue(), equalTo(2L)); + assertThat(results.containsKey("a.count")).isTrue(); + assertThat(results.get("a.count").getValue().longValue()).isEqualTo(2L); - assertTrue(results.containsKey("a.alpha")); - assertThat(results.get("a.alpha").getValue().doubleValue(), equalTo(-1.d)); + assertThat(results.containsKey("a.alpha")).isTrue(); + assertThat(results.get("a.alpha").getValue().doubleValue()).isEqualTo(-1.d); } } diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/SanitizerTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/SanitizerTests.java index ffca349b5e..1efbc3d48c 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/SanitizerTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/SanitizerTests.java @@ -18,7 +18,7 @@ package org.springframework.boot.actuate.endpoint; import org.junit.Test; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link Sanitizer}. @@ -27,23 +27,22 @@ import static org.junit.Assert.assertEquals; */ public class SanitizerTests { - private Sanitizer sanitizer = new Sanitizer(); - @Test public void defaults() throws Exception { - assertEquals(this.sanitizer.sanitize("password", "secret"), "******"); - assertEquals(this.sanitizer.sanitize("my-password", "secret"), "******"); - assertEquals(this.sanitizer.sanitize("my-OTHER.paSSword", "secret"), "******"); - assertEquals(this.sanitizer.sanitize("somesecret", "secret"), "******"); - assertEquals(this.sanitizer.sanitize("somekey", "secret"), "******"); - assertEquals(this.sanitizer.sanitize("find", "secret"), "secret"); + Sanitizer sanitizer = new Sanitizer(); + assertThat(sanitizer.sanitize("password", "secret")).isEqualTo("******"); + assertThat(sanitizer.sanitize("my-password", "secret")).isEqualTo("******"); + assertThat(sanitizer.sanitize("my-OTHER.paSSword", "secret")).isEqualTo("******"); + assertThat(sanitizer.sanitize("somesecret", "secret")).isEqualTo("******"); + assertThat(sanitizer.sanitize("somekey", "secret")).isEqualTo("******"); + assertThat(sanitizer.sanitize("find", "secret")).isEqualTo("secret"); } @Test public void regex() throws Exception { - this.sanitizer.setKeysToSanitize(".*lock.*"); - assertEquals(this.sanitizer.sanitize("verylOCkish", "secret"), "******"); - assertEquals(this.sanitizer.sanitize("veryokish", "secret"), "secret"); + Sanitizer sanitizer = new Sanitizer(".*lock.*"); + assertThat(sanitizer.sanitize("verylOCkish", "secret")).isEqualTo("******"); + assertThat(sanitizer.sanitize("veryokish", "secret")).isEqualTo("secret"); } } diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/ShutdownEndpointTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/ShutdownEndpointTests.java index a4de92086c..4b6fff5b8b 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/ShutdownEndpointTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/ShutdownEndpointTests.java @@ -27,10 +27,7 @@ import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.event.ContextClosedEvent; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.startsWith; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link ShutdownEndpoint}. @@ -48,16 +45,16 @@ public class ShutdownEndpointTests extends AbstractEndpointTests metric : publicMetrics.metrics()) { results.put(metric.getName(), metric); } - assertTrue(results.containsKey("mem")); - assertTrue(results.containsKey("mem.free")); - assertTrue(results.containsKey("processors")); - assertTrue(results.containsKey("uptime")); - assertTrue(results.containsKey("systemload.average")); - - assertTrue(results.containsKey("heap.committed")); - assertTrue(results.containsKey("heap.init")); - assertTrue(results.containsKey("heap.used")); - assertTrue(results.containsKey("heap")); - - assertTrue(results.containsKey("nonheap.committed")); - assertTrue(results.containsKey("nonheap.init")); - assertTrue(results.containsKey("nonheap.used")); - assertTrue(results.containsKey("nonheap")); - - assertTrue(results.containsKey("threads.peak")); - assertTrue(results.containsKey("threads.daemon")); - assertTrue(results.containsKey("threads.totalStarted")); - assertTrue(results.containsKey("threads")); - - assertTrue(results.containsKey("classes.loaded")); - assertTrue(results.containsKey("classes.unloaded")); - assertTrue(results.containsKey("classes")); + assertThat(results).containsKey("mem"); + assertThat(results).containsKey("mem.free"); + assertThat(results).containsKey("processors"); + assertThat(results).containsKey("uptime"); + assertThat(results).containsKey("systemload.average"); + assertThat(results).containsKey("heap.committed"); + assertThat(results).containsKey("heap.init"); + assertThat(results).containsKey("heap.used"); + assertThat(results).containsKey("heap"); + assertThat(results).containsKey("nonheap.committed"); + assertThat(results).containsKey("nonheap.init"); + assertThat(results).containsKey("nonheap.used"); + assertThat(results).containsKey("nonheap"); + assertThat(results).containsKey("threads.peak"); + assertThat(results).containsKey("threads.daemon"); + assertThat(results).containsKey("threads.totalStarted"); + assertThat(results).containsKey("threads"); + assertThat(results).containsKey("classes.loaded"); + assertThat(results).containsKey("classes.unloaded"); + assertThat(results).containsKey("classes"); } } diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/TomcatPublicMetricsTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/TomcatPublicMetricsTests.java index 35f41999bc..1e061145f9 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/TomcatPublicMetricsTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/TomcatPublicMetricsTests.java @@ -27,8 +27,7 @@ import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.util.SocketUtils; -import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link TomcatPublicMetrics} @@ -46,9 +45,9 @@ public class TomcatPublicMetricsTests { TomcatPublicMetrics tomcatMetrics = context .getBean(TomcatPublicMetrics.class); Iterator> metrics = tomcatMetrics.metrics().iterator(); - assertThat(metrics.next().getName(), equalTo("httpsessions.max")); - assertThat(metrics.next().getName(), equalTo("httpsessions.active")); - assertThat(metrics.hasNext(), equalTo(false)); + assertThat(metrics.next().getName()).isEqualTo("httpsessions.max"); + assertThat(metrics.next().getName()).isEqualTo("httpsessions.active"); + assertThat(metrics.hasNext()).isFalse(); } finally { context.close(); diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/TraceEndpointTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/TraceEndpointTests.java index 203be5f180..b5cbdbe46a 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/TraceEndpointTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/TraceEndpointTests.java @@ -27,8 +27,7 @@ import org.springframework.boot.context.properties.EnableConfigurationProperties 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.assertj.core.api.Assertions.assertThat; /** * Tests for {@link TraceEndpoint}. @@ -44,7 +43,7 @@ public class TraceEndpointTests extends AbstractEndpointTests { @Test public void invoke() throws Exception { Trace trace = getEndpointBean().invoke().get(0); - assertThat(trace.getInfo().get("a"), equalTo((Object) "b")); + assertThat(trace.getInfo().get("a")).isEqualTo("b"); } @Configuration diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/jmx/EndpointMBeanExporterTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/jmx/EndpointMBeanExporterTests.java index 99b36bc610..652740aedc 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/jmx/EndpointMBeanExporterTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/jmx/EndpointMBeanExporterTests.java @@ -42,13 +42,7 @@ import org.springframework.jmx.export.MBeanExporter; import org.springframework.jmx.support.ObjectNameManager; import org.springframework.util.ObjectUtils; -import static org.hamcrest.Matchers.instanceOf; -import static org.hamcrest.Matchers.is; -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; /** * Tests for {@link EndpointMBeanExporter} @@ -78,9 +72,9 @@ public class EndpointMBeanExporterTests { MBeanExporter mbeanExporter = this.context.getBean(EndpointMBeanExporter.class); MBeanInfo mbeanInfo = mbeanExporter.getServer() .getMBeanInfo(getObjectName("endpoint1", this.context)); - assertNotNull(mbeanInfo); - assertEquals(3, mbeanInfo.getOperations().length); - assertEquals(3, mbeanInfo.getAttributes().length); + assertThat(mbeanInfo).isNotNull(); + assertThat(mbeanInfo.getOperations().length).isEqualTo(3); + assertThat(mbeanInfo.getAttributes().length).isEqualTo(3); } @Test @@ -94,8 +88,8 @@ public class EndpointMBeanExporterTests { new RootBeanDefinition(TestEndpoint.class, null, mpv)); this.context.refresh(); MBeanExporter mbeanExporter = this.context.getBean(EndpointMBeanExporter.class); - assertFalse(mbeanExporter.getServer() - .isRegistered(getObjectName("endpoint1", this.context))); + assertThat(mbeanExporter.getServer() + .isRegistered(getObjectName("endpoint1", this.context))).isFalse(); } @Test @@ -109,8 +103,8 @@ public class EndpointMBeanExporterTests { new RootBeanDefinition(TestEndpoint.class, null, mpv)); this.context.refresh(); MBeanExporter mbeanExporter = this.context.getBean(EndpointMBeanExporter.class); - assertTrue(mbeanExporter.getServer() - .isRegistered(getObjectName("endpoint1", this.context))); + assertThat(mbeanExporter.getServer() + .isRegistered(getObjectName("endpoint1", this.context))).isTrue(); } @Test @@ -124,10 +118,10 @@ public class EndpointMBeanExporterTests { new RootBeanDefinition(TestEndpoint.class)); this.context.refresh(); MBeanExporter mbeanExporter = this.context.getBean(EndpointMBeanExporter.class); - assertNotNull(mbeanExporter.getServer() - .getMBeanInfo(getObjectName("endpoint1", this.context))); - assertNotNull(mbeanExporter.getServer() - .getMBeanInfo(getObjectName("endpoint2", this.context))); + assertThat(mbeanExporter.getServer() + .getMBeanInfo(getObjectName("endpoint1", this.context))).isNotNull(); + assertThat(mbeanExporter.getServer() + .getMBeanInfo(getObjectName("endpoint2", this.context))).isNotNull(); } @Test @@ -141,8 +135,9 @@ public class EndpointMBeanExporterTests { new RootBeanDefinition(TestEndpoint.class)); this.context.refresh(); MBeanExporter mbeanExporter = this.context.getBean(EndpointMBeanExporter.class); - assertNotNull(mbeanExporter.getServer().getMBeanInfo( - getObjectName("test-domain", "endpoint1", false, this.context))); + assertThat(mbeanExporter.getServer().getMBeanInfo( + getObjectName("test-domain", "endpoint1", false, this.context))) + .isNotNull(); } @Test @@ -158,8 +153,9 @@ public class EndpointMBeanExporterTests { new RootBeanDefinition(TestEndpoint.class)); this.context.refresh(); MBeanExporter mbeanExporter = this.context.getBean(EndpointMBeanExporter.class); - assertNotNull(mbeanExporter.getServer().getMBeanInfo( - getObjectName("test-domain", "endpoint1", true, this.context))); + assertThat(mbeanExporter.getServer().getMBeanInfo( + getObjectName("test-domain", "endpoint1", true, this.context))) + .isNotNull(); } @Test @@ -180,10 +176,9 @@ public class EndpointMBeanExporterTests { new RootBeanDefinition(TestEndpoint.class)); this.context.refresh(); MBeanExporter mbeanExporter = this.context.getBean(EndpointMBeanExporter.class); - assertNotNull(mbeanExporter.getServer() - .getMBeanInfo(ObjectNameManager.getInstance( - getObjectName("test-domain", "endpoint1", true, this.context) - .toString() + ",key1=value1,key2=value2"))); + assertThat(mbeanExporter.getServer().getMBeanInfo(ObjectNameManager.getInstance( + getObjectName("test-domain", "endpoint1", true, this.context).toString() + + ",key1=value1,key2=value2"))).isNotNull(); } @Test @@ -198,9 +193,8 @@ public class EndpointMBeanExporterTests { parent.refresh(); this.context.refresh(); MBeanExporter mbeanExporter = this.context.getBean(EndpointMBeanExporter.class); - assertNotNull(mbeanExporter.getServer() - .getMBeanInfo(getObjectName("endpoint1", this.context))); - + assertThat(mbeanExporter.getServer() + .getMBeanInfo(getObjectName("endpoint1", this.context))).isNotNull(); parent.close(); } @@ -216,8 +210,8 @@ public class EndpointMBeanExporterTests { Object response = mbeanExporter.getServer().invoke( getObjectName("endpoint1", this.context), "getData", new Object[0], new String[0]); - assertThat(response, is(instanceOf(Map.class))); - assertThat(((Map) response).get("date"), is(instanceOf(Long.class))); + assertThat(response).isInstanceOf(Map.class); + assertThat(((Map) response).get("date")).isInstanceOf(Long.class); } @Test @@ -237,8 +231,8 @@ public class EndpointMBeanExporterTests { Object response = mbeanExporter.getServer().invoke( getObjectName("endpoint1", this.context), "getData", new Object[0], new String[0]); - assertThat(response, is(instanceOf(Map.class))); - assertThat(((Map) response).get("date"), is(instanceOf(String.class))); + assertThat(response).isInstanceOf(Map.class); + assertThat(((Map) response).get("date")).isInstanceOf(String.class); } private ObjectName getObjectName(String beanKey, GenericApplicationContext context) diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/mvc/EndpointHandlerMappingTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/mvc/EndpointHandlerMappingTests.java index 26fa616529..44be1690ea 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/mvc/EndpointHandlerMappingTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/mvc/EndpointHandlerMappingTests.java @@ -31,11 +31,7 @@ import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.method.HandlerMethod; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.nullValue; -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 EndpointHandlerMapping}. @@ -61,14 +57,11 @@ public class EndpointHandlerMappingTests { Arrays.asList(endpointA, endpointB)); mapping.setApplicationContext(this.context); mapping.afterPropertiesSet(); - assertThat( - mapping.getHandler(new MockHttpServletRequest("GET", "/a")).getHandler(), - equalTo((Object) new HandlerMethod(endpointA, this.method))); - assertThat( - mapping.getHandler(new MockHttpServletRequest("GET", "/b")).getHandler(), - equalTo((Object) new HandlerMethod(endpointB, this.method))); - assertThat(mapping.getHandler(new MockHttpServletRequest("GET", "/c")), - nullValue()); + assertThat(mapping.getHandler(request("GET", "/a")).getHandler()) + .isEqualTo(new HandlerMethod(endpointA, this.method)); + assertThat(mapping.getHandler(request("GET", "/b")).getHandler()) + .isEqualTo(new HandlerMethod(endpointB, this.method)); + assertThat(mapping.getHandler(request("GET", "/c"))).isNull(); } @Test @@ -80,16 +73,11 @@ public class EndpointHandlerMappingTests { mapping.setApplicationContext(this.context); mapping.setPrefix("/a"); mapping.afterPropertiesSet(); - assertThat( - mapping.getHandler(new MockHttpServletRequest("GET", "/a/a")) - .getHandler(), - equalTo((Object) new HandlerMethod(endpointA, this.method))); - assertThat( - mapping.getHandler(new MockHttpServletRequest("GET", "/a/b")) - .getHandler(), - equalTo((Object) new HandlerMethod(endpointB, this.method))); - assertThat(mapping.getHandler(new MockHttpServletRequest("GET", "/a")), - nullValue()); + assertThat(mapping.getHandler(new MockHttpServletRequest("GET", "/a/a")) + .getHandler()).isEqualTo(new HandlerMethod(endpointA, this.method)); + assertThat(mapping.getHandler(new MockHttpServletRequest("GET", "/a/b")) + .getHandler()).isEqualTo(new HandlerMethod(endpointB, this.method)); + assertThat(mapping.getHandler(request("GET", "/a"))).isNull(); } @Test(expected = HttpRequestMethodNotSupportedException.class) @@ -99,8 +87,8 @@ public class EndpointHandlerMappingTests { Arrays.asList(endpoint)); mapping.setApplicationContext(this.context); mapping.afterPropertiesSet(); - assertNotNull(mapping.getHandler(new MockHttpServletRequest("GET", "/a"))); - assertNull(mapping.getHandler(new MockHttpServletRequest("POST", "/a"))); + assertThat(mapping.getHandler(request("GET", "/a"))).isNotNull(); + assertThat(mapping.getHandler(request("POST", "/a"))).isNull(); } @Test @@ -110,7 +98,7 @@ public class EndpointHandlerMappingTests { Arrays.asList(endpoint)); mapping.setApplicationContext(this.context); mapping.afterPropertiesSet(); - assertNotNull(mapping.getHandler(new MockHttpServletRequest("POST", "/a"))); + assertThat(mapping.getHandler(request("POST", "/a"))).isNotNull(); } @Test(expected = HttpRequestMethodNotSupportedException.class) @@ -120,8 +108,8 @@ public class EndpointHandlerMappingTests { Arrays.asList(endpoint)); mapping.setApplicationContext(this.context); mapping.afterPropertiesSet(); - assertNotNull(mapping.getHandler(new MockHttpServletRequest("POST", "/a"))); - assertNull(mapping.getHandler(new MockHttpServletRequest("GET", "/a"))); + assertThat(mapping.getHandler(request("POST", "/a"))).isNotNull(); + assertThat(mapping.getHandler(request("GET", "/a"))).isNull(); } @Test @@ -132,8 +120,7 @@ public class EndpointHandlerMappingTests { mapping.setDisabled(true); mapping.setApplicationContext(this.context); mapping.afterPropertiesSet(); - assertThat(mapping.getHandler(new MockHttpServletRequest("GET", "/a")), - nullValue()); + assertThat(mapping.getHandler(request("GET", "/a"))).isNull(); } @Test @@ -145,10 +132,12 @@ public class EndpointHandlerMappingTests { mapping.setDisabled(true); mapping.setApplicationContext(this.context); mapping.afterPropertiesSet(); - assertThat(mapping.getHandler(new MockHttpServletRequest("GET", "/a")), - nullValue()); - assertThat(mapping.getHandler(new MockHttpServletRequest("POST", "/a")), - nullValue()); + assertThat(mapping.getHandler(request("GET", "/a"))).isNull(); + assertThat(mapping.getHandler(request("POST", "/a"))).isNull(); + } + + private MockHttpServletRequest request(String method, String requestURI) { + return new MockHttpServletRequest(method, requestURI); } private static class TestEndpoint extends AbstractEndpoint { diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/mvc/HalBrowserMvcEndpointBrowserPathIntegrationTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/mvc/HalBrowserMvcEndpointBrowserPathIntegrationTests.java index 20999c0e53..40058ced26 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/mvc/HalBrowserMvcEndpointBrowserPathIntegrationTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/mvc/HalBrowserMvcEndpointBrowserPathIntegrationTests.java @@ -35,7 +35,7 @@ import org.springframework.test.web.servlet.MvcResult; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; -import static org.junit.Assert.assertEquals; +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.header; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @@ -68,7 +68,8 @@ public class HalBrowserMvcEndpointBrowserPathIntegrationTests { MvcResult response = this.mockMvc .perform(get("/actuator/").accept(MediaType.TEXT_HTML)) .andExpect(status().isOk()).andReturn(); - assertEquals("/actuator/browser.html", response.getResponse().getForwardedUrl()); + assertThat(response.getResponse().getForwardedUrl()) + .isEqualTo("/actuator/browser.html"); } @Test diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/mvc/HalBrowserMvcEndpointDisabledIntegrationTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/mvc/HalBrowserMvcEndpointDisabledIntegrationTests.java index ffb22defe2..78538dfda1 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/mvc/HalBrowserMvcEndpointDisabledIntegrationTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/mvc/HalBrowserMvcEndpointDisabledIntegrationTests.java @@ -35,7 +35,7 @@ import org.springframework.test.web.servlet.MvcResult; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; -import static org.junit.Assert.assertEquals; +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.header; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; @@ -78,7 +78,8 @@ public class HalBrowserMvcEndpointDisabledIntegrationTests { MvcResult response = this.mockMvc .perform(get("/actuator/").accept(MediaType.TEXT_HTML)) .andExpect(status().isOk()).andReturn(); - assertEquals("/actuator/browser.html", response.getResponse().getForwardedUrl()); + assertThat(response.getResponse().getForwardedUrl()) + .isEqualTo("/actuator/browser.html"); } @Test diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/mvc/HalBrowserMvcEndpointEndpointsDisabledIntegrationTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/mvc/HalBrowserMvcEndpointEndpointsDisabledIntegrationTests.java index 77f17fd135..2c06adad13 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/mvc/HalBrowserMvcEndpointEndpointsDisabledIntegrationTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/mvc/HalBrowserMvcEndpointEndpointsDisabledIntegrationTests.java @@ -34,8 +34,7 @@ import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; -import static org.hamcrest.Matchers.empty; -import static org.junit.Assert.assertThat; +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.status; @@ -91,7 +90,7 @@ public class HalBrowserMvcEndpointEndpointsDisabledIntegrationTests { @Test public void endpointsAllDisabled() throws Exception { - assertThat(this.mvcEndpoints.getEndpoints(), empty()); + assertThat(this.mvcEndpoints.getEndpoints()).isEmpty(); } @MinimalActuatorHypermediaApplication diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/mvc/HalBrowserMvcEndpointServerContextPathIntegrationTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/mvc/HalBrowserMvcEndpointServerContextPathIntegrationTests.java index 855dc41757..78968489ed 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/mvc/HalBrowserMvcEndpointServerContextPathIntegrationTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/mvc/HalBrowserMvcEndpointServerContextPathIntegrationTests.java @@ -40,8 +40,7 @@ import org.springframework.test.context.web.WebAppConfiguration; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import static org.springframework.hateoas.mvc.ControllerLinkBuilder.linkTo; /** @@ -68,9 +67,8 @@ public class HalBrowserMvcEndpointServerContextPathIntegrationTests { ResponseEntity entity = new TestRestTemplate().exchange( "http://localhost:" + this.port + "/spring/", HttpMethod.GET, new HttpEntity(null, headers), String.class); - assertEquals(HttpStatus.OK, entity.getStatusCode()); - assertTrue("Wrong body: " + entity.getBody(), - entity.getBody().contains("\"_links\":")); + assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); + assertThat(entity.getBody()).contains("\"_links\":"); } @Test @@ -80,9 +78,8 @@ public class HalBrowserMvcEndpointServerContextPathIntegrationTests { ResponseEntity entity = new TestRestTemplate().exchange( "http://localhost:" + this.port + "/spring/actuator/", HttpMethod.GET, new HttpEntity(null, headers), String.class); - assertEquals(HttpStatus.OK, entity.getStatusCode()); - assertTrue("Wrong body: " + entity.getBody(), - entity.getBody().contains(" entity = new TestRestTemplate().exchange( "http://localhost:" + this.port + "/spring/actuator", HttpMethod.GET, new HttpEntity(null, headers), String.class); - assertEquals(HttpStatus.OK, entity.getStatusCode()); - assertTrue("Wrong body: " + entity.getBody(), - entity.getBody().contains("\"_links\":")); + assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); + assertThat(entity.getBody()).contains("\"_links\":"); } @Test @@ -104,9 +100,8 @@ public class HalBrowserMvcEndpointServerContextPathIntegrationTests { ResponseEntity entity = new TestRestTemplate().exchange( "http://localhost:" + this.port + "/spring/actuator/", HttpMethod.GET, new HttpEntity(null, headers), String.class); - assertEquals(HttpStatus.OK, entity.getStatusCode()); - assertTrue("Wrong body: " + entity.getBody(), - entity.getBody().contains("\"_links\":")); + assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); + assertThat(entity.getBody()).contains("\"_links\":"); } @MinimalActuatorHypermediaApplication diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/mvc/HalBrowserMvcEndpointServerPortIntegrationTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/mvc/HalBrowserMvcEndpointServerPortIntegrationTests.java index 6f9ca98e3a..dbcf430ca6 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/mvc/HalBrowserMvcEndpointServerPortIntegrationTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/mvc/HalBrowserMvcEndpointServerPortIntegrationTests.java @@ -40,8 +40,7 @@ import org.springframework.test.context.web.WebAppConfiguration; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import static org.springframework.hateoas.mvc.ControllerLinkBuilder.linkTo; /** @@ -68,11 +67,9 @@ public class HalBrowserMvcEndpointServerPortIntegrationTests { ResponseEntity entity = new TestRestTemplate().exchange( "http://localhost:" + this.port + "/actuator", HttpMethod.GET, new HttpEntity(null, headers), String.class); - assertEquals(HttpStatus.OK, entity.getStatusCode()); - assertTrue("Wrong body: " + entity.getBody(), - entity.getBody().contains("\"_links\":")); - assertTrue("Wrong body: " + entity.getBody(), - entity.getBody().contains(":" + this.port)); + assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); + assertThat(entity.getBody()).contains("\"_links\":"); + assertThat(entity.getBody()).contains(":" + this.port); } @Test @@ -82,11 +79,9 @@ public class HalBrowserMvcEndpointServerPortIntegrationTests { ResponseEntity entity = new TestRestTemplate().exchange( "http://localhost:" + this.port + "/actuator/", HttpMethod.GET, new HttpEntity(null, headers), String.class); - assertEquals(HttpStatus.OK, entity.getStatusCode()); - assertTrue("Wrong body: " + entity.getBody(), - entity.getBody().contains("\"_links\":")); - assertTrue("Wrong body: " + entity.getBody(), - entity.getBody().contains(":" + this.port)); + assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); + assertThat(entity.getBody()).contains("\"_links\":"); + assertThat(entity.getBody()).contains(":" + this.port); } @Test @@ -96,9 +91,8 @@ public class HalBrowserMvcEndpointServerPortIntegrationTests { ResponseEntity entity = new TestRestTemplate().exchange( "http://localhost:" + this.port + "/actuator/", HttpMethod.GET, new HttpEntity(null, headers), String.class); - assertEquals(HttpStatus.OK, entity.getStatusCode()); - assertTrue("Wrong body: " + entity.getBody(), - entity.getBody().contains(" response = (ResponseEntity) result; - assertTrue(response.getBody().getStatus() == Status.DOWN); - assertEquals(HttpStatus.SERVICE_UNAVAILABLE, response.getStatusCode()); + assertThat(response.getBody().getStatus() == Status.DOWN).isTrue(); + assertThat(response.getStatusCode()).isEqualTo(HttpStatus.SERVICE_UNAVAILABLE); } @Test @@ -104,10 +99,10 @@ public class HealthMvcEndpointTests { this.mvc.setStatusMapping( Collections.singletonMap("OK", HttpStatus.INTERNAL_SERVER_ERROR)); Object result = this.mvc.invoke(null); - assertTrue(result instanceof ResponseEntity); + assertThat(result instanceof ResponseEntity).isTrue(); ResponseEntity response = (ResponseEntity) result; - assertTrue(response.getBody().getStatus().equals(new Status("OK"))); - assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, response.getStatusCode()); + assertThat(response.getBody().getStatus().equals(new Status("OK"))).isTrue(); + assertThat(response.getStatusCode()).isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR); } @Test @@ -118,10 +113,10 @@ public class HealthMvcEndpointTests { this.mvc.setStatusMapping(Collections.singletonMap("out-of-service", HttpStatus.INTERNAL_SERVER_ERROR)); Object result = this.mvc.invoke(null); - assertTrue(result instanceof ResponseEntity); + assertThat(result instanceof ResponseEntity).isTrue(); ResponseEntity response = (ResponseEntity) result; - assertTrue(response.getBody().getStatus().equals(Status.OUT_OF_SERVICE)); - assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, response.getStatusCode()); + assertThat(response.getBody().getStatus().equals(Status.OUT_OF_SERVICE)).isTrue(); + assertThat(response.getStatusCode()).isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR); } @Test @@ -130,9 +125,9 @@ public class HealthMvcEndpointTests { .willReturn(new Health.Builder().up().withDetail("foo", "bar").build()); given(this.endpoint.isSensitive()).willReturn(false); Object result = this.mvc.invoke(this.admin); - assertTrue(result instanceof Health); - assertTrue(((Health) result).getStatus() == Status.UP); - assertEquals("bar", ((Health) result).getDetails().get("foo")); + assertThat(result instanceof Health).isTrue(); + assertThat(((Health) result).getStatus() == Status.UP).isTrue(); + assertThat(((Health) result).getDetails().get("foo")).isEqualTo("bar"); } @Test @@ -140,9 +135,9 @@ public class HealthMvcEndpointTests { given(this.endpoint.invoke()) .willReturn(new Health.Builder().up().withDetail("foo", "bar").build()); Object result = this.mvc.invoke(this.user); - assertTrue(result instanceof Health); - assertTrue(((Health) result).getStatus() == Status.UP); - assertNull(((Health) result).getDetails().get("foo")); + assertThat(result instanceof Health).isTrue(); + assertThat(((Health) result).getStatus() == Status.UP).isTrue(); + assertThat(((Health) result).getDetails().get("foo")).isNull(); } @Test @@ -152,19 +147,19 @@ public class HealthMvcEndpointTests { given(this.endpoint.invoke()) .willReturn(new Health.Builder().up().withDetail("foo", "bar").build()); Object result = this.mvc.invoke(this.admin); - assertTrue(result instanceof Health); + assertThat(result instanceof Health).isTrue(); Health health = (Health) result; - assertTrue(health.getStatus() == Status.UP); - assertThat(health.getDetails().size(), is(equalTo(1))); - assertThat(health.getDetails().get("foo"), is(equalTo((Object) "bar"))); + assertThat(health.getStatus() == Status.UP).isTrue(); + assertThat(health.getDetails()).hasSize(1); + assertThat(health.getDetails().get("foo")).isEqualTo("bar"); given(this.endpoint.invoke()).willReturn(new Health.Builder().down().build()); result = this.mvc.invoke(null); // insecure now - assertTrue(result instanceof Health); + assertThat(result instanceof Health).isTrue(); health = (Health) result; // so the result is cached - assertTrue(health.getStatus() == Status.UP); + assertThat(health.getStatus() == Status.UP).isTrue(); // but the details are hidden - assertThat(health.getDetails().size(), is(equalTo(0))); + assertThat(health.getDetails()).isEmpty(); } @Test @@ -174,9 +169,9 @@ public class HealthMvcEndpointTests { given(this.endpoint.invoke()) .willReturn(new Health.Builder().up().withDetail("foo", "bar").build()); Object result = this.mvc.invoke(null); - assertTrue(result instanceof Health); - assertTrue(((Health) result).getStatus() == Status.UP); - assertEquals("bar", ((Health) result).getDetails().get("foo")); + assertThat(result instanceof Health).isTrue(); + assertThat(((Health) result).getStatus() == Status.UP).isTrue(); + assertThat(((Health) result).getDetails().get("foo")).isEqualTo("bar"); } @Test @@ -185,9 +180,9 @@ public class HealthMvcEndpointTests { given(this.endpoint.invoke()) .willReturn(new Health.Builder().up().withDetail("foo", "bar").build()); Object result = this.mvc.invoke(null); - assertTrue(result instanceof Health); - assertTrue(((Health) result).getStatus() == Status.UP); - assertNull(((Health) result).getDetails().get("foo")); + assertThat(result instanceof Health).isTrue(); + assertThat(((Health) result).getStatus() == Status.UP).isTrue(); + assertThat(((Health) result).getDetails().get("foo")).isNull(); } @Test @@ -198,9 +193,9 @@ public class HealthMvcEndpointTests { given(this.endpoint.invoke()) .willReturn(new Health.Builder().up().withDetail("foo", "bar").build()); Object result = this.mvc.invoke(null); - assertTrue(result instanceof Health); - assertTrue(((Health) result).getStatus() == Status.UP); - assertEquals("bar", ((Health) result).getDetails().get("foo")); + assertThat(result instanceof Health).isTrue(); + assertThat(((Health) result).getStatus() == Status.UP).isTrue(); + assertThat(((Health) result).getDetails().get("foo")).isEqualTo("bar"); } @Test @@ -209,13 +204,13 @@ public class HealthMvcEndpointTests { given(this.endpoint.invoke()) .willReturn(new Health.Builder().up().withDetail("foo", "bar").build()); Object result = this.mvc.invoke(null); - assertTrue(result instanceof Health); - assertTrue(((Health) result).getStatus() == Status.UP); + assertThat(result instanceof Health).isTrue(); + assertThat(((Health) result).getStatus() == Status.UP).isTrue(); given(this.endpoint.invoke()).willReturn(new Health.Builder().down().build()); result = this.mvc.invoke(null); @SuppressWarnings("unchecked") Health health = ((ResponseEntity) result).getBody(); - assertTrue(health.getStatus() == Status.DOWN); + assertThat(health.getStatus() == Status.DOWN).isTrue(); } @Test @@ -225,14 +220,14 @@ public class HealthMvcEndpointTests { given(this.endpoint.invoke()) .willReturn(new Health.Builder().up().withDetail("foo", "bar").build()); Object result = this.mvc.invoke(null); - assertTrue(result instanceof Health); - assertTrue(((Health) result).getStatus() == Status.UP); + assertThat(result instanceof Health).isTrue(); + assertThat(((Health) result).getStatus() == Status.UP).isTrue(); Thread.sleep(100); given(this.endpoint.invoke()).willReturn(new Health.Builder().down().build()); result = this.mvc.invoke(null); @SuppressWarnings("unchecked") Health health = ((ResponseEntity) result).getBody(); - assertTrue(health.getStatus() == Status.DOWN); + assertThat(health.getStatus() == Status.DOWN).isTrue(); } } diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/mvc/JolokiaMvcEndpointTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/mvc/JolokiaMvcEndpointTests.java index f814720c33..9b9f073756 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/mvc/JolokiaMvcEndpointTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/mvc/JolokiaMvcEndpointTests.java @@ -18,7 +18,6 @@ package org.springframework.boot.actuate.endpoint.mvc; import java.util.Set; -import org.hamcrest.Matcher; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; @@ -43,10 +42,8 @@ import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; import org.springframework.web.servlet.config.annotation.EnableWebMvc; +import static org.assertj.core.api.Assertions.assertThat; import static org.hamcrest.Matchers.containsString; -import static org.hamcrest.Matchers.hasItem; -import static org.hamcrest.Matchers.instanceOf; -import static org.junit.Assert.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; @@ -78,10 +75,9 @@ public class JolokiaMvcEndpointTests { } @Test - @SuppressWarnings({ "rawtypes", "unchecked" }) public void endpointRegistered() throws Exception { Set values = this.endpoints.getEndpoints(); - assertThat(values, (Matcher) hasItem(instanceOf(JolokiaMvcEndpoint.class))); + assertThat(values).hasAtLeastOneElementOfType(JolokiaMvcEndpoint.class); } @Test diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/mvc/LogFileMvcEndpointTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/mvc/LogFileMvcEndpointTests.java index 1c8b28caf1..27bd05d41d 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/mvc/LogFileMvcEndpointTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/mvc/LogFileMvcEndpointTests.java @@ -31,9 +31,7 @@ import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; import org.springframework.util.FileCopyUtils; -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 LogFileMvcEndpoint}. @@ -67,7 +65,7 @@ public class LogFileMvcEndpointTests { MockHttpServletRequest request = new MockHttpServletRequest( HttpMethod.HEAD.name(), "/logfile"); this.mvc.invoke(request, response); - assertThat(response.getStatus(), equalTo(HttpStatus.NOT_FOUND.value())); + assertThat(response.getStatus()).isEqualTo(HttpStatus.NOT_FOUND.value()); } @Test @@ -77,7 +75,7 @@ public class LogFileMvcEndpointTests { MockHttpServletRequest request = new MockHttpServletRequest( HttpMethod.HEAD.name(), "/logfile"); this.mvc.invoke(request, response); - assertThat(response.getStatus(), equalTo(HttpStatus.NOT_FOUND.value())); + assertThat(response.getStatus()).isEqualTo(HttpStatus.NOT_FOUND.value()); } @Test @@ -87,7 +85,7 @@ public class LogFileMvcEndpointTests { MockHttpServletRequest request = new MockHttpServletRequest( HttpMethod.HEAD.name(), "/logfile"); this.mvc.invoke(request, response); - assertThat(response.getStatus(), equalTo(HttpStatus.OK.value())); + assertThat(response.getStatus()).isEqualTo(HttpStatus.OK.value()); } @Test @@ -98,7 +96,7 @@ public class LogFileMvcEndpointTests { MockHttpServletRequest request = new MockHttpServletRequest( HttpMethod.HEAD.name(), "/logfile"); this.mvc.invoke(request, response); - assertThat(response.getStatus(), equalTo(HttpStatus.NOT_FOUND.value())); + assertThat(response.getStatus()).isEqualTo(HttpStatus.NOT_FOUND.value()); } @Test @@ -108,8 +106,8 @@ public class LogFileMvcEndpointTests { MockHttpServletRequest request = new MockHttpServletRequest(HttpMethod.GET.name(), "/logfile"); this.mvc.invoke(request, response); - assertThat(response.getStatus(), equalTo(HttpStatus.OK.value())); - assertEquals("--TEST--", response.getContentAsString()); + assertThat(response.getStatus()).isEqualTo(HttpStatus.OK.value()); + assertThat(response.getContentAsString()).isEqualTo("--TEST--"); } } diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/mvc/MvcEndpointsTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/mvc/MvcEndpointsTests.java index 6b1efe420e..a9ccf71299 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/mvc/MvcEndpointsTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/mvc/MvcEndpointsTests.java @@ -22,7 +22,7 @@ import org.springframework.boot.actuate.endpoint.AbstractEndpoint; import org.springframework.boot.test.EnvironmentTestUtils; import org.springframework.context.support.StaticApplicationContext; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link MvcEndpoints}. @@ -41,7 +41,7 @@ public class MvcEndpointsTests { new TestEndpoint()); this.endpoints.setApplicationContext(this.context); this.endpoints.afterPropertiesSet(); - assertEquals(1, this.endpoints.getEndpoints().size()); + assertThat(this.endpoints.getEndpoints()).hasSize(1); } @Test @@ -52,7 +52,7 @@ public class MvcEndpointsTests { new TestEndpoint()); this.endpoints.setApplicationContext(this.context); this.endpoints.afterPropertiesSet(); - assertEquals(1, this.endpoints.getEndpoints().size()); + assertThat(this.endpoints.getEndpoints()).hasSize(1); } @Test @@ -61,7 +61,7 @@ public class MvcEndpointsTests { new EndpointMvcAdapter(new TestEndpoint())); this.endpoints.setApplicationContext(this.context); this.endpoints.afterPropertiesSet(); - assertEquals(1, this.endpoints.getEndpoints().size()); + assertThat(this.endpoints.getEndpoints()).hasSize(1); } @Test @@ -72,9 +72,9 @@ public class MvcEndpointsTests { new TestEndpoint()); this.endpoints.setApplicationContext(this.context); this.endpoints.afterPropertiesSet(); - assertEquals(1, this.endpoints.getEndpoints().size()); - assertEquals("/foo/bar", - this.endpoints.getEndpoints().iterator().next().getPath()); + assertThat(this.endpoints.getEndpoints()).hasSize(1); + assertThat(this.endpoints.getEndpoints().iterator().next().getPath()) + .isEqualTo("/foo/bar"); } protected static class TestEndpoint extends AbstractEndpoint { diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/mvc/NamePatternFilterTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/mvc/NamePatternFilterTests.java index 838c190c65..7401cf0a30 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/mvc/NamePatternFilterTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/mvc/NamePatternFilterTests.java @@ -20,11 +20,7 @@ import java.util.Map; import org.junit.Test; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.hasEntry; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.nullValue; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link NamePatternFilter}. @@ -37,54 +33,54 @@ public class NamePatternFilterTests { @Test public void nonRegex() throws Exception { MockNamePatternFilter filter = new MockNamePatternFilter(); - assertThat(filter.getResults("not.a.regex"), - hasEntry("not.a.regex", (Object) "not.a.regex")); - assertThat(filter.isGetNamesCalled(), equalTo(false)); + assertThat(filter.getResults("not.a.regex")).containsEntry("not.a.regex", + "not.a.regex"); + assertThat(filter.isGetNamesCalled()).isFalse(); } @Test public void regexRepetitionZeroOrMore() { MockNamePatternFilter filter = new MockNamePatternFilter(); Map results = filter.getResults("fo.*"); - assertThat(results.get("foo"), equalTo((Object) "foo")); - assertThat(results.get("fool"), equalTo((Object) "fool")); - assertThat(filter.isGetNamesCalled(), equalTo(true)); + assertThat(results.get("foo")).isEqualTo("foo"); + assertThat(results.get("fool")).isEqualTo("fool"); + assertThat(filter.isGetNamesCalled()).isTrue(); } @Test public void regexRepetitionOneOrMore() { MockNamePatternFilter filter = new MockNamePatternFilter(); Map results = filter.getResults("fo.+"); - assertThat(results.get("foo"), equalTo((Object) "foo")); - assertThat(results.get("fool"), equalTo((Object) "fool")); - assertThat(filter.isGetNamesCalled(), equalTo(true)); + assertThat(results.get("foo")).isEqualTo("foo"); + assertThat(results.get("fool")).isEqualTo("fool"); + assertThat(filter.isGetNamesCalled()).isTrue(); } @Test public void regexEndAnchor() { MockNamePatternFilter filter = new MockNamePatternFilter(); Map results = filter.getResults("foo$"); - assertThat(results.get("foo"), equalTo((Object) "foo")); - assertThat(results.get("fool"), is(nullValue())); - assertThat(filter.isGetNamesCalled(), equalTo(true)); + assertThat(results.get("foo")).isEqualTo("foo"); + assertThat(results.get("fool")).isNull(); + assertThat(filter.isGetNamesCalled()).isTrue(); } @Test public void regexStartAnchor() { MockNamePatternFilter filter = new MockNamePatternFilter(); Map results = filter.getResults("^foo"); - assertThat(results.get("foo"), equalTo((Object) "foo")); - assertThat(results.get("fool"), is(nullValue())); - assertThat(filter.isGetNamesCalled(), equalTo(true)); + assertThat(results.get("foo")).isEqualTo("foo"); + assertThat(results.get("fool")).isNull(); + assertThat(filter.isGetNamesCalled()).isTrue(); } @Test public void regexCharacterClass() { MockNamePatternFilter filter = new MockNamePatternFilter(); Map results = filter.getResults("fo[a-z]l"); - assertThat(results.get("foo"), is(nullValue())); - assertThat(results.get("fool"), equalTo((Object) "fool")); - assertThat(filter.isGetNamesCalled(), equalTo(true)); + assertThat(results.get("foo")).isNull(); + assertThat(results.get("fool")).isEqualTo("fool"); + assertThat(filter.isGetNamesCalled()).isTrue(); } private static class MockNamePatternFilter extends NamePatternFilter { diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/mvc/ShutdownMvcEndpointTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/mvc/ShutdownMvcEndpointTests.java index e5b2e61236..909d00dd2d 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/mvc/ShutdownMvcEndpointTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/mvc/ShutdownMvcEndpointTests.java @@ -24,7 +24,7 @@ import org.springframework.boot.actuate.endpoint.ShutdownEndpoint; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; /** @@ -43,7 +43,7 @@ public class ShutdownMvcEndpointTests { @SuppressWarnings("unchecked") ResponseEntity> response = (ResponseEntity>) this.mvc .invoke(); - assertEquals(HttpStatus.NOT_FOUND, response.getStatusCode()); + assertThat(response.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND); } } diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/ApplicationHealthIndicatorTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/ApplicationHealthIndicatorTests.java index 4c0eab893b..825ff894c0 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/ApplicationHealthIndicatorTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/ApplicationHealthIndicatorTests.java @@ -18,7 +18,7 @@ package org.springframework.boot.actuate.health; import org.junit.Test; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link ApplicationHealthIndicator}. @@ -30,7 +30,7 @@ public class ApplicationHealthIndicatorTests { @Test public void indicatesUp() throws Exception { ApplicationHealthIndicator healthIndicator = new ApplicationHealthIndicator(); - assertEquals(Status.UP, healthIndicator.health().getStatus()); + assertThat(healthIndicator.health().getStatus()).isEqualTo(Status.UP); } } diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/CompositeHealthIndicatorTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/CompositeHealthIndicatorTests.java index 1700cac758..39154d2b90 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/CompositeHealthIndicatorTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/CompositeHealthIndicatorTests.java @@ -25,10 +25,7 @@ import org.junit.Test; import org.mockito.Mock; import org.mockito.MockitoAnnotations; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.hasEntry; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.BDDMockito.given; /** @@ -72,11 +69,11 @@ public class CompositeHealthIndicatorTests { CompositeHealthIndicator composite = new CompositeHealthIndicator( this.healthAggregator, indicators); Health result = composite.health(); - assertThat(result.getDetails().size(), equalTo(2)); - assertThat(result.getDetails(), hasEntry("one", - (Object) new Health.Builder().unknown().withDetail("1", "1").build())); - assertThat(result.getDetails(), hasEntry("two", - (Object) new Health.Builder().unknown().withDetail("2", "2").build())); + assertThat(result.getDetails()).hasSize(2); + assertThat(result.getDetails()).containsEntry("one", + new Health.Builder().unknown().withDetail("1", "1").build()); + assertThat(result.getDetails()).containsEntry("two", + new Health.Builder().unknown().withDetail("2", "2").build()); } @Test @@ -88,13 +85,13 @@ public class CompositeHealthIndicatorTests { this.healthAggregator, indicators); composite.addHealthIndicator("three", this.three); Health result = composite.health(); - assertThat(result.getDetails().size(), equalTo(3)); - assertThat(result.getDetails(), hasEntry("one", - (Object) new Health.Builder().unknown().withDetail("1", "1").build())); - assertThat(result.getDetails(), hasEntry("two", - (Object) new Health.Builder().unknown().withDetail("2", "2").build())); - assertThat(result.getDetails(), hasEntry("three", - (Object) new Health.Builder().unknown().withDetail("3", "3").build())); + assertThat(result.getDetails()).hasSize(3); + assertThat(result.getDetails()).containsEntry("one", + new Health.Builder().unknown().withDetail("1", "1").build()); + assertThat(result.getDetails()).containsEntry("two", + new Health.Builder().unknown().withDetail("2", "2").build()); + assertThat(result.getDetails()).containsEntry("three", + new Health.Builder().unknown().withDetail("3", "3").build()); } @Test @@ -104,11 +101,11 @@ public class CompositeHealthIndicatorTests { composite.addHealthIndicator("one", this.one); composite.addHealthIndicator("two", this.two); Health result = composite.health(); - assertThat(result.getDetails().size(), equalTo(2)); - assertThat(result.getDetails(), hasEntry("one", - (Object) new Health.Builder().unknown().withDetail("1", "1").build())); - assertThat(result.getDetails(), hasEntry("two", - (Object) new Health.Builder().unknown().withDetail("2", "2").build())); + assertThat(result.getDetails().size()).isEqualTo(2); + assertThat(result.getDetails()).containsEntry("one", + new Health.Builder().unknown().withDetail("1", "1").build()); + assertThat(result.getDetails()).containsEntry("two", + new Health.Builder().unknown().withDetail("2", "2").build()); } @Test @@ -121,15 +118,12 @@ public class CompositeHealthIndicatorTests { CompositeHealthIndicator composite = new CompositeHealthIndicator( this.healthAggregator); composite.addHealthIndicator("db", innerComposite); - Health result = composite.health(); - ObjectMapper mapper = new ObjectMapper(); - assertEquals( - "{\"status\":\"UNKNOWN\",\"db\":{\"status\":\"UNKNOWN\"" + assertThat(mapper.writeValueAsString(result)) + .isEqualTo("{\"status\":\"UNKNOWN\",\"db\":{\"status\":\"UNKNOWN\"" + ",\"db1\":{\"status\":\"UNKNOWN\",\"1\":\"1\"}," - + "\"db2\":{\"status\":\"UNKNOWN\",\"2\":\"2\"}}}", - mapper.writeValueAsString(result)); + + "\"db2\":{\"status\":\"UNKNOWN\",\"2\":\"2\"}}}"); } } diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/DataSourceHealthIndicatorTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/DataSourceHealthIndicatorTests.java index 62fcf46beb..1ac7811ae7 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/DataSourceHealthIndicatorTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/DataSourceHealthIndicatorTests.java @@ -29,12 +29,7 @@ import org.springframework.boot.autoconfigure.jdbc.EmbeddedDatabaseConnection; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.datasource.SingleConnectionDataSource; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.notNullValue; -import static org.hamcrest.Matchers.nullValue; -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; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; @@ -70,8 +65,8 @@ public class DataSourceHealthIndicatorTests { public void database() { this.indicator.setDataSource(this.dataSource); Health health = this.indicator.health(); - assertNotNull(health.getDetails().get("database")); - assertNotNull(health.getDetails().get("hello")); + assertThat(health.getDetails().get("database")).isNotNull(); + assertThat(health.getDetails().get("hello")).isNotNull(); } @Test @@ -82,9 +77,9 @@ public class DataSourceHealthIndicatorTests { this.indicator.setQuery("SELECT COUNT(*) from FOO"); Health health = this.indicator.health(); System.err.println(health); - assertNotNull(health.getDetails().get("database")); - assertEquals(Status.UP, health.getStatus()); - assertNotNull(health.getDetails().get("hello")); + assertThat(health.getDetails().get("database")).isNotNull(); + assertThat(health.getStatus()).isEqualTo(Status.UP); + assertThat(health.getDetails().get("hello")).isNotNull(); } @Test @@ -92,8 +87,8 @@ public class DataSourceHealthIndicatorTests { this.indicator.setDataSource(this.dataSource); this.indicator.setQuery("SELECT COUNT(*) from BAR"); Health health = this.indicator.health(); - assertThat(health.getDetails().get("database"), notNullValue()); - assertEquals(Status.DOWN, health.getStatus()); + assertThat(health.getDetails().get("database")).isNotNull(); + assertThat(health.getStatus()).isEqualTo(Status.DOWN); } @Test @@ -105,24 +100,24 @@ public class DataSourceHealthIndicatorTests { given(dataSource.getConnection()).willReturn(connection); this.indicator.setDataSource(dataSource); Health health = this.indicator.health(); - assertNotNull(health.getDetails().get("database")); + assertThat(health.getDetails().get("database")).isNotNull(); verify(connection, times(2)).close(); } @Test public void productLookups() throws Exception { - assertThat(Product.forProduct("newone"), nullValue()); - assertThat(Product.forProduct("HSQL Database Engine"), equalTo(Product.HSQLDB)); - assertThat(Product.forProduct("Oracle"), equalTo(Product.ORACLE)); - assertThat(Product.forProduct("Apache Derby"), equalTo(Product.DERBY)); - assertThat(Product.forProduct("DB2"), equalTo(Product.DB2)); - assertThat(Product.forProduct("DB2/LINUXX8664"), equalTo(Product.DB2)); - assertThat(Product.forProduct("DB2 UDB for AS/400"), equalTo(Product.DB2_AS400)); - assertThat(Product.forProduct("DB3 XDB for AS/400"), equalTo(Product.DB2_AS400)); - assertThat(Product.forProduct("Informix Dynamic Server"), - equalTo(Product.INFORMIX)); - assertThat(Product.forProduct("Firebird 2.5.WI"), equalTo(Product.FIREBIRD)); - assertThat(Product.forProduct("Firebird 2.1.LI"), equalTo(Product.FIREBIRD)); + assertThat(Product.forProduct("newone")).isNull(); + assertThat(Product.forProduct("HSQL Database Engine")).isEqualTo(Product.HSQLDB); + assertThat(Product.forProduct("Oracle")).isEqualTo(Product.ORACLE); + assertThat(Product.forProduct("Apache Derby")).isEqualTo(Product.DERBY); + assertThat(Product.forProduct("DB2")).isEqualTo(Product.DB2); + assertThat(Product.forProduct("DB2/LINUXX8664")).isEqualTo(Product.DB2); + assertThat(Product.forProduct("DB2 UDB for AS/400")).isEqualTo(Product.DB2_AS400); + assertThat(Product.forProduct("DB3 XDB for AS/400")).isEqualTo(Product.DB2_AS400); + assertThat(Product.forProduct("Informix Dynamic Server")) + .isEqualTo(Product.INFORMIX); + assertThat(Product.forProduct("Firebird 2.5.WI")).isEqualTo(Product.FIREBIRD); + assertThat(Product.forProduct("Firebird 2.1.LI")).isEqualTo(Product.FIREBIRD); } } diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/DiskSpaceHealthIndicatorTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/DiskSpaceHealthIndicatorTests.java index 69a9c0cdaf..c78971a436 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/DiskSpaceHealthIndicatorTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/DiskSpaceHealthIndicatorTests.java @@ -26,7 +26,7 @@ import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.BDDMockito.given; /** @@ -60,10 +60,10 @@ public class DiskSpaceHealthIndicatorTests { given(this.fileMock.getFreeSpace()).willReturn(THRESHOLD_BYTES + 10); given(this.fileMock.getTotalSpace()).willReturn(THRESHOLD_BYTES * 10); Health health = this.healthIndicator.health(); - assertEquals(Status.UP, health.getStatus()); - assertEquals(THRESHOLD_BYTES, health.getDetails().get("threshold")); - assertEquals(THRESHOLD_BYTES + 10, health.getDetails().get("free")); - assertEquals(THRESHOLD_BYTES * 10, health.getDetails().get("total")); + assertThat(health.getStatus()).isEqualTo(Status.UP); + assertThat(health.getDetails().get("threshold")).isEqualTo(THRESHOLD_BYTES); + assertThat(health.getDetails().get("free")).isEqualTo(THRESHOLD_BYTES + 10); + assertThat(health.getDetails().get("total")).isEqualTo(THRESHOLD_BYTES * 10); } @Test @@ -71,10 +71,10 @@ public class DiskSpaceHealthIndicatorTests { given(this.fileMock.getFreeSpace()).willReturn(THRESHOLD_BYTES - 10); given(this.fileMock.getTotalSpace()).willReturn(THRESHOLD_BYTES * 10); Health health = this.healthIndicator.health(); - assertEquals(Status.DOWN, health.getStatus()); - assertEquals(THRESHOLD_BYTES, health.getDetails().get("threshold")); - assertEquals(THRESHOLD_BYTES - 10, health.getDetails().get("free")); - assertEquals(THRESHOLD_BYTES * 10, health.getDetails().get("total")); + assertThat(health.getStatus()).isEqualTo(Status.DOWN); + assertThat(health.getDetails().get("threshold")).isEqualTo(THRESHOLD_BYTES); + assertThat(health.getDetails().get("free")).isEqualTo(THRESHOLD_BYTES - 10); + assertThat(health.getDetails().get("total")).isEqualTo(THRESHOLD_BYTES * 10); } private DiskSpaceHealthIndicatorProperties createProperties(File path, diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/ElasticsearchHealthIndicatorTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/ElasticsearchHealthIndicatorTests.java index 713a682b54..9413d97fb4 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/ElasticsearchHealthIndicatorTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/ElasticsearchHealthIndicatorTests.java @@ -39,11 +39,7 @@ import org.mockito.ArgumentCaptor; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; -import static org.hamcrest.Matchers.arrayContaining; -import static org.hamcrest.Matchers.containsString; -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.BDDMockito.given; import static org.mockito.Matchers.any; @@ -84,9 +80,9 @@ public class ElasticsearchHealthIndicatorTests { .forClass(ClusterHealthRequest.class); given(this.cluster.health(requestCaptor.capture())).willReturn(responseFuture); Health health = this.indicator.health(); - assertThat(responseFuture.getTimeout, is(100L)); - assertThat(requestCaptor.getValue().indices(), is(arrayContaining("_all"))); - assertThat(health.getStatus(), is(Status.UP)); + assertThat(responseFuture.getTimeout).isEqualTo(100L); + assertThat(requestCaptor.getValue().indices()).contains("_all"); + assertThat(health.getStatus()).isEqualTo(Status.UP); } @Test @@ -99,9 +95,9 @@ public class ElasticsearchHealthIndicatorTests { this.properties.getIndices() .addAll(Arrays.asList("test-index-1", "test-index-2")); Health health = this.indicator.health(); - assertThat(requestCaptor.getValue().indices(), - is(arrayContaining("test-index-1", "test-index-2"))); - assertThat(health.getStatus(), is(Status.UP)); + assertThat(requestCaptor.getValue().indices()).contains("test-index-1", + "test-index-2"); + assertThat(health.getStatus()).isEqualTo(Status.UP); } @Test @@ -113,7 +109,7 @@ public class ElasticsearchHealthIndicatorTests { given(this.cluster.health(requestCaptor.capture())).willReturn(responseFuture); this.properties.setResponseTimeout(1000L); this.indicator.health(); - assertThat(responseFuture.getTimeout, is(1000L)); + assertThat(responseFuture.getTimeout).isEqualTo(1000L); } @Test @@ -123,7 +119,7 @@ public class ElasticsearchHealthIndicatorTests { given(this.cluster.health(any(ClusterHealthRequest.class))) .willReturn(responseFuture); Health health = this.indicator.health(); - assertThat(health.getStatus(), is(Status.UP)); + assertThat(health.getStatus()).isEqualTo(Status.UP); Map details = health.getDetails(); assertDetail(details, "clusterName", "test-cluster"); assertDetail(details, "activeShards", 1); @@ -141,7 +137,7 @@ public class ElasticsearchHealthIndicatorTests { responseFuture.onResponse(new StubClusterHealthResponse(ClusterHealthStatus.RED)); given(this.cluster.health(any(ClusterHealthRequest.class))) .willReturn(responseFuture); - assertThat(this.indicator.health().getStatus(), is(Status.DOWN)); + assertThat(this.indicator.health().getStatus()).isEqualTo(Status.DOWN); } @Test @@ -151,7 +147,7 @@ public class ElasticsearchHealthIndicatorTests { .onResponse(new StubClusterHealthResponse(ClusterHealthStatus.YELLOW)); given(this.cluster.health(any(ClusterHealthRequest.class))) .willReturn(responseFuture); - assertThat(this.indicator.health().getStatus(), is(Status.UP)); + assertThat(this.indicator.health().getStatus()).isEqualTo(Status.UP); } @Test @@ -160,14 +156,14 @@ public class ElasticsearchHealthIndicatorTests { given(this.cluster.health(any(ClusterHealthRequest.class))) .willReturn(responseFuture); Health health = this.indicator.health(); - assertThat(health.getStatus(), is(Status.DOWN)); - assertThat((String) health.getDetails().get("error"), - containsString(ElasticsearchTimeoutException.class.getName())); + assertThat(health.getStatus()).isEqualTo(Status.DOWN); + assertThat((String) health.getDetails().get("error")) + .contains(ElasticsearchTimeoutException.class.getName()); } @SuppressWarnings("unchecked") private void assertDetail(Map details, String detail, T value) { - assertThat((T) details.get(detail), is(equalTo(value))); + assertThat((T) details.get(detail)).isEqualTo(value); } private final static class StubClusterHealthResponse extends ClusterHealthResponse { diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/HealthTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/HealthTests.java index c3ad64e04f..edde833b00 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/HealthTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/HealthTests.java @@ -22,9 +22,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.not; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link Health}. @@ -46,16 +44,16 @@ public class HealthTests { @Test public void createWithStatus() throws Exception { Health health = Health.status(Status.UP).build(); - assertThat(health.getStatus(), equalTo(Status.UP)); - assertThat(health.getDetails().size(), equalTo(0)); + assertThat(health.getStatus()).isEqualTo(Status.UP); + assertThat(health.getDetails().size()).isEqualTo(0); } @Test public void createWithDetails() throws Exception { Health health = new Health.Builder(Status.UP, Collections.singletonMap("a", "b")) .build(); - assertThat(health.getStatus(), equalTo(Status.UP)); - assertThat(health.getDetails().get("a"), equalTo((Object) "b")); + assertThat(health.getStatus()).isEqualTo(Status.UP); + assertThat(health.getDetails().get("a")).isEqualTo("b"); } @Test @@ -65,12 +63,12 @@ public class HealthTests { Health h2 = new Health.Builder(Status.UP, Collections.singletonMap("a", "b")) .build(); Health h3 = new Health.Builder(Status.UP).build(); - assertThat(h1, equalTo(h1)); - assertThat(h1, equalTo(h2)); - assertThat(h1, not(equalTo(h3))); - assertThat(h1.hashCode(), equalTo(h1.hashCode())); - assertThat(h1.hashCode(), equalTo(h2.hashCode())); - assertThat(h1.hashCode(), not(equalTo(h3.hashCode()))); + assertThat(h1).isEqualTo(h1); + assertThat(h1).isEqualTo(h2); + assertThat(h1).isNotEqualTo(h3); + assertThat(h1.hashCode()).isEqualTo(h1.hashCode()); + assertThat(h1.hashCode()).isEqualTo(h2.hashCode()); + assertThat(h1.hashCode()).isNotEqualTo(h3.hashCode()); } @Test @@ -78,82 +76,82 @@ public class HealthTests { RuntimeException ex = new RuntimeException("bang"); Health health = new Health.Builder(Status.UP, Collections.singletonMap("a", "b")) .withException(ex).build(); - assertThat(health.getDetails().get("a"), equalTo((Object) "b")); - assertThat(health.getDetails().get("error"), - equalTo((Object) "java.lang.RuntimeException: bang")); + assertThat(health.getDetails().get("a")).isEqualTo("b"); + assertThat(health.getDetails().get("error")) + .isEqualTo("java.lang.RuntimeException: bang"); } @Test public void withDetails() throws Exception { Health health = new Health.Builder(Status.UP, Collections.singletonMap("a", "b")) .withDetail("c", "d").build(); - assertThat(health.getDetails().get("a"), equalTo((Object) "b")); - assertThat(health.getDetails().get("c"), equalTo((Object) "d")); + assertThat(health.getDetails().get("a")).isEqualTo("b"); + assertThat(health.getDetails().get("c")).isEqualTo("d"); } @Test public void unknownWithDetails() throws Exception { Health health = new Health.Builder().unknown().withDetail("a", "b").build(); - assertThat(health.getStatus(), equalTo(Status.UNKNOWN)); - assertThat(health.getDetails().get("a"), equalTo((Object) "b")); + assertThat(health.getStatus()).isEqualTo(Status.UNKNOWN); + assertThat(health.getDetails().get("a")).isEqualTo("b"); } @Test public void unknown() throws Exception { Health health = new Health.Builder().unknown().build(); - assertThat(health.getStatus(), equalTo(Status.UNKNOWN)); - assertThat(health.getDetails().size(), equalTo(0)); + assertThat(health.getStatus()).isEqualTo(Status.UNKNOWN); + assertThat(health.getDetails().size()).isEqualTo(0); } @Test public void upWithDetails() throws Exception { Health health = new Health.Builder().up().withDetail("a", "b").build(); - assertThat(health.getStatus(), equalTo(Status.UP)); - assertThat(health.getDetails().get("a"), equalTo((Object) "b")); + assertThat(health.getStatus()).isEqualTo(Status.UP); + assertThat(health.getDetails().get("a")).isEqualTo("b"); } @Test public void up() throws Exception { Health health = new Health.Builder().up().build(); - assertThat(health.getStatus(), equalTo(Status.UP)); - assertThat(health.getDetails().size(), equalTo(0)); + assertThat(health.getStatus()).isEqualTo(Status.UP); + assertThat(health.getDetails().size()).isEqualTo(0); } @Test public void downWithException() throws Exception { RuntimeException ex = new RuntimeException("bang"); Health health = Health.down(ex).build(); - assertThat(health.getStatus(), equalTo(Status.DOWN)); - assertThat(health.getDetails().get("error"), - equalTo((Object) "java.lang.RuntimeException: bang")); + assertThat(health.getStatus()).isEqualTo(Status.DOWN); + assertThat(health.getDetails().get("error")) + .isEqualTo("java.lang.RuntimeException: bang"); } @Test public void down() throws Exception { Health health = Health.down().build(); - assertThat(health.getStatus(), equalTo(Status.DOWN)); - assertThat(health.getDetails().size(), equalTo(0)); + assertThat(health.getStatus()).isEqualTo(Status.DOWN); + assertThat(health.getDetails().size()).isEqualTo(0); } @Test public void outOfService() throws Exception { Health health = Health.outOfService().build(); - assertThat(health.getStatus(), equalTo(Status.OUT_OF_SERVICE)); - assertThat(health.getDetails().size(), equalTo(0)); + assertThat(health.getStatus()).isEqualTo(Status.OUT_OF_SERVICE); + assertThat(health.getDetails().size()).isEqualTo(0); } @Test public void statusCode() throws Exception { Health health = Health.status("UP").build(); - assertThat(health.getStatus(), equalTo(Status.UP)); - assertThat(health.getDetails().size(), equalTo(0)); + assertThat(health.getStatus()).isEqualTo(Status.UP); + assertThat(health.getDetails().size()).isEqualTo(0); } @Test public void status() throws Exception { Health health = Health.status(Status.UP).build(); - assertThat(health.getStatus(), equalTo(Status.UP)); - assertThat(health.getDetails().size(), equalTo(0)); + assertThat(health.getStatus()).isEqualTo(Status.UP); + assertThat(health.getDetails().size()).isEqualTo(0); } } diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/JmsHealthIndicatorTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/JmsHealthIndicatorTests.java index b10a1eb8cb..5be69b8a9b 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/JmsHealthIndicatorTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/JmsHealthIndicatorTests.java @@ -23,7 +23,7 @@ import javax.jms.JMSException; import org.junit.Test; -import static org.junit.Assert.assertEquals; +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; @@ -46,8 +46,8 @@ public class JmsHealthIndicatorTests { given(connectionFactory.createConnection()).willReturn(connection); JmsHealthIndicator indicator = new JmsHealthIndicator(connectionFactory); Health health = indicator.health(); - assertEquals(Status.UP, health.getStatus()); - assertEquals("JMS test provider", health.getDetails().get("provider")); + assertThat(health.getStatus()).isEqualTo(Status.UP); + assertThat(health.getDetails().get("provider")).isEqualTo("JMS test provider"); verify(connection, times(1)).close(); } @@ -58,8 +58,8 @@ public class JmsHealthIndicatorTests { .willThrow(new JMSException("test", "123")); JmsHealthIndicator indicator = new JmsHealthIndicator(connectionFactory); Health health = indicator.health(); - assertEquals(Status.DOWN, health.getStatus()); - assertEquals(null, health.getDetails().get("provider")); + assertThat(health.getStatus()).isEqualTo(Status.DOWN); + assertThat(health.getDetails().get("provider")).isNull(); } @Test @@ -73,8 +73,8 @@ public class JmsHealthIndicatorTests { given(connectionFactory.createConnection()).willReturn(connection); JmsHealthIndicator indicator = new JmsHealthIndicator(connectionFactory); Health health = indicator.health(); - assertEquals(Status.DOWN, health.getStatus()); - assertEquals(null, health.getDetails().get("provider")); + assertThat(health.getStatus()).isEqualTo(Status.DOWN); + assertThat(health.getDetails().get("provider")).isNull(); verify(connection, times(1)).close(); } diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/MailHealthIndicatorTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/MailHealthIndicatorTests.java index 6383289605..a0ba3f7f35 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/MailHealthIndicatorTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/MailHealthIndicatorTests.java @@ -32,9 +32,7 @@ import org.junit.Test; import org.springframework.mail.javamail.JavaMailSenderImpl; -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; import static org.mockito.BDDMockito.given; import static org.mockito.BDDMockito.willThrow; import static org.mockito.Mockito.mock; @@ -67,8 +65,8 @@ public class MailHealthIndicatorTests { public void smtpIsUp() { given(this.mailSender.getProtocol()).willReturn("success"); Health health = this.indicator.health(); - assertEquals(Status.UP, health.getStatus()); - assertEquals("smtp.acme.org:25", health.getDetails().get("location")); + assertThat(health.getStatus()).isEqualTo(Status.UP); + assertThat(health.getDetails().get("location")).isEqualTo("smtp.acme.org:25"); } @Test @@ -76,11 +74,11 @@ public class MailHealthIndicatorTests { willThrow(new MessagingException("A test exception")).given(this.mailSender) .testConnection(); Health health = this.indicator.health(); - assertEquals(Status.DOWN, health.getStatus()); - assertEquals("smtp.acme.org:25", health.getDetails().get("location")); + assertThat(health.getStatus()).isEqualTo(Status.DOWN); + assertThat(health.getDetails().get("location")).isEqualTo("smtp.acme.org:25"); Object errorMessage = health.getDetails().get("error"); - assertNotNull(errorMessage); - assertTrue(errorMessage.toString().contains("A test exception")); + assertThat(errorMessage).isNotNull(); + assertThat(errorMessage.toString().contains("A test exception")).isTrue(); } public static class SuccessTransport extends Transport { diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/MongoHealthIndicatorTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/MongoHealthIndicatorTests.java index a02af1e467..95893a52b9 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/MongoHealthIndicatorTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/MongoHealthIndicatorTests.java @@ -29,9 +29,7 @@ import org.springframework.boot.autoconfigure.mongo.MongoAutoConfiguration; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.data.mongodb.core.MongoTemplate; -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; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; @@ -58,10 +56,11 @@ public class MongoHealthIndicatorTests { PropertyPlaceholderAutoConfiguration.class, MongoAutoConfiguration.class, MongoDataAutoConfiguration.class, EndpointAutoConfiguration.class, HealthIndicatorAutoConfiguration.class); - assertEquals(1, this.context.getBeanNamesForType(MongoTemplate.class).length); + assertThat(this.context.getBeanNamesForType(MongoTemplate.class).length) + .isEqualTo(1); MongoHealthIndicator healthIndicator = this.context .getBean(MongoHealthIndicator.class); - assertNotNull(healthIndicator); + assertThat(healthIndicator).isNotNull(); } @Test @@ -71,11 +70,9 @@ public class MongoHealthIndicatorTests { MongoTemplate mongoTemplate = mock(MongoTemplate.class); given(mongoTemplate.executeCommand("{ buildInfo: 1 }")).willReturn(commandResult); MongoHealthIndicator healthIndicator = new MongoHealthIndicator(mongoTemplate); - Health health = healthIndicator.health(); - assertEquals(Status.UP, health.getStatus()); - assertEquals("2.6.4", health.getDetails().get("version")); - + assertThat(health.getStatus()).isEqualTo(Status.UP); + assertThat(health.getDetails().get("version")).isEqualTo("2.6.4"); verify(commandResult).getString("version"); verify(mongoTemplate).executeCommand("{ buildInfo: 1 }"); } @@ -86,12 +83,11 @@ public class MongoHealthIndicatorTests { given(mongoTemplate.executeCommand("{ buildInfo: 1 }")) .willThrow(new MongoException("Connection failed")); MongoHealthIndicator healthIndicator = new MongoHealthIndicator(mongoTemplate); - Health health = healthIndicator.health(); - assertEquals(Status.DOWN, health.getStatus()); - assertTrue(((String) health.getDetails().get("error")) + assertThat(health.getStatus()).isEqualTo(Status.DOWN); + assertThat(((String) health.getDetails().get("error")) .contains("Connection failed")); - verify(mongoTemplate).executeCommand("{ buildInfo: 1 }"); } + } diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/OrderedHealthAggregatorTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/OrderedHealthAggregatorTests.java index a2185250ac..f950a93a80 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/OrderedHealthAggregatorTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/OrderedHealthAggregatorTests.java @@ -23,7 +23,7 @@ import java.util.Map; import org.junit.Before; import org.junit.Test; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link OrderedHealthAggregator}. @@ -46,7 +46,8 @@ public class OrderedHealthAggregatorTests { healths.put("h2", new Health.Builder().status(Status.UP).build()); healths.put("h3", new Health.Builder().status(Status.UNKNOWN).build()); healths.put("h4", new Health.Builder().status(Status.OUT_OF_SERVICE).build()); - assertEquals(Status.DOWN, this.healthAggregator.aggregate(healths).getStatus()); + assertThat(this.healthAggregator.aggregate(healths).getStatus()) + .isEqualTo(Status.DOWN); } @Test @@ -58,8 +59,8 @@ public class OrderedHealthAggregatorTests { healths.put("h2", new Health.Builder().status(Status.UP).build()); healths.put("h3", new Health.Builder().status(Status.UNKNOWN).build()); healths.put("h4", new Health.Builder().status(Status.OUT_OF_SERVICE).build()); - assertEquals(Status.UNKNOWN, - this.healthAggregator.aggregate(healths).getStatus()); + assertThat(this.healthAggregator.aggregate(healths).getStatus()) + .isEqualTo(Status.UNKNOWN); } @Test @@ -70,7 +71,8 @@ public class OrderedHealthAggregatorTests { healths.put("h3", new Health.Builder().status(Status.UNKNOWN).build()); healths.put("h4", new Health.Builder().status(Status.OUT_OF_SERVICE).build()); healths.put("h5", new Health.Builder().status(new Status("CUSTOM")).build()); - assertEquals(Status.DOWN, this.healthAggregator.aggregate(healths).getStatus()); + assertThat(this.healthAggregator.aggregate(healths).getStatus()) + .isEqualTo(Status.DOWN); } @Test @@ -83,7 +85,8 @@ public class OrderedHealthAggregatorTests { healths.put("h3", new Health.Builder().status(Status.UNKNOWN).build()); healths.put("h4", new Health.Builder().status(Status.OUT_OF_SERVICE).build()); healths.put("h5", new Health.Builder().status(new Status("CUSTOM")).build()); - assertEquals(Status.DOWN, this.healthAggregator.aggregate(healths).getStatus()); + assertThat(this.healthAggregator.aggregate(healths).getStatus()) + .isEqualTo(Status.DOWN); } } diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/RabbitHealthIndicatorTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/RabbitHealthIndicatorTests.java index 30727b10c4..9b9f3c71c3 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/RabbitHealthIndicatorTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/RabbitHealthIndicatorTests.java @@ -26,8 +26,7 @@ import org.springframework.boot.autoconfigure.PropertyPlaceholderAutoConfigurati import org.springframework.boot.autoconfigure.amqp.RabbitAutoConfiguration; import org.springframework.context.annotation.AnnotationConfigApplicationContext; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link RabbitHealthIndicator}. @@ -50,10 +49,11 @@ public class RabbitHealthIndicatorTests { this.context = new AnnotationConfigApplicationContext( PropertyPlaceholderAutoConfiguration.class, RabbitAutoConfiguration.class, EndpointAutoConfiguration.class, HealthIndicatorAutoConfiguration.class); - assertEquals(1, this.context.getBeanNamesForType(RabbitAdmin.class).length); + assertThat(this.context.getBeanNamesForType(RabbitAdmin.class).length) + .isEqualTo(1); RabbitHealthIndicator healthIndicator = this.context .getBean(RabbitHealthIndicator.class); - assertNotNull(healthIndicator); + assertThat(healthIndicator).isNotNull(); } } diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/RedisHealthIndicatorTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/RedisHealthIndicatorTests.java index e20367ded2..e48c080226 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/RedisHealthIndicatorTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/RedisHealthIndicatorTests.java @@ -30,9 +30,7 @@ import org.springframework.data.redis.RedisConnectionFailureException; import org.springframework.data.redis.connection.RedisConnection; import org.springframework.data.redis.connection.RedisConnectionFactory; -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; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; @@ -58,18 +56,17 @@ public class RedisHealthIndicatorTests { this.context = new AnnotationConfigApplicationContext( PropertyPlaceholderAutoConfiguration.class, RedisAutoConfiguration.class, EndpointAutoConfiguration.class, HealthIndicatorAutoConfiguration.class); - assertEquals(1, - this.context.getBeanNamesForType(RedisConnectionFactory.class).length); + assertThat(this.context.getBeanNamesForType(RedisConnectionFactory.class)) + .hasSize(1); RedisHealthIndicator healthIndicator = this.context .getBean(RedisHealthIndicator.class); - assertNotNull(healthIndicator); + assertThat(healthIndicator).isNotNull(); } @Test public void redisIsUp() throws Exception { Properties info = new Properties(); info.put("redis_version", "2.8.9"); - RedisConnection redisConnection = mock(RedisConnection.class); RedisConnectionFactory redisConnectionFactory = mock( RedisConnectionFactory.class); @@ -77,11 +74,9 @@ public class RedisHealthIndicatorTests { given(redisConnection.info()).willReturn(info); RedisHealthIndicator healthIndicator = new RedisHealthIndicator( redisConnectionFactory); - Health health = healthIndicator.health(); - assertEquals(Status.UP, health.getStatus()); - assertEquals("2.8.9", health.getDetails().get("version")); - + assertThat(health.getStatus()).isEqualTo(Status.UP); + assertThat(health.getDetails().get("version")).isEqualTo("2.8.9"); verify(redisConnectionFactory).getConnection(); verify(redisConnection).info(); } @@ -96,13 +91,12 @@ public class RedisHealthIndicatorTests { .willThrow(new RedisConnectionFailureException("Connection failed")); RedisHealthIndicator healthIndicator = new RedisHealthIndicator( redisConnectionFactory); - Health health = healthIndicator.health(); - assertEquals(Status.DOWN, health.getStatus()); - assertTrue(((String) health.getDetails().get("error")) + assertThat(health.getStatus()).isEqualTo(Status.DOWN); + assertThat(((String) health.getDetails().get("error")) .contains("Connection failed")); - verify(redisConnectionFactory).getConnection(); verify(redisConnection).info(); } + } diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/SolrHealthIndicatorTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/SolrHealthIndicatorTests.java index 14ccbcb41b..4ffc295dbe 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/SolrHealthIndicatorTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/SolrHealthIndicatorTests.java @@ -30,9 +30,7 @@ import org.springframework.boot.autoconfigure.PropertyPlaceholderAutoConfigurati import org.springframework.boot.autoconfigure.solr.SolrAutoConfiguration; import org.springframework.context.annotation.AnnotationConfigApplicationContext; -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; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; @@ -57,10 +55,11 @@ public class SolrHealthIndicatorTests { this.context = new AnnotationConfigApplicationContext( PropertyPlaceholderAutoConfiguration.class, SolrAutoConfiguration.class, EndpointAutoConfiguration.class, HealthIndicatorAutoConfiguration.class); - assertEquals(1, this.context.getBeanNamesForType(SolrServer.class).length); + assertThat(this.context.getBeanNamesForType(SolrServer.class).length) + .isEqualTo(1); SolrHealthIndicator healthIndicator = this.context .getBean(SolrHealthIndicator.class); - assertNotNull(healthIndicator); + assertThat(healthIndicator).isNotNull(); } @Test @@ -71,22 +70,21 @@ public class SolrHealthIndicatorTests { response.add("status", "OK"); pingResponse.setResponse(response); given(solrServer.ping()).willReturn(pingResponse); - SolrHealthIndicator healthIndicator = new SolrHealthIndicator(solrServer); Health health = healthIndicator.health(); - assertEquals(Status.UP, health.getStatus()); - assertEquals("OK", health.getDetails().get("solrStatus")); + assertThat(health.getStatus()).isEqualTo(Status.UP); + assertThat(health.getDetails().get("solrStatus")).isEqualTo("OK"); } @Test public void solrIsDown() throws Exception { SolrServer solrServer = mock(SolrServer.class); given(solrServer.ping()).willThrow(new IOException("Connection failed")); - SolrHealthIndicator healthIndicator = new SolrHealthIndicator(solrServer); Health health = healthIndicator.health(); - assertEquals(Status.DOWN, health.getStatus()); - assertTrue(((String) health.getDetails().get("error")) + assertThat(health.getStatus()).isEqualTo(Status.DOWN); + assertThat(((String) health.getDetails().get("error")) .contains("Connection failed")); } + } diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/aggregate/AggregateMetricReaderTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/aggregate/AggregateMetricReaderTests.java index 2d2311746d..92e84e3c66 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/aggregate/AggregateMetricReaderTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/aggregate/AggregateMetricReaderTests.java @@ -24,8 +24,7 @@ import org.springframework.boot.actuate.metrics.Metric; import org.springframework.boot.actuate.metrics.repository.InMemoryMetricRepository; import org.springframework.boot.actuate.metrics.writer.Delta; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link AggregateMetricReader}. @@ -41,20 +40,21 @@ public class AggregateMetricReaderTests { @Test public void writeAndReadDefaults() { this.source.set(new Metric("foo.bar.spam", 2.3)); - assertEquals(2.3, this.reader.findOne("aggregate.spam").getValue()); + assertThat(this.reader.findOne("aggregate.spam").getValue()).isEqualTo(2.3); } @Test public void defaultKeyPattern() { this.source.set(new Metric("foo.bar.spam.bucket.wham", 2.3)); - assertEquals(2.3, this.reader.findOne("aggregate.spam.bucket.wham").getValue()); + assertThat(this.reader.findOne("aggregate.spam.bucket.wham").getValue()) + .isEqualTo(2.3); } @Test public void addKeyPattern() { this.source.set(new Metric("foo.bar.spam.bucket.wham", 2.3)); this.reader.setKeyPattern("d.d.k.d"); - assertEquals(2.3, this.reader.findOne("aggregate.spam.wham").getValue()); + assertThat(this.reader.findOne("aggregate.spam.wham").getValue()).isEqualTo(2.3); } @Test @@ -63,42 +63,43 @@ public class AggregateMetricReaderTests { this.source.set(new Metric("off.bar.spam.bucket.wham", 2.4)); this.reader.setPrefix("www"); this.reader.setKeyPattern("k.d.k.d"); - assertEquals(2.3, this.reader.findOne("www.foo.spam.wham").getValue()); - assertEquals(2, this.reader.count()); + assertThat(this.reader.findOne("www.foo.spam.wham").getValue()).isEqualTo(2.3); + assertThat(this.reader.count()).isEqualTo(2); } @Test public void writeAndReadExtraLong() { this.source.set(new Metric("blee.foo.bar.spam", 2.3)); this.reader.setKeyPattern("d.d.d.k"); - assertEquals(2.3, this.reader.findOne("aggregate.spam").getValue()); + assertThat(this.reader.findOne("aggregate.spam").getValue()).isEqualTo(2.3); } @Test public void writeAndReadLatestValue() { this.source.set(new Metric("foo.bar.spam", 2.3, new Date(100L))); this.source.set(new Metric("oof.rab.spam", 2.4, new Date(0L))); - assertEquals(2.3, this.reader.findOne("aggregate.spam").getValue()); + assertThat(this.reader.findOne("aggregate.spam").getValue()).isEqualTo(2.3); } @Test public void onlyPrefixed() { this.source.set(new Metric("foo.bar.spam", 2.3)); - assertNull(this.reader.findOne("spam")); + assertThat(this.reader.findOne("spam")).isNull(); } @Test public void incrementCounter() { this.source.increment(new Delta("foo.bar.counter.spam", 2L)); this.source.increment(new Delta("oof.rab.counter.spam", 3L)); - assertEquals(5L, this.reader.findOne("aggregate.counter.spam").getValue()); + assertThat(this.reader.findOne("aggregate.counter.spam").getValue()) + .isEqualTo(5L); } @Test public void countGauges() { this.source.set(new Metric("foo.bar.spam", 2.3)); this.source.set(new Metric("oof.rab.spam", 2.4)); - assertEquals(1, this.reader.count()); + assertThat(this.reader.count()).isEqualTo(1); } @Test @@ -107,7 +108,7 @@ public class AggregateMetricReaderTests { this.source.set(new Metric("oof.rab.spam", 2.4)); this.source.increment(new Delta("foo.bar.counter.spam", 2L)); this.source.increment(new Delta("oof.rab.counter.spam", 3L)); - assertEquals(2, this.reader.count()); + assertThat(this.reader.count()).isEqualTo(2); } } diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/buffer/BufferGaugeServiceSpeedTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/buffer/BufferGaugeServiceSpeedTests.java index e30c879196..bb01907559 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/buffer/BufferGaugeServiceSpeedTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/buffer/BufferGaugeServiceSpeedTests.java @@ -42,7 +42,7 @@ import org.springframework.boot.actuate.metrics.Metric; import org.springframework.lang.UsesJava8; import org.springframework.util.StopWatch; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * Speed tests for {@link BufferGaugeService}. @@ -117,7 +117,7 @@ public class BufferGaugeServiceSpeedTests { }); watch.stop(); System.err.println("Read(" + count + ")=" + watch.getLastTaskTimeMillis() + "ms"); - assertTrue(number * threadCount < total.longValue()); + assertThat(number * threadCount < total.longValue()).isTrue(); } @Theory @@ -141,7 +141,7 @@ public class BufferGaugeServiceSpeedTests { }); watch.stop(); System.err.println("Read(" + count + ")=" + watch.getLastTaskTimeMillis() + "ms"); - assertTrue(0 < total.longValue()); + assertThat(0 < total.longValue()).isTrue(); } private void iterate(String taskName) throws Exception { diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/buffer/BufferMetricReaderTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/buffer/BufferMetricReaderTests.java index d20a1e946a..65093e2de7 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/buffer/BufferMetricReaderTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/buffer/BufferMetricReaderTests.java @@ -18,8 +18,7 @@ package org.springframework.boot.actuate.metrics.buffer; import org.junit.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link BufferMetricReader}. @@ -39,21 +38,21 @@ public class BufferMetricReaderTests { public void countReflectsNumberOfMetrics() { this.gauges.set("foo", 1); this.counters.increment("bar", 2); - assertEquals(2, this.reader.count()); + assertThat(this.reader.count()).isEqualTo(2); } @Test public void findGauge() { this.gauges.set("foo", 1); - assertNotNull(this.reader.findOne("foo")); - assertEquals(1, this.reader.count()); + assertThat(this.reader.findOne("foo")).isNotNull(); + assertThat(this.reader.count()).isEqualTo(1); } @Test public void findCounter() { this.counters.increment("foo", 1); - assertNotNull(this.reader.findOne("foo")); - assertEquals(1, this.reader.count()); + assertThat(this.reader.findOne("foo")).isNotNull(); + assertThat(this.reader.count()).isEqualTo(1); } } diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/buffer/CounterBuffersTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/buffer/CounterBuffersTests.java index afc65e445d..323c8e4880 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/buffer/CounterBuffersTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/buffer/CounterBuffersTests.java @@ -20,8 +20,7 @@ import java.util.function.Consumer; import org.junit.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link CounterBuffers}. @@ -43,7 +42,7 @@ public class CounterBuffersTests { CounterBuffersTests.this.value = buffer.getValue(); } }); - assertEquals(2, this.value); + assertThat(this.value).isEqualTo(2); } @Test @@ -54,12 +53,12 @@ public class CounterBuffersTests { CounterBuffersTests.this.value = buffer.getValue(); } }); - assertEquals(0, this.value); + assertThat(this.value).isEqualTo(0); } @Test public void findNonExistent() { - assertNull(this.buffers.find("foo")); + assertThat(this.buffers.find("foo")).isNull(); } } diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/buffer/CounterServiceSpeedTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/buffer/CounterServiceSpeedTests.java index f7bd7b6344..0efd1810d1 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/buffer/CounterServiceSpeedTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/buffer/CounterServiceSpeedTests.java @@ -41,7 +41,7 @@ import org.springframework.boot.actuate.metrics.Metric; import org.springframework.lang.UsesJava8; import org.springframework.util.StopWatch; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * Speed tests for {@link CounterService}. @@ -116,7 +116,7 @@ public class CounterServiceSpeedTests { }); watch.stop(); System.err.println("Read(" + count + ")=" + watch.getLastTaskTimeMillis() + "ms"); - assertEquals(number * threadCount, total.longValue()); + assertThat(total.longValue()).isEqualTo(number * threadCount); } @Theory @@ -140,7 +140,7 @@ public class CounterServiceSpeedTests { }); watch.stop(); System.err.println("Read(" + count + ")=" + watch.getLastTaskTimeMillis() + "ms"); - assertEquals(number * threadCount, total.longValue()); + assertThat(total.longValue()).isEqualTo(number * threadCount); } private void iterate(String taskName) throws Exception { diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/buffer/DefaultCounterServiceSpeedTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/buffer/DefaultCounterServiceSpeedTests.java index 60e8947750..0b3362a337 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/buffer/DefaultCounterServiceSpeedTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/buffer/DefaultCounterServiceSpeedTests.java @@ -41,7 +41,7 @@ import org.springframework.boot.actuate.metrics.writer.DefaultCounterService; import org.springframework.lang.UsesJava8; import org.springframework.util.StopWatch; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * Speed tests for {@link DefaultCounterService}. @@ -124,7 +124,7 @@ public class DefaultCounterServiceSpeedTests { }); watch.stop(); System.err.println("Read(" + count + ")=" + watch.getLastTaskTimeMillis() + "ms"); - assertEquals(number * threadCount, total.longValue()); + assertThat(total.longValue()).isEqualTo(number * threadCount); } } diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/buffer/DefaultGaugeServiceSpeedTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/buffer/DefaultGaugeServiceSpeedTests.java index bd84d21f7d..2615372a2d 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/buffer/DefaultGaugeServiceSpeedTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/buffer/DefaultGaugeServiceSpeedTests.java @@ -41,7 +41,7 @@ import org.springframework.boot.actuate.metrics.writer.DefaultGaugeService; import org.springframework.lang.UsesJava8; import org.springframework.util.StopWatch; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * Speed tests for {@link DefaultGaugeService}. @@ -125,7 +125,7 @@ public class DefaultGaugeServiceSpeedTests { }); watch.stop(); System.err.println("Read(" + count + ")=" + watch.getLastTaskTimeMillis() + "ms"); - assertTrue(0 < total.longValue()); + assertThat(0 < total.longValue()).isTrue(); } } diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/buffer/DropwizardCounterServiceSpeedTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/buffer/DropwizardCounterServiceSpeedTests.java index 95e5490253..f5c2ea73bb 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/buffer/DropwizardCounterServiceSpeedTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/buffer/DropwizardCounterServiceSpeedTests.java @@ -42,7 +42,7 @@ import org.springframework.boot.actuate.metrics.reader.MetricRegistryMetricReade import org.springframework.lang.UsesJava8; import org.springframework.util.StopWatch; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * Speeds tests for {@link DropwizardMetricServices DropwizardMetricServices'} @@ -127,7 +127,7 @@ public class DropwizardCounterServiceSpeedTests { }); watch.stop(); System.err.println("Read(" + count + ")=" + watch.getLastTaskTimeMillis() + "ms"); - assertEquals(number * threadCount, total.longValue()); + assertThat(total.longValue()).isEqualTo(number * threadCount); } } diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/dropwizard/DropwizardMetricServicesTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/dropwizard/DropwizardMetricServicesTests.java index 530ad69412..a82773f9ed 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/dropwizard/DropwizardMetricServicesTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/dropwizard/DropwizardMetricServicesTests.java @@ -23,8 +23,7 @@ import com.codahale.metrics.Gauge; import com.codahale.metrics.MetricRegistry; import org.junit.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link DropwizardMetricServices}. @@ -42,7 +41,7 @@ public class DropwizardMetricServicesTests { this.writer.increment("foo"); this.writer.increment("foo"); this.writer.increment("foo"); - assertEquals(3, this.registry.counter("counter.foo").getCount()); + assertThat(this.registry.counter("counter.foo").getCount()).isEqualTo(3); } @Test @@ -50,7 +49,7 @@ public class DropwizardMetricServicesTests { this.writer.increment("meter.foo"); this.writer.increment("meter.foo"); this.writer.increment("meter.foo"); - assertEquals(3, this.registry.meter("meter.foo").getCount()); + assertThat(this.registry.meter("meter.foo").getCount()).isEqualTo(3); } @Test @@ -58,7 +57,7 @@ public class DropwizardMetricServicesTests { this.writer.increment("counter.foo"); this.writer.increment("counter.foo"); this.writer.increment("counter.foo"); - assertEquals(3, this.registry.counter("counter.foo").getCount()); + assertThat(this.registry.counter("counter.foo").getCount()).isEqualTo(3); } @Test @@ -66,23 +65,23 @@ public class DropwizardMetricServicesTests { this.writer.submit("foo", 2.1); @SuppressWarnings("unchecked") Gauge gauge = (Gauge) this.registry.getMetrics().get("gauge.foo"); - assertEquals(new Double(2.1), gauge.getValue()); + assertThat(gauge.getValue()).isEqualTo(new Double(2.1)); this.writer.submit("foo", 2.3); - assertEquals(new Double(2.3), gauge.getValue()); + assertThat(gauge.getValue()).isEqualTo(new Double(2.3)); } @Test public void setPredefinedTimer() { this.writer.submit("timer.foo", 200); this.writer.submit("timer.foo", 300); - assertEquals(2, this.registry.timer("timer.foo").getCount()); + assertThat(this.registry.timer("timer.foo").getCount()).isEqualTo(2); } @Test public void setPredefinedHistogram() { this.writer.submit("histogram.foo", 2.1); this.writer.submit("histogram.foo", 2.3); - assertEquals(2, this.registry.histogram("histogram.foo").getCount()); + assertThat(this.registry.histogram("histogram.foo").getCount()).isEqualTo(2); } /** @@ -108,7 +107,8 @@ public class DropwizardMetricServicesTests { } for (WriterThread thread : threads) { - assertFalse("expected thread caused unexpected exception", thread.isFailed()); + assertThat(thread.isFailed()) + .as("expected thread caused unexpected exception").isFalse(); } } diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/export/MetricCopyExporterTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/export/MetricCopyExporterTests.java index 1dc4d01b91..948f7f8743 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/export/MetricCopyExporterTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/export/MetricCopyExporterTests.java @@ -25,7 +25,7 @@ import org.springframework.boot.actuate.metrics.repository.InMemoryMetricReposit import org.springframework.boot.actuate.metrics.writer.Delta; import org.springframework.boot.actuate.metrics.writer.GaugeWriter; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link MetricCopyExporter}. @@ -45,18 +45,18 @@ public class MetricCopyExporterTests { public void export() { this.reader.set(new Metric("foo", 2.3)); this.exporter.export(); - assertEquals(1, this.writer.count()); + assertThat(this.writer.count()).isEqualTo(1); } @Test public void counter() { this.reader.increment(new Delta("counter.foo", 2)); this.exporter.export(); - assertEquals(1, this.writer.count()); + assertThat(this.writer.count()).isEqualTo(1); this.reader.increment(new Delta("counter.foo", 3)); this.exporter.export(); this.exporter.flush(); - assertEquals(5L, this.writer.findOne("counter.foo").getValue()); + assertThat(this.writer.findOne("counter.foo").getValue()).isEqualTo(5L); } @Test @@ -68,7 +68,7 @@ public class MetricCopyExporterTests { this.reader.increment(new Delta("counter.foo", 3)); exporter.export(); exporter.flush(); - assertEquals(5L, writer.getValue().getValue()); + assertThat(writer.getValue().getValue()).isEqualTo(5L); } @Test @@ -76,7 +76,7 @@ public class MetricCopyExporterTests { this.exporter.setIncludes("*"); this.reader.set(new Metric("foo", 2.3)); this.exporter.export(); - assertEquals(1, this.writer.count()); + assertThat(this.writer.count()).isEqualTo(1); } @Test @@ -86,7 +86,7 @@ public class MetricCopyExporterTests { this.reader.set(new Metric("foo", 2.3)); this.reader.set(new Metric("bar", 2.4)); this.exporter.export(); - assertEquals(1, this.writer.count()); + assertThat(this.writer.count()).isEqualTo(1); } @Test @@ -95,7 +95,7 @@ public class MetricCopyExporterTests { this.reader.set(new Metric("foo", 2.3)); this.reader.set(new Metric("bar", 2.4)); this.exporter.export(); - assertEquals(1, this.writer.count()); + assertThat(this.writer.count()).isEqualTo(1); } @Test @@ -103,7 +103,7 @@ public class MetricCopyExporterTests { this.reader.set(new Metric("foo", 2.3)); this.exporter.setEarliestTimestamp(new Date(System.currentTimeMillis() + 10000)); this.exporter.export(); - assertEquals(0, this.writer.count()); + assertThat(this.writer.count()).isEqualTo(0); } @Test @@ -112,7 +112,7 @@ public class MetricCopyExporterTests { this.exporter.setIgnoreTimestamps(true); this.exporter.setEarliestTimestamp(new Date(System.currentTimeMillis() + 10000)); this.exporter.export(); - assertEquals(1, this.writer.count()); + assertThat(this.writer.count()).isEqualTo(1); } private static class SimpleGaugeWriter implements GaugeWriter { diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/export/MetricExportersTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/export/MetricExportersTests.java index 311f706b85..fa3198e1eb 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/export/MetricExportersTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/export/MetricExportersTests.java @@ -28,8 +28,7 @@ import org.springframework.boot.actuate.metrics.writer.GaugeWriter; import org.springframework.boot.actuate.metrics.writer.MetricWriter; import org.springframework.scheduling.config.ScheduledTaskRegistrar; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link MetricExporters}. @@ -54,8 +53,8 @@ public class MetricExportersTests { this.exporters.setReader(this.reader); this.exporters.setWriters(this.writers); this.exporters.configureTasks(new ScheduledTaskRegistrar()); - assertNotNull(this.exporters.getExporters()); - assertEquals(0, this.exporters.getExporters().size()); + assertThat(this.exporters.getExporters()).isNotNull(); + assertThat(this.exporters.getExporters()).isEmpty(); } @Test @@ -66,8 +65,8 @@ public class MetricExportersTests { this.exporters.setReader(this.reader); this.exporters.setWriters(this.writers); this.exporters.configureTasks(new ScheduledTaskRegistrar()); - assertNotNull(this.exporters.getExporters()); - assertEquals(1, this.exporters.getExporters().size()); + assertThat(this.exporters.getExporters()).isNotNull(); + assertThat(this.exporters.getExporters()).hasSize(1); } @Test @@ -77,8 +76,8 @@ public class MetricExportersTests { this.exporters.setExporters(Collections.singletonMap("foo", new MetricCopyExporter(this.reader, this.writer))); this.exporters.configureTasks(new ScheduledTaskRegistrar()); - assertNotNull(this.exporters.getExporters()); - assertEquals(1, this.exporters.getExporters().size()); + assertThat(this.exporters.getExporters()).isNotNull(); + assertThat(this.exporters.getExporters()).hasSize(1); } } diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/export/PrefixMetricGroupExporterTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/export/PrefixMetricGroupExporterTests.java index d7ec890989..04fd1987bf 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/export/PrefixMetricGroupExporterTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/export/PrefixMetricGroupExporterTests.java @@ -25,7 +25,7 @@ import org.springframework.boot.actuate.metrics.Iterables; import org.springframework.boot.actuate.metrics.Metric; import org.springframework.boot.actuate.metrics.repository.InMemoryMetricRepository; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link PrefixMetricGroupExporter}. @@ -47,7 +47,7 @@ public class PrefixMetricGroupExporterTests { this.reader.set(new Metric("foo.spam", 1.3)); this.exporter.setGroups(Collections.singleton("foo")); this.exporter.export(); - assertEquals(1, Iterables.collection(this.writer.groups()).size()); + assertThat(Iterables.collection(this.writer.groups())).hasSize(1); } @Test @@ -56,7 +56,7 @@ public class PrefixMetricGroupExporterTests { this.reader.set(new Metric("foo.spam", 1.3)); this.exporter.setGroups(Collections.singleton("bar")); this.exporter.export(); - assertEquals(0, Iterables.collection(this.writer.groups()).size()); + assertThat(Iterables.collection(this.writer.groups())).isEmpty(); } @Test @@ -64,8 +64,8 @@ public class PrefixMetricGroupExporterTests { this.reader.set("foo", Arrays.>asList(new Metric("bar", 2.3), new Metric("spam", 1.3))); this.exporter.export(); - assertEquals(1, this.writer.countGroups()); - assertEquals(2, Iterables.collection(this.writer.findAll("foo")).size()); + assertThat(this.writer.countGroups()).isEqualTo(1); + assertThat(Iterables.collection(this.writer.findAll("foo"))).hasSize(2); } @Test @@ -75,7 +75,7 @@ public class PrefixMetricGroupExporterTests { this.reader.set(new Metric("foobar.spam", 1.3)); this.exporter.setGroups(Collections.singleton("foo")); this.exporter.export(); - assertEquals(1, Iterables.collection(this.writer.groups()).size()); + assertThat(Iterables.collection(this.writer.groups())).hasSize(1); } } diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/export/RichGaugeExporterTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/export/RichGaugeExporterTests.java index 122b71c050..0d48071f93 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/export/RichGaugeExporterTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/export/RichGaugeExporterTests.java @@ -23,7 +23,7 @@ import org.springframework.boot.actuate.metrics.Metric; import org.springframework.boot.actuate.metrics.repository.InMemoryMetricRepository; import org.springframework.boot.actuate.metrics.rich.InMemoryRichGaugeRepository; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link RichGaugeExporter}. @@ -43,7 +43,7 @@ public class RichGaugeExporterTests { public void prefixedMetricsCopied() { this.reader.set(new Metric("foo", 2.3)); this.exporter.export(); - assertEquals(1, Iterables.collection(this.writer.groups()).size()); + assertThat(Iterables.collection(this.writer.groups())).hasSize(1); } } diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/integration/SpringIntegrationMetricReaderTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/integration/SpringIntegrationMetricReaderTests.java index 146c358759..6b4dea5e08 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/integration/SpringIntegrationMetricReaderTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/integration/SpringIntegrationMetricReaderTests.java @@ -32,7 +32,7 @@ import org.springframework.integration.monitor.IntegrationMBeanExporter; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link SpringIntegrationMetricReader}. @@ -50,7 +50,7 @@ public class SpringIntegrationMetricReaderTests { @Test public void test() { - assertTrue(this.reader.count() > 0); + assertThat(this.reader.count() > 0).isTrue(); } @Configuration diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/jmx/DefaultMetricNamingStrategyTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/jmx/DefaultMetricNamingStrategyTests.java index 20f0151627..f5564fc2df 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/jmx/DefaultMetricNamingStrategyTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/jmx/DefaultMetricNamingStrategyTests.java @@ -20,7 +20,7 @@ import javax.management.ObjectName; import org.junit.Test; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link DefaultMetricNamingStrategy}. @@ -35,37 +35,37 @@ public class DefaultMetricNamingStrategyTests { public void simpleName() throws Exception { ObjectName name = this.strategy.getObjectName(null, "domain:type=MetricValue,name=foo"); - assertEquals("domain", name.getDomain()); - assertEquals("foo", name.getKeyProperty("type")); + assertThat(name.getDomain()).isEqualTo("domain"); + assertThat(name.getKeyProperty("type")).isEqualTo("foo"); } @Test public void onePeriod() throws Exception { ObjectName name = this.strategy.getObjectName(null, "domain:type=MetricValue,name=foo.bar"); - assertEquals("domain", name.getDomain()); - assertEquals("foo", name.getKeyProperty("type")); - assertEquals("Wrong name: " + name, "bar", name.getKeyProperty("value")); + assertThat(name.getDomain()).isEqualTo("domain"); + assertThat(name.getKeyProperty("type")).isEqualTo("foo"); + assertThat(name.getKeyProperty("value")).isEqualTo("bar"); } @Test public void twoPeriods() throws Exception { ObjectName name = this.strategy.getObjectName(null, "domain:type=MetricValue,name=foo.bar.spam"); - assertEquals("domain", name.getDomain()); - assertEquals("foo", name.getKeyProperty("type")); - assertEquals("Wrong name: " + name, "bar", name.getKeyProperty("name")); - assertEquals("Wrong name: " + name, "spam", name.getKeyProperty("value")); + assertThat(name.getDomain()).isEqualTo("domain"); + assertThat(name.getKeyProperty("type")).isEqualTo("foo"); + assertThat(name.getKeyProperty("name")).isEqualTo("bar"); + assertThat(name.getKeyProperty("value")).isEqualTo("spam"); } @Test public void threePeriods() throws Exception { ObjectName name = this.strategy.getObjectName(null, "domain:type=MetricValue,name=foo.bar.spam.bucket"); - assertEquals("domain", name.getDomain()); - assertEquals("foo", name.getKeyProperty("type")); - assertEquals("Wrong name: " + name, "bar", name.getKeyProperty("name")); - assertEquals("Wrong name: " + name, "spam.bucket", name.getKeyProperty("value")); + assertThat(name.getDomain()).isEqualTo("domain"); + assertThat(name.getKeyProperty("type")).isEqualTo("foo"); + assertThat(name.getKeyProperty("name")).isEqualTo("bar"); + assertThat(name.getKeyProperty("value")).isEqualTo("spam.bucket"); } } diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/reader/MetricRegistryMetricReaderTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/reader/MetricRegistryMetricReaderTests.java index 077549d98c..4617dea14f 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/reader/MetricRegistryMetricReaderTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/reader/MetricRegistryMetricReaderTests.java @@ -25,10 +25,7 @@ import org.junit.Test; import org.springframework.boot.actuate.metrics.Metric; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.nullValue; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link MetricRegistryMetricReader}. @@ -52,9 +49,9 @@ public class MetricRegistryMetricReaderTests { } }); - assertThat(this.metricReader.findOne("test"), is(nullValue())); + assertThat(this.metricReader.findOne("test")).isNull(); this.metricRegistry.remove("test"); - assertThat(this.metricReader.findOne("test"), is(nullValue())); + assertThat(this.metricReader.findOne("test")).isNull(); } @Test @@ -69,9 +66,9 @@ public class MetricRegistryMetricReaderTests { }); Metric metric = (Metric) this.metricReader.findOne("test"); - assertThat(metric.getValue(), equalTo(Integer.valueOf(5))); + assertThat(metric.getValue()).isEqualTo(Integer.valueOf(5)); this.metricRegistry.remove("test"); - assertThat(this.metricReader.findOne("test"), is(nullValue())); + assertThat(this.metricReader.findOne("test")).isNull(); } } diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/repository/InMemoryMetricRepositoryTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/repository/InMemoryMetricRepositoryTests.java index 4748f6ad35..9f07ab81a8 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/repository/InMemoryMetricRepositoryTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/repository/InMemoryMetricRepositoryTests.java @@ -23,7 +23,8 @@ import org.junit.Test; import org.springframework.boot.actuate.metrics.Metric; import org.springframework.boot.actuate.metrics.writer.Delta; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.offset; /** * Tests for {@link InMemoryMetricRepository}. @@ -35,13 +36,15 @@ public class InMemoryMetricRepositoryTests { @Test public void increment() { this.repository.increment(new Delta("foo", 1, new Date())); - assertEquals(1.0, this.repository.findOne("foo").getValue().doubleValue(), 0.01); + assertThat(this.repository.findOne("foo").getValue().doubleValue()).isEqualTo(1.0, + offset(0.01)); } @Test public void set() { this.repository.set(new Metric("foo", 2.5, new Date())); - assertEquals(2.5, this.repository.findOne("foo").getValue().doubleValue(), 0.01); + assertThat(this.repository.findOne("foo").getValue().doubleValue()).isEqualTo(2.5, + offset(0.01)); } } diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/repository/InMemoryPrefixMetricRepositoryTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/repository/InMemoryPrefixMetricRepositoryTests.java index 21e861cd45..29881f7c5c 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/repository/InMemoryPrefixMetricRepositoryTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/repository/InMemoryPrefixMetricRepositoryTests.java @@ -24,8 +24,7 @@ import org.junit.Test; import org.springframework.boot.actuate.metrics.Metric; import org.springframework.boot.actuate.metrics.writer.Delta; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Dave Syer @@ -43,8 +42,8 @@ public class InMemoryPrefixMetricRepositoryTests { for (Metric metric : this.repository.findAll("foo")) { names.add(metric.getName()); } - assertEquals(2, names.size()); - assertTrue(names.contains("foo.bar")); + assertThat(names).hasSize(2); + assertThat(names.contains("foo.bar")).isTrue(); } @Test @@ -54,8 +53,8 @@ public class InMemoryPrefixMetricRepositoryTests { for (Metric metric : this.repository.findAll("foo.*")) { names.add(metric.getName()); } - assertEquals(1, names.size()); - assertTrue(names.contains("foo.bar")); + assertThat(names).hasSize(1); + assertThat(names.contains("foo.bar")).isTrue(); } @Test @@ -65,8 +64,8 @@ public class InMemoryPrefixMetricRepositoryTests { for (Metric metric : this.repository.findAll("foo.")) { names.add(metric.getName()); } - assertEquals(1, names.size()); - assertTrue(names.contains("foo.bar")); + assertThat(names).hasSize(1); + assertThat(names.contains("foo.bar")).isTrue(); } @Test @@ -77,8 +76,8 @@ public class InMemoryPrefixMetricRepositoryTests { for (Metric metric : this.repository.findAll("foo")) { names.add(metric.getName()); } - assertEquals(1, names.size()); - assertTrue(names.contains("foo.bar")); + assertThat(names).hasSize(1); + assertThat(names.contains("foo.bar")).isTrue(); } @Test @@ -90,9 +89,9 @@ public class InMemoryPrefixMetricRepositoryTests { for (Metric metric : this.repository.findAll("foo")) { names.add(metric.getName()); } - assertEquals(2, names.size()); - assertTrue(names.contains("foo.bar")); - assertEquals(3L, this.repository.findOne("foo.bar").getValue()); + assertThat(names).hasSize(2); + assertThat(names.contains("foo.bar")).isTrue(); + assertThat(this.repository.findOne("foo.bar").getValue()).isEqualTo(3L); } } diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/repository/redis/RedisMetricRepositoryTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/repository/redis/RedisMetricRepositoryTests.java index 3a21cfe525..0db12ce2d9 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/repository/redis/RedisMetricRepositoryTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/repository/redis/RedisMetricRepositoryTests.java @@ -27,9 +27,8 @@ import org.springframework.boot.actuate.metrics.writer.Delta; import org.springframework.boot.redis.RedisTestServer; import org.springframework.data.redis.core.StringRedisTemplate; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.offset; /** * Tests for {@link RedisMetricRepository}. @@ -54,26 +53,26 @@ public class RedisMetricRepositoryTests { @After public void clear() { - assertNotNull(new StringRedisTemplate(this.redis.getConnectionFactory()) - .opsForValue().get(this.prefix + ".foo")); + assertThat(new StringRedisTemplate(this.redis.getConnectionFactory()) + .opsForValue().get(this.prefix + ".foo")).isNotNull(); this.repository.reset("foo"); this.repository.reset("bar"); - assertNull(new StringRedisTemplate(this.redis.getConnectionFactory()) - .opsForValue().get(this.prefix + ".foo")); + assertThat(new StringRedisTemplate(this.redis.getConnectionFactory()) + .opsForValue().get(this.prefix + ".foo")).isNull(); } @Test public void setAndGet() { this.repository.set(new Metric("foo", 12.3)); Metric metric = this.repository.findOne("foo"); - assertEquals("foo", metric.getName()); - assertEquals(12.3, metric.getValue().doubleValue(), 0.01); + assertThat(metric.getName()).isEqualTo("foo"); + assertThat(metric.getValue().doubleValue()).isEqualTo(12.3, offset(0.01)); } @Test public void incrementAndGet() { this.repository.increment(new Delta("foo", 3L)); - assertEquals(3, this.repository.findOne("foo").getValue().longValue()); + assertThat(this.repository.findOne("foo").getValue().longValue()).isEqualTo(3); } @Test @@ -81,29 +80,29 @@ public class RedisMetricRepositoryTests { this.repository.set(new Metric("foo", 12.3)); this.repository.increment(new Delta("foo", 3L)); Metric metric = this.repository.findOne("foo"); - assertEquals("foo", metric.getName()); - assertEquals(15.3, metric.getValue().doubleValue(), 0.01); + assertThat(metric.getName()).isEqualTo("foo"); + assertThat(metric.getValue().doubleValue()).isEqualTo(15.3, offset(0.01)); } @Test public void findAll() { this.repository.increment(new Delta("foo", 3L)); this.repository.set(new Metric("bar", 12.3)); - assertEquals(2, Iterables.collection(this.repository.findAll()).size()); + assertThat(Iterables.collection(this.repository.findAll())).hasSize(2); } @Test public void findOneWithAll() { this.repository.increment(new Delta("foo", 3L)); Metric metric = this.repository.findAll().iterator().next(); - assertEquals("foo", metric.getName()); + assertThat(metric.getName()).isEqualTo("foo"); } @Test public void count() { this.repository.increment(new Delta("foo", 3L)); this.repository.set(new Metric("bar", 12.3)); - assertEquals(2, this.repository.count()); + assertThat(this.repository.count()).isEqualTo(2); } } diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/repository/redis/RedisMultiMetricRepositoryTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/repository/redis/RedisMultiMetricRepositoryTests.java index 5a93a8275a..a5d156accc 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/repository/redis/RedisMultiMetricRepositoryTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/repository/redis/RedisMultiMetricRepositoryTests.java @@ -37,9 +37,7 @@ import org.springframework.boot.actuate.metrics.writer.Delta; import org.springframework.boot.redis.RedisTestServer; import org.springframework.data.redis.core.StringRedisTemplate; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link RedisMultiMetricRepository}. @@ -77,14 +75,14 @@ public class RedisMultiMetricRepositoryTests { @After public void clear() { - assertTrue(new StringRedisTemplate(this.redis.getConnectionFactory()).opsForZSet() - .size("keys." + this.prefix) > 0); + assertThat(new StringRedisTemplate(this.redis.getConnectionFactory()).opsForZSet() + .size("keys." + this.prefix)).isGreaterThan(0); this.repository.reset("foo"); this.repository.reset("bar"); - assertNull(new StringRedisTemplate(this.redis.getConnectionFactory()) - .opsForValue().get(this.prefix + ".foo")); - assertNull(new StringRedisTemplate(this.redis.getConnectionFactory()) - .opsForValue().get(this.prefix + ".bar")); + assertThat(new StringRedisTemplate(this.redis.getConnectionFactory()) + .opsForValue().get(this.prefix + ".foo")).isNull(); + assertThat(new StringRedisTemplate(this.redis.getConnectionFactory()) + .opsForValue().get(this.prefix + ".bar")).isNull(); } @Test @@ -93,8 +91,8 @@ public class RedisMultiMetricRepositoryTests { Arrays.>asList(new Metric("foo.bar", 12.3))); this.repository.set("foo", Arrays.>asList(new Metric("foo.bar", 15.3))); - assertEquals(15.3, Iterables.collection(this.repository.findAll("foo")).iterator() - .next().getValue()); + assertThat(Iterables.collection(this.repository.findAll("foo")).iterator().next() + .getValue()).isEqualTo(15.3); } @Test @@ -102,7 +100,7 @@ public class RedisMultiMetricRepositoryTests { this.repository.set("foo", Arrays.>asList(new Metric("foo.val", 12.3), new Metric("foo.bar", 11.3))); - assertEquals(2, Iterables.collection(this.repository.findAll("foo")).size()); + assertThat(Iterables.collection(this.repository.findAll("foo"))).hasSize(2); } @Test @@ -114,8 +112,7 @@ public class RedisMultiMetricRepositoryTests { Arrays.>asList(new Metric("bar.val", 12.3), new Metric("bar.foo", 11.3))); Collection groups = Iterables.collection(this.repository.groups()); - assertEquals(2, groups.size()); - assertTrue("Wrong groups: " + groups, groups.contains("foo")); + assertThat(groups).hasSize(2).contains("foo"); } @Test @@ -126,7 +123,7 @@ public class RedisMultiMetricRepositoryTests { this.repository.set("bar", Arrays.>asList(new Metric("bar.val", 12.3), new Metric("bar.foo", 11.3))); - assertEquals(2, this.repository.countGroups()); + assertThat(this.repository.countGroups()).isEqualTo(2); } @Test @@ -142,9 +139,8 @@ public class RedisMultiMetricRepositoryTests { bar = metric; } } - assertEquals(2, names.size()); - assertTrue("Wrong names: " + names, names.contains("foo.bar")); - assertEquals(3d, bar.getValue()); + assertThat(names).hasSize(2).contains("foo.bar"); + assertThat(bar.getValue()).isEqualTo(3d); } } diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/rich/InMemoryRichGaugeRepositoryTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/rich/InMemoryRichGaugeRepositoryTests.java index 32171323be..a3f93837d5 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/rich/InMemoryRichGaugeRepositoryTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/rich/InMemoryRichGaugeRepositoryTests.java @@ -20,7 +20,8 @@ import org.junit.Test; import org.springframework.boot.actuate.metrics.Metric; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.offset; /** * @author Dave Syer @@ -33,8 +34,8 @@ public class InMemoryRichGaugeRepositoryTests { public void writeAndRead() { this.repository.set(new Metric("foo", 1d)); this.repository.set(new Metric("foo", 2d)); - assertEquals(2L, this.repository.findOne("foo").getCount()); - assertEquals(2d, this.repository.findOne("foo").getValue(), 0.01); + assertThat(this.repository.findOne("foo").getCount()).isEqualTo(2L); + assertThat(this.repository.findOne("foo").getValue()).isEqualTo(2d, offset(0.01)); } } diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/rich/MultiMetricRichGaugeReaderTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/rich/MultiMetricRichGaugeReaderTests.java index 24f9928551..d27af496f5 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/rich/MultiMetricRichGaugeReaderTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/rich/MultiMetricRichGaugeReaderTests.java @@ -22,8 +22,7 @@ import org.springframework.boot.actuate.metrics.Metric; import org.springframework.boot.actuate.metrics.export.RichGaugeExporter; import org.springframework.boot.actuate.metrics.repository.InMemoryMetricRepository; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link MultiMetricRichGaugeReader}. @@ -45,11 +44,11 @@ public class MultiMetricRichGaugeReaderTests { this.data.set(new Metric("foo", 1)); this.exporter.export(); // Check the exporter worked - assertEquals(6, this.repository.count()); - assertEquals(1, this.reader.count()); + assertThat(this.repository.count()).isEqualTo(6); + assertThat(this.reader.count()).isEqualTo(1); RichGauge one = this.reader.findOne("foo"); - assertNotNull(one); - assertEquals(2, one.getCount()); + assertThat(one).isNotNull(); + assertThat(one.getCount()).isEqualTo(2); } @Test @@ -57,10 +56,10 @@ public class MultiMetricRichGaugeReaderTests { this.data.set(new Metric("foo", 1)); this.data.set(new Metric("bar", 1)); this.exporter.export(); - assertEquals(2, this.reader.count()); + assertThat(this.reader.count()).isEqualTo(2); RichGauge one = this.reader.findOne("foo"); - assertNotNull(one); - assertEquals(1, one.getCount()); + assertThat(one).isNotNull(); + assertThat(one.getCount()).isEqualTo(1); } } diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/statsd/StatsdMetricWriterTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/statsd/StatsdMetricWriterTests.java index 12362919cb..60e74b4f02 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/statsd/StatsdMetricWriterTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/statsd/StatsdMetricWriterTests.java @@ -30,7 +30,7 @@ import org.springframework.boot.actuate.metrics.Metric; import org.springframework.boot.actuate.metrics.writer.Delta; import org.springframework.util.SocketUtils; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link StatsdMetricWriter}. @@ -56,14 +56,14 @@ public class StatsdMetricWriterTests { public void increment() { this.writer.increment(new Delta("counter.foo", 3L)); this.server.waitForMessage(); - assertEquals("me.counter.foo:3|c", this.server.messagesReceived().get(0)); + assertThat(this.server.messagesReceived().get(0)).isEqualTo("me.counter.foo:3|c"); } @Test public void setLongMetric() throws Exception { this.writer.set(new Metric("gauge.foo", 3L)); this.server.waitForMessage(); - assertEquals("me.gauge.foo:3|g", this.server.messagesReceived().get(0)); + assertThat(this.server.messagesReceived().get(0)).isEqualTo("me.gauge.foo:3|g"); } @Test @@ -71,14 +71,14 @@ public class StatsdMetricWriterTests { this.writer.set(new Metric("gauge.foo", 3.7)); this.server.waitForMessage(); // Doubles are truncated - assertEquals("me.gauge.foo:3.7|g", this.server.messagesReceived().get(0)); + assertThat(this.server.messagesReceived().get(0)).isEqualTo("me.gauge.foo:3.7|g"); } @Test public void setTimerMetric() throws Exception { this.writer.set(new Metric("timer.foo", 37L)); this.server.waitForMessage(); - assertEquals("me.timer.foo:37|ms", this.server.messagesReceived().get(0)); + assertThat(this.server.messagesReceived().get(0)).isEqualTo("me.timer.foo:37|ms"); } @Test @@ -86,7 +86,7 @@ public class StatsdMetricWriterTests { this.writer = new StatsdMetricWriter("localhost", this.port); this.writer.set(new Metric("gauge.foo", 3L)); this.server.waitForMessage(); - assertEquals("gauge.foo:3|g", this.server.messagesReceived().get(0)); + assertThat(this.server.messagesReceived().get(0)).isEqualTo("gauge.foo:3|g"); } @Test @@ -94,10 +94,10 @@ public class StatsdMetricWriterTests { this.writer = new StatsdMetricWriter("my.", "localhost", this.port); this.writer.set(new Metric("gauge.foo", 3L)); this.server.waitForMessage(); - assertEquals("my.gauge.foo:3|g", this.server.messagesReceived().get(0)); + assertThat(this.server.messagesReceived().get(0)).isEqualTo("my.gauge.foo:3|g"); } - private static final class DummyStatsDServer { + private static final class DummyStatsDServer implements Runnable { private final List messagesReceived = new ArrayList(); @@ -107,31 +107,29 @@ public class StatsdMetricWriterTests { try { this.server = new DatagramSocket(port); } - catch (SocketException e) { - throw new IllegalStateException(e); + catch (SocketException ex) { + throw new IllegalStateException(ex); } - new Thread(new Runnable() { - @Override - public void run() { - try { - final DatagramPacket packet = new DatagramPacket(new byte[256], - 256); - DummyStatsDServer.this.server.receive(packet); - DummyStatsDServer.this.messagesReceived.add( - new String(packet.getData(), Charset.forName("UTF-8")) - .trim()); - } - catch (Exception e) { - // Ignore - } - } - }).start(); + new Thread(this).start(); } public void stop() { this.server.close(); } + @Override + public void run() { + try { + DatagramPacket packet = new DatagramPacket(new byte[256], 256); + this.server.receive(packet); + this.messagesReceived.add( + new String(packet.getData(), Charset.forName("UTF-8")).trim()); + } + catch (Exception ex) { + // Ignore + } + } + public void waitForMessage() { while (this.messagesReceived.isEmpty()) { try { diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/util/InMemoryRepositoryTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/util/SimpleInMemoryRepositoryTests.java old mode 100644 new mode 100755 similarity index 62% rename from spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/util/InMemoryRepositoryTests.java rename to spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/util/SimpleInMemoryRepositoryTests.java index c551356044..70c5c291e8 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/util/InMemoryRepositoryTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/util/SimpleInMemoryRepositoryTests.java @@ -29,21 +29,21 @@ import org.junit.Test; import org.springframework.boot.actuate.metrics.util.SimpleInMemoryRepository.Callback; -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 SimpleInMemoryRepository}. + * * @author Dave Syer */ -public class InMemoryRepositoryTests { +public class SimpleInMemoryRepositoryTests { private final SimpleInMemoryRepository repository = new SimpleInMemoryRepository(); @Test public void setAndGet() { this.repository.set("foo", "bar"); - assertEquals("bar", this.repository.findOne("foo")); + assertThat(this.repository.findOne("foo")).isEqualTo("bar"); } @Test @@ -55,7 +55,7 @@ public class InMemoryRepositoryTests { return "bar"; } }); - assertEquals("bar", this.repository.findOne("foo")); + assertThat(this.repository.findOne("foo")).isEqualTo("bar"); } @Test @@ -66,7 +66,7 @@ public class InMemoryRepositoryTests { return "bar"; } }); - assertEquals("bar", this.repository.findOne("foo")); + assertThat(this.repository.findOne("foo")).isEqualTo("bar"); } @Test @@ -75,59 +75,59 @@ public class InMemoryRepositoryTests { this.repository.set("foo.bar", "one"); this.repository.set("foo.min", "two"); this.repository.set("foo.max", "three"); - assertEquals(3, - ((Collection) this.repository.findAllWithPrefix("foo")).size()); + assertThat(((Collection) this.repository.findAllWithPrefix("foo"))).hasSize(3); } @Test public void patternsAcceptedForRegisteredPrefix() { this.repository.set("foo.bar", "spam"); Iterator iterator = this.repository.findAllWithPrefix("foo.*").iterator(); - assertEquals("spam", iterator.next()); - assertFalse(iterator.hasNext()); + assertThat(iterator.next()).isEqualTo("spam"); + assertThat(iterator.hasNext()).isFalse(); } @Test public void updateConcurrent() throws Exception { - final SimpleInMemoryRepository repository = new SimpleInMemoryRepository(); + SimpleInMemoryRepository repository = new SimpleInMemoryRepository(); Collection> tasks = new ArrayList>(); for (int i = 0; i < 1000; i++) { - tasks.add(new Callable() { - @Override - public Boolean call() throws Exception { - repository.update("foo", new Callback() { - @Override - public Integer modify(Integer current) { - if (current == null) { - return 1; - } - return current + 1; - } - }); - return true; - } - }); - tasks.add(new Callable() { - @Override - public Boolean call() throws Exception { - repository.update("foo", new Callback() { - @Override - public Integer modify(Integer current) { - if (current == null) { - return -1; - } - return current - 1; - } - }); - return true; - } - }); + tasks.add(new RepositoryUpdate(repository, 1)); + tasks.add(new RepositoryUpdate(repository, -1)); } List> all = Executors.newFixedThreadPool(10).invokeAll(tasks); for (Future future : all) { - assertTrue(future.get(1, TimeUnit.SECONDS)); + assertThat(future.get(1, TimeUnit.SECONDS)).isTrue(); } - assertEquals(Integer.valueOf(0), repository.findOne("foo")); + assertThat(repository.findOne("foo")).isEqualTo(0); + } + + private static class RepositoryUpdate implements Callable { + + private final SimpleInMemoryRepository repository; + + private final int delta; + + RepositoryUpdate(SimpleInMemoryRepository repository, int delta) { + this.repository = repository; + this.delta = delta; + } + + @Override + public Boolean call() throws Exception { + this.repository.update("foo", new Callback() { + + @Override + public Integer modify(Integer current) { + if (current == null) { + return RepositoryUpdate.this.delta; + } + return current + RepositoryUpdate.this.delta; + } + + }); + return true; + } + } } diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/writer/DefaultCounterServiceTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/writer/DefaultCounterServiceTests.java index b41f910d29..fdf4964d23 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/writer/DefaultCounterServiceTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/writer/DefaultCounterServiceTests.java @@ -22,12 +22,14 @@ import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.runners.MockitoJUnitRunner; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; /** * Tests for {@link DefaultCounterService}. + * + * @author Dave Syer */ @RunWith(MockitoJUnitRunner.class) public class DefaultCounterServiceTests { @@ -44,32 +46,32 @@ public class DefaultCounterServiceTests { public void incrementWithExistingCounter() { this.service.increment("counter.foo"); verify(this.repository).increment(this.captor.capture()); - assertEquals("counter.foo", this.captor.getValue().getName()); - assertEquals(1L, this.captor.getValue().getValue()); + assertThat(this.captor.getValue().getName()).isEqualTo("counter.foo"); + assertThat(this.captor.getValue().getValue()).isEqualTo(1L); } @Test public void incrementWithExistingNearCounter() { this.service.increment("counter-foo"); verify(this.repository).increment(this.captor.capture()); - assertEquals("counter.counter-foo", this.captor.getValue().getName()); - assertEquals(1L, this.captor.getValue().getValue()); + assertThat(this.captor.getValue().getName()).isEqualTo("counter.counter-foo"); + assertThat(this.captor.getValue().getValue()).isEqualTo(1L); } @Test public void incrementPrependsCounter() { this.service.increment("foo"); verify(this.repository).increment(this.captor.capture()); - assertEquals("counter.foo", this.captor.getValue().getName()); - assertEquals(1L, this.captor.getValue().getValue()); + assertThat(this.captor.getValue().getName()).isEqualTo("counter.foo"); + assertThat(this.captor.getValue().getValue()).isEqualTo(1L); } @Test public void decrementPrependsCounter() { this.service.decrement("foo"); verify(this.repository).increment(this.captor.capture()); - assertEquals("counter.foo", this.captor.getValue().getName()); - assertEquals(-1L, this.captor.getValue().getValue()); + assertThat(this.captor.getValue().getName()).isEqualTo("counter.foo"); + assertThat(this.captor.getValue().getValue()).isEqualTo(-1L); } @Test @@ -77,4 +79,5 @@ public class DefaultCounterServiceTests { this.service.reset("foo"); verify(this.repository).reset("counter.foo"); } + } diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/writer/DefaultGaugeServiceTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/writer/DefaultGaugeServiceTests.java index 0e6d150633..56b90d5bc1 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/writer/DefaultGaugeServiceTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/writer/DefaultGaugeServiceTests.java @@ -21,12 +21,14 @@ import org.mockito.ArgumentCaptor; import org.springframework.boot.actuate.metrics.Metric; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; /** * Tests for {@link DefaultGaugeService}. + * + * @author Dave Syer */ public class DefaultGaugeServiceTests { @@ -40,8 +42,8 @@ public class DefaultGaugeServiceTests { @SuppressWarnings("rawtypes") ArgumentCaptor captor = ArgumentCaptor.forClass(Metric.class); verify(this.repository).set(captor.capture()); - assertEquals("gauge.foo", captor.getValue().getName()); - assertEquals(2.3, captor.getValue().getValue()); + assertThat(captor.getValue().getName()).isEqualTo("gauge.foo"); + assertThat(captor.getValue().getValue()).isEqualTo(2.3); } } diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/security/AuthenticationAuditListenerTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/security/AuthenticationAuditListenerTests.java index c13cd3550e..4c77b85ce4 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/security/AuthenticationAuditListenerTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/security/AuthenticationAuditListenerTests.java @@ -32,8 +32,7 @@ import org.springframework.security.core.authority.AuthorityUtils; import org.springframework.security.core.userdetails.User; import org.springframework.security.web.authentication.switchuser.AuthenticationSwitchUserEvent; -import static org.hamcrest.Matchers.hasEntry; -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.mock; import static org.mockito.Mockito.never; @@ -97,8 +96,8 @@ public class AuthenticationAuditListenerTests { ArgumentCaptor auditApplicationEvent = ArgumentCaptor .forClass(AuditApplicationEvent.class); verify(this.publisher).publishEvent(auditApplicationEvent.capture()); - assertThat(auditApplicationEvent.getValue().getAuditEvent().getData(), - hasEntry("details", details)); + assertThat(auditApplicationEvent.getValue().getAuditEvent().getData()) + .containsEntry("details", details); } } diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/system/ApplicationPidFileWriterTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/system/ApplicationPidFileWriterTests.java index 496c9122a0..75f10e896c 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/system/ApplicationPidFileWriterTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/system/ApplicationPidFileWriterTests.java @@ -37,9 +37,7 @@ import org.springframework.core.env.StandardEnvironment; import org.springframework.mock.env.MockPropertySource; import org.springframework.util.FileCopyUtils; -import static org.hamcrest.Matchers.isEmptyString; -import static org.hamcrest.Matchers.not; -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; @@ -76,8 +74,8 @@ public class ApplicationPidFileWriterTests { File file = this.temporaryFolder.newFile(); ApplicationPidFileWriter listener = new ApplicationPidFileWriter(file); listener.onApplicationEvent(EVENT); - assertThat(FileCopyUtils.copyToString(new FileReader(file)), - not(isEmptyString())); + FileReader reader = new FileReader(file); + assertThat(FileCopyUtils.copyToString(reader)).isNotEmpty(); } @Test @@ -86,9 +84,8 @@ public class ApplicationPidFileWriterTests { System.setProperty("PIDFILE", this.temporaryFolder.newFile().getAbsolutePath()); ApplicationPidFileWriter listener = new ApplicationPidFileWriter(file); listener.onApplicationEvent(EVENT); - assertThat( - FileCopyUtils.copyToString(new FileReader(System.getProperty("PIDFILE"))), - not(isEmptyString())); + FileReader reader = new FileReader(System.getProperty("PIDFILE")); + assertThat(FileCopyUtils.copyToString(reader)).isNotEmpty(); } @Test @@ -98,8 +95,7 @@ public class ApplicationPidFileWriterTests { file.getAbsolutePath()); ApplicationPidFileWriter listener = new ApplicationPidFileWriter(); listener.onApplicationEvent(event); - assertThat(FileCopyUtils.copyToString(new FileReader(file)), - not(isEmptyString())); + assertThat(FileCopyUtils.copyToString(new FileReader(file))).isNotEmpty(); } @Test @@ -109,11 +105,10 @@ public class ApplicationPidFileWriterTests { file.getAbsolutePath()); ApplicationPidFileWriter listener = new ApplicationPidFileWriter(); listener.onApplicationEvent(event); - assertThat(FileCopyUtils.copyToString(new FileReader(file)), isEmptyString()); + assertThat(FileCopyUtils.copyToString(new FileReader(file))).isEmpty(); listener.setTriggerEventType(ApplicationEnvironmentPreparedEvent.class); listener.onApplicationEvent(event); - assertThat(FileCopyUtils.copyToString(new FileReader(file)), - not(isEmptyString())); + assertThat(FileCopyUtils.copyToString(new FileReader(file))).isNotEmpty(); } @Test @@ -123,8 +118,7 @@ public class ApplicationPidFileWriterTests { listener.setTriggerEventType(ApplicationStartedEvent.class); listener.onApplicationEvent( new ApplicationStartedEvent(new SpringApplication(), new String[] {})); - assertThat(FileCopyUtils.copyToString(new FileReader(file)), - not(isEmptyString())); + assertThat(FileCopyUtils.copyToString(new FileReader(file))).isNotEmpty(); } @Test @@ -133,7 +127,7 @@ public class ApplicationPidFileWriterTests { file.setReadOnly(); ApplicationPidFileWriter listener = new ApplicationPidFileWriter(file); listener.onApplicationEvent(EVENT); - assertThat(FileCopyUtils.copyToString(new FileReader(file)), isEmptyString()); + assertThat(FileCopyUtils.copyToString(new FileReader(file))).isEmpty(); } @Test diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/system/EmbeddedServerPortFileWriterTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/system/EmbeddedServerPortFileWriterTests.java index 5d5d540b0d..3c6ae972a9 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/system/EmbeddedServerPortFileWriterTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/system/EmbeddedServerPortFileWriterTests.java @@ -33,9 +33,7 @@ import org.springframework.boot.context.embedded.EmbeddedWebApplicationContext; import org.springframework.util.FileCopyUtils; import org.springframework.util.StringUtils; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.hasItem; -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; @@ -62,7 +60,7 @@ public class EmbeddedServerPortFileWriterTests { File file = this.temporaryFolder.newFile(); EmbeddedServerPortFileWriter listener = new EmbeddedServerPortFileWriter(file); listener.onApplicationEvent(mockEvent("", 8080)); - assertThat(FileCopyUtils.copyToString(new FileReader(file)), equalTo("8080")); + assertThat(FileCopyUtils.copyToString(new FileReader(file))).isEqualTo("8080"); } @Test @@ -70,8 +68,8 @@ public class EmbeddedServerPortFileWriterTests { System.setProperty("PORTFILE", this.temporaryFolder.newFile().getAbsolutePath()); EmbeddedServerPortFileWriter listener = new EmbeddedServerPortFileWriter(); listener.onApplicationEvent(mockEvent("", 8080)); - assertThat(FileCopyUtils.copyToString( - new FileReader(System.getProperty("PORTFILE"))), equalTo("8080")); + FileReader reader = new FileReader(System.getProperty("PORTFILE")); + assertThat(FileCopyUtils.copyToString(reader)).isEqualTo("8080"); } @Test @@ -80,8 +78,8 @@ public class EmbeddedServerPortFileWriterTests { System.setProperty("PORTFILE", this.temporaryFolder.newFile().getAbsolutePath()); EmbeddedServerPortFileWriter listener = new EmbeddedServerPortFileWriter(file); listener.onApplicationEvent(mockEvent("", 8080)); - assertThat(FileCopyUtils.copyToString( - new FileReader(System.getProperty("PORTFILE"))), equalTo("8080")); + FileReader reader = new FileReader(System.getProperty("PORTFILE")); + assertThat(FileCopyUtils.copyToString(reader)).isEqualTo("8080"); } @Test @@ -90,17 +88,16 @@ public class EmbeddedServerPortFileWriterTests { EmbeddedServerPortFileWriter listener = new EmbeddedServerPortFileWriter(file); listener.onApplicationEvent(mockEvent("", 8080)); listener.onApplicationEvent(mockEvent("management", 9090)); - assertThat(FileCopyUtils.copyToString(new FileReader(file)), equalTo("8080")); + assertThat(FileCopyUtils.copyToString(new FileReader(file))).isEqualTo("8080"); String managementFile = file.getName(); managementFile = managementFile.substring(0, managementFile.length() - StringUtils.getFilenameExtension(managementFile).length() - 1); managementFile = managementFile + "-management." + StringUtils.getFilenameExtension(file.getName()); - assertThat( - FileCopyUtils.copyToString( - new FileReader(new File(file.getParentFile(), managementFile))), - equalTo("9090")); - assertThat(collectFileNames(file.getParentFile()), hasItem(managementFile)); + FileReader reader = new FileReader( + new File(file.getParentFile(), managementFile)); + assertThat(FileCopyUtils.copyToString(reader)).isEqualTo("9090"); + assertThat(collectFileNames(file.getParentFile())).contains(managementFile); } @Test @@ -114,11 +111,10 @@ public class EmbeddedServerPortFileWriterTests { - StringUtils.getFilenameExtension(managementFile).length() - 1); managementFile = managementFile + "-MANAGEMENT." + StringUtils.getFilenameExtension(file.getName()); - assertThat( - FileCopyUtils.copyToString( - new FileReader(new File(file.getParentFile(), managementFile))), - equalTo("9090")); - assertThat(collectFileNames(file.getParentFile()), hasItem(managementFile)); + FileReader reader = new FileReader( + new File(file.getParentFile(), managementFile)); + assertThat(FileCopyUtils.copyToString(reader)).isEqualTo("9090"); + assertThat(collectFileNames(file.getParentFile())).contains(managementFile); } private EmbeddedServletContainerInitializedEvent mockEvent(String name, int port) { diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/trace/InMemoryTraceRepositoryTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/trace/InMemoryTraceRepositoryTests.java index 091fe9376e..0d2f8f5ab7 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/trace/InMemoryTraceRepositoryTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/trace/InMemoryTraceRepositoryTests.java @@ -21,7 +21,7 @@ import java.util.List; import org.junit.Test; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link InMemoryTraceRepository}. @@ -39,9 +39,9 @@ public class InMemoryTraceRepositoryTests { this.repository.add(Collections.singletonMap("bar", "foo")); this.repository.add(Collections.singletonMap("bar", "bar")); List traces = this.repository.findAll(); - assertEquals(2, traces.size()); - assertEquals("bar", traces.get(0).getInfo().get("bar")); - assertEquals("foo", traces.get(1).getInfo().get("bar")); + assertThat(traces).hasSize(2); + assertThat(traces.get(0).getInfo().get("bar")).isEqualTo("bar"); + assertThat(traces.get(1).getInfo().get("bar")).isEqualTo("foo"); } @Test @@ -52,9 +52,9 @@ public class InMemoryTraceRepositoryTests { this.repository.add(Collections.singletonMap("bar", "foo")); this.repository.add(Collections.singletonMap("bar", "bar")); List traces = this.repository.findAll(); - assertEquals(2, traces.size()); - assertEquals("bar", traces.get(1).getInfo().get("bar")); - assertEquals("foo", traces.get(0).getInfo().get("bar")); + assertThat(traces).hasSize(2); + assertThat(traces.get(1).getInfo().get("bar")).isEqualTo("bar"); + assertThat(traces.get(0).getInfo().get("bar")).isEqualTo("foo"); } } diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/trace/WebRequestTraceFilterTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/trace/WebRequestTraceFilterTests.java index c122f50c25..8a7c6b6764 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/trace/WebRequestTraceFilterTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/trace/WebRequestTraceFilterTests.java @@ -37,8 +37,7 @@ import org.springframework.boot.autoconfigure.web.DefaultErrorAttributes; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link WebRequestTraceFilter}. @@ -62,10 +61,10 @@ public class WebRequestTraceFilterTests { MockHttpServletRequest request = new MockHttpServletRequest("GET", "/foo"); request.addHeader("Accept", "application/json"); Map trace = this.filter.getTrace(request); - assertEquals("GET", trace.get("method")); - assertEquals("/foo", trace.get("path")); + assertThat(trace.get("method")).isEqualTo("GET"); + assertThat(trace.get("path")).isEqualTo("/foo"); Map map = (Map) trace.get("headers"); - assertEquals("{Accept=application/json}", map.get("request").toString()); + assertThat(map.get("request").toString()).isEqualTo("{Accept=application/json}"); } @Test @@ -110,22 +109,23 @@ public class WebRequestTraceFilterTests { } }); - assertEquals(1, this.repository.findAll().size()); + assertThat(this.repository.findAll()).hasSize(1); Map trace = this.repository.findAll().iterator().next().getInfo(); Map map = (Map) trace.get("headers"); - assertEquals("{Content-Type=application/json, status=200}", - map.get("response").toString()); - assertEquals("GET", trace.get("method")); - assertEquals("/foo", trace.get("path")); - assertEquals("paramvalue", - ((String[]) ((Map) trace.get("parameters")).get("param"))[0]); - assertEquals("some.remote.addr", trace.get("remoteAddress")); - assertEquals("some.query.string", trace.get("query")); - assertEquals(principal.getName(), trace.get("userPrincipal")); - assertEquals("some.context.path", trace.get("contextPath")); - assertEquals(url, trace.get("pathInfo")); - assertEquals("authType", trace.get("authType")); - assertEquals("{Accept=application/json}", map.get("request").toString()); + + assertThat(map.get("response").toString()) + .isEqualTo("{Content-Type=application/json, status=200}"); + assertThat(trace.get("method")).isEqualTo("GET"); + assertThat(trace.get("path")).isEqualTo("/foo"); + assertThat(((String[]) ((Map) trace.get("parameters")).get("param"))[0]) + .isEqualTo("paramvalue"); + assertThat(trace.get("remoteAddress")).isEqualTo("some.remote.addr"); + assertThat(trace.get("query")).isEqualTo("some.query.string"); + assertThat(trace.get("userPrincipal")).isEqualTo(principal.getName()); + assertThat(trace.get("contextPath")).isEqualTo("some.context.path"); + assertThat(trace.get("pathInfo")).isEqualTo(url); + assertThat(trace.get("authType")).isEqualTo("authType"); + assertThat(map.get("request").toString()).isEqualTo("{Accept=application/json}"); } @Test @@ -144,7 +144,7 @@ public class WebRequestTraceFilterTests { }); Map info = this.repository.findAll().iterator().next().getInfo(); Map headers = (Map) info.get("headers"); - assertTrue(headers.get("response") == null); + assertThat(headers.get("response") == null).isTrue(); } @Test @@ -158,7 +158,7 @@ public class WebRequestTraceFilterTests { @SuppressWarnings("unchecked") Map map = (Map) ((Map) trace .get("headers")).get("response"); - assertEquals("404", map.get("status").toString()); + assertThat(map.get("status").toString()).isEqualTo("404"); } @Test @@ -175,7 +175,7 @@ public class WebRequestTraceFilterTests { @SuppressWarnings("unchecked") Map map = (Map) trace.get("error"); System.err.println(map); - assertEquals("Foo", map.get("message").toString()); + assertThat(map.get("message").toString()).isEqualTo("Foo"); } } From 7f9358f4d89e44689f7578f7604f9509611cf7ae Mon Sep 17 00:00:00 2001 From: Phillip Webb Date: Sat, 6 Feb 2016 14:52:48 -0800 Subject: [PATCH 04/10] Use AssertJ in spring-boot-devtools See gh-5083 --- .../RemoteUrlPropertyExtractorTests.java | 17 +++--- .../DevToolsPropertiesTests.java | 17 +++--- .../LocalDevToolsAutoConfigurationTests.java | 43 +++++++-------- .../RemoteDevToolsAutoConfigurationTests.java | 15 +++--- .../autoconfigure/TriggerFileFilterTests.java | 7 ++- .../classpath/ClassPathChangedEventTests.java | 10 ++-- .../ClassPathFileChangeListenerTests.java | 7 ++- .../ClassPathFileSystemWatcherTests.java | 7 ++- .../PatternClassPathRestartStrategyTests.java | 6 +-- ...ToolsHomePropertiesPostProcessorTests.java | 8 ++- .../devtools/filewatch/ChangedFileTests.java | 9 ++-- .../devtools/filewatch/FileSnapshotTests.java | 14 +++-- .../filewatch/FileSystemWatcherTests.java | 43 +++++++-------- .../filewatch/FolderSnapshotTests.java | 22 ++++---- .../HttpTunnelIntegrationTests.java | 10 ++-- .../ConnectionInputStreamTests.java | 7 ++- .../ConnectionOutputStreamTests.java | 7 ++- .../boot/devtools/livereload/FrameTests.java | 49 +++++++++-------- .../livereload/LiveReloadServerTests.java | 19 +++---- .../client/ClassPathChangeUploaderTests.java | 15 +++--- .../client/DelayedLiveReloadTriggerTests.java | 5 +- .../client/HttpHeaderInterceptorTests.java | 7 ++- ...LocalDebugPortAvailableConditionTests.java | 11 ++-- .../RemoteClientConfigurationTests.java | 12 ++--- .../remote/server/DispatcherFilterTests.java | 7 ++- .../remote/server/DispatcherTests.java | 5 +- .../server/HttpHeaderAccessManagerTests.java | 11 ++-- .../remote/server/HttpStatusHandlerTests.java | 7 ++- .../remote/server/UrlHandlerMapperTests.java | 8 ++- .../devtools/restart/ChangeableUrlsTests.java | 11 ++-- .../DefaultRestartInitializerTests.java | 20 ++++--- .../devtools/restart/MainMethodTests.java | 9 ++-- .../OnInitializedRestarterConditionTests.java | 9 ++-- .../RestartApplicationListenerTests.java | 28 +++++----- .../restart/RestartScopeInitializerTests.java | 7 ++- .../boot/devtools/restart/RestarterTests.java | 26 +++++----- .../SilentExitExceptionHandlerTests.java | 8 ++- .../classloader/ClassLoaderFileTests.java | 16 +++--- .../classloader/ClassLoaderFilesTests.java | 52 ++++++++----------- .../classloader/RestartClassLoaderTests.java | 30 +++++------ .../DefaultSourceFolderUrlFilterTests.java | 12 ++--- .../server/HttpRestartServerTests.java | 12 ++--- .../restart/server/RestartServerTests.java | 12 ++--- .../settings/DevToolsSettingsTests.java | 28 +++++----- .../client/HttpTunnelConnectionTests.java | 14 +++-- .../tunnel/client/TunnelClientTests.java | 17 +++--- .../HttpTunnelPayloadForwarderTests.java | 7 ++- .../payload/HttpTunnelPayloadTests.java | 22 ++++---- .../tunnel/server/HttpTunnelServerTests.java | 43 ++++++++------- .../SocketTargetServerConnectionTests.java | 13 ++--- .../server/StaticPortProviderTests.java | 5 +- 51 files changed, 359 insertions(+), 447 deletions(-) mode change 100755 => 100644 spring-boot-devtools/src/test/java/org/springframework/boot/devtools/autoconfigure/LocalDevToolsAutoConfigurationTests.java mode change 100755 => 100644 spring-boot-devtools/src/test/java/org/springframework/boot/devtools/integrationtest/HttpTunnelIntegrationTests.java diff --git a/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/RemoteUrlPropertyExtractorTests.java b/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/RemoteUrlPropertyExtractorTests.java index c1781a29ca..bfbe8e62f0 100644 --- a/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/RemoteUrlPropertyExtractorTests.java +++ b/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/RemoteUrlPropertyExtractorTests.java @@ -27,10 +27,7 @@ import org.springframework.boot.SpringApplication; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.Configuration; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.nullValue; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link RemoteUrlPropertyExtractor}. @@ -73,17 +70,17 @@ public class RemoteUrlPropertyExtractorTests { @Test public void validUrl() throws Exception { ApplicationContext context = doTest("http://localhost:8080"); - assertThat(context.getEnvironment().getProperty("remoteUrl"), - equalTo("http://localhost:8080")); - assertThat(context.getEnvironment().getProperty("spring.thymeleaf.cache"), - is(nullValue())); + assertThat(context.getEnvironment().getProperty("remoteUrl")) + .isEqualTo("http://localhost:8080"); + assertThat(context.getEnvironment().getProperty("spring.thymeleaf.cache")) + .isNull(); } @Test public void cleanValidUrl() throws Exception { ApplicationContext context = doTest("http://localhost:8080/"); - assertThat(context.getEnvironment().getProperty("remoteUrl"), - equalTo("http://localhost:8080")); + assertThat(context.getEnvironment().getProperty("remoteUrl")) + .isEqualTo("http://localhost:8080"); } private ApplicationContext doTest(String... args) { diff --git a/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/autoconfigure/DevToolsPropertiesTests.java b/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/autoconfigure/DevToolsPropertiesTests.java index 888ca9dc70..8397af3675 100644 --- a/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/autoconfigure/DevToolsPropertiesTests.java +++ b/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/autoconfigure/DevToolsPropertiesTests.java @@ -18,8 +18,7 @@ package org.springframework.boot.devtools.autoconfigure; import org.junit.Test; -import static org.hamcrest.Matchers.arrayContaining; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link DevToolsProperties}. @@ -34,11 +33,10 @@ public class DevToolsPropertiesTests { public void additionalExcludeKeepsDefaults() { DevToolsProperties.Restart restart = this.devToolsProperties.getRestart(); restart.setAdditionalExclude("foo/**,bar/**"); - assertThat(restart.getAllExclude(), - arrayContaining("META-INF/maven/**", "META-INF/resources/**", - "resources/**", "static/**", "public/**", "templates/**", - "**/*Test.class", "**/*Tests.class", "git.properties", "foo/**", - "bar/**")); + assertThat(restart.getAllExclude()).containsOnly("META-INF/maven/**", + "META-INF/resources/**", "resources/**", "static/**", "public/**", + "templates/**", "**/*Test.class", "**/*Tests.class", "git.properties", + "foo/**", "bar/**"); } @Test @@ -46,7 +44,7 @@ public class DevToolsPropertiesTests { DevToolsProperties.Restart restart = this.devToolsProperties.getRestart(); restart.setExclude(""); restart.setAdditionalExclude("foo/**,bar/**"); - assertThat(restart.getAllExclude(), arrayContaining("foo/**", "bar/**")); + assertThat(restart.getAllExclude()).containsOnly("foo/**", "bar/**"); } @Test @@ -54,8 +52,7 @@ public class DevToolsPropertiesTests { DevToolsProperties.Restart restart = this.devToolsProperties.getRestart(); restart.setExclude("biz/**"); restart.setAdditionalExclude("foo/**,bar/**"); - assertThat(restart.getAllExclude(), - arrayContaining("biz/**", "foo/**", "bar/**")); + assertThat(restart.getAllExclude()).containsOnly("biz/**", "foo/**", "bar/**"); } } diff --git a/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/autoconfigure/LocalDevToolsAutoConfigurationTests.java b/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/autoconfigure/LocalDevToolsAutoConfigurationTests.java old mode 100755 new mode 100644 index 7f2c0ed9d5..c5d6555166 --- a/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/autoconfigure/LocalDevToolsAutoConfigurationTests.java +++ b/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/autoconfigure/LocalDevToolsAutoConfigurationTests.java @@ -51,12 +51,7 @@ import org.springframework.session.ExpiringSession; import org.springframework.test.util.ReflectionTestUtils; import org.springframework.util.SocketUtils; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.hasKey; -import static org.hamcrest.Matchers.instanceOf; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.notNullValue; -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.mock; import static org.mockito.Mockito.never; @@ -94,7 +89,7 @@ public class LocalDevToolsAutoConfigurationTests { this.context = initializeAndRun(Config.class); TemplateResolver resolver = this.context.getBean(TemplateResolver.class); resolver.initialize(); - assertThat(resolver.isCacheable(), equalTo(false)); + assertThat(resolver.isCacheable()).isFalse(); } @Test @@ -102,7 +97,7 @@ public class LocalDevToolsAutoConfigurationTests { this.context = initializeAndRun(Config.class, "--spring.thymeleaf.cache=true"); TemplateResolver resolver = this.context.getBean(TemplateResolver.class); resolver.initialize(); - assertThat(resolver.isCacheable(), equalTo(true)); + assertThat(resolver.isCacheable()).isTrue(); } @Test @@ -114,7 +109,7 @@ public class LocalDevToolsAutoConfigurationTests { this.context = initializeAndRun(Config.class); TemplateResolver resolver = this.context.getBean(TemplateResolver.class); resolver.initialize(); - assertThat(resolver.isCacheable(), equalTo(true)); + assertThat(resolver.isCacheable()).isTrue(); } finally { System.setProperty("user.home", userHome); @@ -125,14 +120,14 @@ public class LocalDevToolsAutoConfigurationTests { public void resourceCachePeriodIsZero() throws Exception { this.context = initializeAndRun(WebResourcesConfig.class); ResourceProperties properties = this.context.getBean(ResourceProperties.class); - assertThat(properties.getCachePeriod(), equalTo(0)); + assertThat(properties.getCachePeriod()).isEqualTo(0); } @Test public void liveReloadServer() throws Exception { this.context = initializeAndRun(Config.class); LiveReloadServer server = this.context.getBean(LiveReloadServer.class); - assertThat(server.isStarted(), equalTo(true)); + assertThat(server.isStarted()).isTrue(); } @Test @@ -198,7 +193,7 @@ public class LocalDevToolsAutoConfigurationTests { this.context = initializeAndRun(Config.class); ClassPathFileSystemWatcher watcher = this.context .getBean(ClassPathFileSystemWatcher.class); - assertThat(watcher, notNullValue()); + assertThat(watcher).isNotNull(); } @Test @@ -220,7 +215,7 @@ public class LocalDevToolsAutoConfigurationTests { Object watcher = ReflectionTestUtils.getField(classPathWatcher, "fileSystemWatcher"); Object filter = ReflectionTestUtils.getField(watcher, "triggerFilter"); - assertThat(filter, instanceOf(TriggerFileFilter.class)); + assertThat(filter).isInstanceOf(TriggerFileFilter.class); } @Test @@ -236,9 +231,9 @@ public class LocalDevToolsAutoConfigurationTests { @SuppressWarnings("unchecked") Map folders = (Map) ReflectionTestUtils .getField(watcher, "folders"); - assertThat(folders.size(), is(equalTo(2))); - assertThat(folders, hasKey(new File("src/main/java").getAbsoluteFile())); - assertThat(folders, hasKey(new File("src/test/java").getAbsoluteFile())); + assertThat(folders).hasSize(2) + .containsKey(new File("src/main/java").getAbsoluteFile()) + .containsKey(new File("src/test/java").getAbsoluteFile()); } @Test @@ -263,14 +258,14 @@ public class LocalDevToolsAutoConfigurationTests { this.context = application.run(); RedisTemplate redisTemplate = this.context.getBean("sessionRedisTemplate", RedisTemplate.class); - assertThat(redisTemplate.getHashKeySerializer(), - is(instanceOf(RestartCompatibleRedisSerializer.class))); - assertThat(redisTemplate.getHashValueSerializer(), - is(instanceOf(RestartCompatibleRedisSerializer.class))); - assertThat(redisTemplate.getKeySerializer(), - is(instanceOf(RestartCompatibleRedisSerializer.class))); - assertThat(redisTemplate.getValueSerializer(), - is(instanceOf(RestartCompatibleRedisSerializer.class))); + assertThat(redisTemplate.getHashKeySerializer()) + .isInstanceOf(RestartCompatibleRedisSerializer.class); + assertThat(redisTemplate.getHashValueSerializer()) + .isInstanceOf(RestartCompatibleRedisSerializer.class); + assertThat(redisTemplate.getKeySerializer()) + .isInstanceOf(RestartCompatibleRedisSerializer.class); + assertThat(redisTemplate.getValueSerializer()) + .isInstanceOf(RestartCompatibleRedisSerializer.class); } private ConfigurableApplicationContext initializeAndRun(Class config, diff --git a/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/autoconfigure/RemoteDevToolsAutoConfigurationTests.java b/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/autoconfigure/RemoteDevToolsAutoConfigurationTests.java index 42075ef632..3c18101839 100644 --- a/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/autoconfigure/RemoteDevToolsAutoConfigurationTests.java +++ b/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/autoconfigure/RemoteDevToolsAutoConfigurationTests.java @@ -47,8 +47,7 @@ import org.springframework.mock.web.MockHttpServletResponse; import org.springframework.mock.web.MockServletContext; import org.springframework.web.context.support.AnnotationConfigWebApplicationContext; -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; /** @@ -204,7 +203,7 @@ public class RemoteDevToolsAutoConfigurationTests { this.request.addHeader(DEFAULT_SECRET_HEADER_NAME, "supersecret"); this.response.setStatus(500); filter.doFilter(this.request, this.response, this.chain); - assertThat(this.response.getStatus(), equalTo(200)); + assertThat(this.response.getStatus()).isEqualTo(200); } @Test @@ -216,17 +215,17 @@ public class RemoteDevToolsAutoConfigurationTests { this.request.addHeader(DEFAULT_SECRET_HEADER_NAME, "supersecret"); this.response.setStatus(500); filter.doFilter(this.request, this.response, this.chain); - assertThat(this.response.getStatus(), equalTo(200)); + assertThat(this.response.getStatus()).isEqualTo(200); } private void assertTunnelInvoked(boolean value) { - assertThat(this.context.getBean(MockHttpTunnelServer.class).invoked, - equalTo(value)); + assertThat(this.context.getBean(MockHttpTunnelServer.class).invoked) + .isEqualTo(value); } private void assertRestartInvoked(boolean value) { - assertThat(this.context.getBean(MockHttpRestartServer.class).invoked, - equalTo(value)); + assertThat(this.context.getBean(MockHttpRestartServer.class).invoked) + .isEqualTo(value); } private void loadContext(String... properties) { diff --git a/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/autoconfigure/TriggerFileFilterTests.java b/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/autoconfigure/TriggerFileFilterTests.java index d2a604f19a..fab213ad53 100644 --- a/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/autoconfigure/TriggerFileFilterTests.java +++ b/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/autoconfigure/TriggerFileFilterTests.java @@ -23,8 +23,7 @@ import org.junit.Test; import org.junit.rules.ExpectedException; import org.junit.rules.TemporaryFolder; -import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link TriggerFileFilter}. @@ -49,13 +48,13 @@ public class TriggerFileFilterTests { @Test public void acceptNameMatch() throws Exception { File file = this.temp.newFile("thefile.txt"); - assertThat(new TriggerFileFilter("thefile.txt").accept(file), equalTo(true)); + assertThat(new TriggerFileFilter("thefile.txt").accept(file)).isTrue(); } @Test public void doesNotAcceptNameMismatch() throws Exception { File file = this.temp.newFile("notthefile.txt"); - assertThat(new TriggerFileFilter("thefile.txt").accept(file), equalTo(false)); + assertThat(new TriggerFileFilter("thefile.txt").accept(file)).isFalse(); } } diff --git a/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/classpath/ClassPathChangedEventTests.java b/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/classpath/ClassPathChangedEventTests.java index 45b0caa4e4..cac6b933d3 100644 --- a/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/classpath/ClassPathChangedEventTests.java +++ b/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/classpath/ClassPathChangedEventTests.java @@ -25,9 +25,7 @@ import org.junit.rules.ExpectedException; import org.springframework.boot.devtools.filewatch.ChangedFiles; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.sameInstance; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link ClassPathChangedEvent}. @@ -53,7 +51,7 @@ public class ClassPathChangedEventTests { Set changeSet = new LinkedHashSet(); ClassPathChangedEvent event = new ClassPathChangedEvent(this.source, changeSet, false); - assertThat(event.getChangeSet(), sameInstance(changeSet)); + assertThat(event.getChangeSet()).isSameAs(changeSet); } @Test @@ -61,9 +59,9 @@ public class ClassPathChangedEventTests { Set changeSet = new LinkedHashSet(); ClassPathChangedEvent event; event = new ClassPathChangedEvent(this.source, changeSet, false); - assertThat(event.isRestartRequired(), equalTo(false)); + assertThat(event.isRestartRequired()).isFalse(); event = new ClassPathChangedEvent(this.source, changeSet, true); - assertThat(event.isRestartRequired(), equalTo(true)); + assertThat(event.isRestartRequired()).isTrue(); } } diff --git a/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/classpath/ClassPathFileChangeListenerTests.java b/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/classpath/ClassPathFileChangeListenerTests.java index 1dcd4f0e02..128fcdcec8 100644 --- a/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/classpath/ClassPathFileChangeListenerTests.java +++ b/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/classpath/ClassPathFileChangeListenerTests.java @@ -36,8 +36,7 @@ import org.springframework.boot.devtools.filewatch.FileSystemWatcher; import org.springframework.context.ApplicationEvent; import org.springframework.context.ApplicationEventPublisher; -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.never; import static org.mockito.Mockito.verify; @@ -116,8 +115,8 @@ public class ClassPathFileChangeListenerTests { verify(this.eventPublisher).publishEvent(this.eventCaptor.capture()); ClassPathChangedEvent actualEvent = (ClassPathChangedEvent) this.eventCaptor .getValue(); - assertThat(actualEvent.getChangeSet(), equalTo(changeSet)); - assertThat(actualEvent.isRestartRequired(), equalTo(restart)); + assertThat(actualEvent.getChangeSet()).isEqualTo(changeSet); + assertThat(actualEvent.isRestartRequired()).isEqualTo(restart); } } diff --git a/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/classpath/ClassPathFileSystemWatcherTests.java b/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/classpath/ClassPathFileSystemWatcherTests.java index 5465f527bf..8147eaa5f5 100644 --- a/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/classpath/ClassPathFileSystemWatcherTests.java +++ b/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/classpath/ClassPathFileSystemWatcherTests.java @@ -40,8 +40,7 @@ import org.springframework.core.env.Environment; import org.springframework.core.env.MapPropertySource; import org.springframework.util.FileCopyUtils; -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; /** @@ -84,9 +83,9 @@ public class ClassPathFileSystemWatcherTests { FileCopyUtils.copy("file".getBytes(), classFile); Thread.sleep(1100); List events = context.getBean(Listener.class).getEvents(); - assertThat(events.size(), equalTo(1)); + assertThat(events.size()).isEqualTo(1); assertThat(events.get(0).getChangeSet().iterator().next().getFiles().iterator() - .next().getFile(), equalTo(classFile)); + .next().getFile()).isEqualTo(classFile); context.close(); } diff --git a/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/classpath/PatternClassPathRestartStrategyTests.java b/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/classpath/PatternClassPathRestartStrategyTests.java index ea6a76fcd8..6a0f74ab02 100644 --- a/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/classpath/PatternClassPathRestartStrategyTests.java +++ b/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/classpath/PatternClassPathRestartStrategyTests.java @@ -23,8 +23,7 @@ import org.junit.Test; import org.springframework.boot.devtools.filewatch.ChangedFile; import org.springframework.boot.devtools.filewatch.ChangedFile.Type; -import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link PatternClassPathRestartStrategy}. @@ -90,7 +89,8 @@ public class PatternClassPathRestartStrategyTests { private void assertRestartRequired(ClassPathRestartStrategy strategy, String relativeName, boolean expected) { - assertThat(strategy.isRestartRequired(mockFile(relativeName)), equalTo(expected)); + assertThat(strategy.isRestartRequired(mockFile(relativeName))) + .isEqualTo(expected); } private ChangedFile mockFile(String relativeName) { diff --git a/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/env/DevToolsHomePropertiesPostProcessorTests.java b/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/env/DevToolsHomePropertiesPostProcessorTests.java index b4d8b58f21..788f9afde3 100644 --- a/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/env/DevToolsHomePropertiesPostProcessorTests.java +++ b/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/env/DevToolsHomePropertiesPostProcessorTests.java @@ -30,9 +30,7 @@ import org.junit.rules.TemporaryFolder; import org.springframework.core.env.ConfigurableEnvironment; 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 DevToolsHomePropertiesPostProcessor}. @@ -63,7 +61,7 @@ public class DevToolsHomePropertiesPostProcessorTests { ConfigurableEnvironment environment = new MockEnvironment(); MockDevToolHomePropertiesPostProcessor postProcessor = new MockDevToolHomePropertiesPostProcessor(); postProcessor.postProcessEnvironment(environment, null); - assertThat(environment.getProperty("abc"), equalTo("def")); + assertThat(environment.getProperty("abc")).isEqualTo("def"); } @Test @@ -71,7 +69,7 @@ public class DevToolsHomePropertiesPostProcessorTests { ConfigurableEnvironment environment = new MockEnvironment(); MockDevToolHomePropertiesPostProcessor postProcessor = new MockDevToolHomePropertiesPostProcessor(); postProcessor.postProcessEnvironment(environment, null); - assertThat(environment.getProperty("abc"), nullValue()); + assertThat(environment.getProperty("abc")).isNull(); } private class MockDevToolHomePropertiesPostProcessor diff --git a/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/filewatch/ChangedFileTests.java b/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/filewatch/ChangedFileTests.java index 3b731f026a..9675cd7b70 100644 --- a/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/filewatch/ChangedFileTests.java +++ b/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/filewatch/ChangedFileTests.java @@ -25,8 +25,7 @@ import org.junit.rules.TemporaryFolder; import org.springframework.boot.devtools.filewatch.ChangedFile.Type; -import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link ChangedFile}. @@ -66,14 +65,14 @@ public class ChangedFileTests { public void getFile() throws Exception { File file = this.temp.newFile(); ChangedFile changedFile = new ChangedFile(this.temp.newFolder(), file, Type.ADD); - assertThat(changedFile.getFile(), equalTo(file)); + assertThat(changedFile.getFile()).isEqualTo(file); } @Test public void getType() throws Exception { ChangedFile changedFile = new ChangedFile(this.temp.newFolder(), this.temp.newFile(), Type.DELETE); - assertThat(changedFile.getType(), equalTo(Type.DELETE)); + assertThat(changedFile.getType()).isEqualTo(Type.DELETE); } @Test @@ -82,7 +81,7 @@ public class ChangedFileTests { File subFolder = new File(folder, "A"); File file = new File(subFolder, "B.txt"); ChangedFile changedFile = new ChangedFile(folder, file, Type.ADD); - assertThat(changedFile.getRelativeName(), equalTo("A/B.txt")); + assertThat(changedFile.getRelativeName()).isEqualTo("A/B.txt"); } } diff --git a/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/filewatch/FileSnapshotTests.java b/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/filewatch/FileSnapshotTests.java index 5725d0280a..15a7e4c4a0 100644 --- a/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/filewatch/FileSnapshotTests.java +++ b/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/filewatch/FileSnapshotTests.java @@ -28,9 +28,7 @@ import org.junit.rules.TemporaryFolder; import org.springframework.util.FileCopyUtils; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.not; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link FileSnapshot}. @@ -70,8 +68,8 @@ public class FileSnapshotTests { File fileCopy = new File(file, "x").getParentFile(); FileSnapshot snapshot1 = new FileSnapshot(file); FileSnapshot snapshot2 = new FileSnapshot(fileCopy); - assertThat(snapshot1, equalTo(snapshot2)); - assertThat(snapshot1.hashCode(), equalTo(snapshot2.hashCode())); + assertThat(snapshot1).isEqualTo(snapshot2); + assertThat(snapshot1.hashCode()).isEqualTo(snapshot2.hashCode()); } @Test @@ -79,7 +77,7 @@ public class FileSnapshotTests { File file = createNewFile("abc", MODIFIED); FileSnapshot snapshot1 = new FileSnapshot(file); file.delete(); - assertThat(snapshot1, not(equalTo(new FileSnapshot(file)))); + assertThat(snapshot1).isNotEqualTo(new FileSnapshot(file)); } @Test @@ -87,7 +85,7 @@ public class FileSnapshotTests { File file = createNewFile("abc", MODIFIED); FileSnapshot snapshot1 = new FileSnapshot(file); setupFile(file, "abcd", MODIFIED); - assertThat(snapshot1, not(equalTo(new FileSnapshot(file)))); + assertThat(snapshot1).isNotEqualTo(new FileSnapshot(file)); } @Test @@ -95,7 +93,7 @@ public class FileSnapshotTests { File file = createNewFile("abc", MODIFIED); FileSnapshot snapshot1 = new FileSnapshot(file); setupFile(file, "abc", MODIFIED + TWO_MINS); - assertThat(snapshot1, not(equalTo(new FileSnapshot(file)))); + assertThat(snapshot1).isNotEqualTo(new FileSnapshot(file)); } private File createNewFile(String content, long lastModified) throws IOException { diff --git a/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/filewatch/FileSystemWatcherTests.java b/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/filewatch/FileSystemWatcherTests.java index 5de4f54479..ccaa0439c1 100644 --- a/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/filewatch/FileSystemWatcherTests.java +++ b/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/filewatch/FileSystemWatcherTests.java @@ -22,7 +22,6 @@ import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.util.ArrayList; -import java.util.Arrays; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.List; @@ -37,11 +36,7 @@ import org.junit.rules.TemporaryFolder; import org.springframework.boot.devtools.filewatch.ChangedFile.Type; import org.springframework.util.FileCopyUtils; -import static org.hamcrest.Matchers.contains; -import static org.hamcrest.Matchers.equalTo; -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.Mockito.mock; /** @@ -112,7 +107,7 @@ public class FileSystemWatcherTests { @Test public void sourceFolderMustExist() throws Exception { File folder = new File("does/not/exist"); - assertThat(folder.exists(), is(false)); + assertThat(folder.exists()).isFalse(); this.thrown.expect(IllegalArgumentException.class); this.thrown.expectMessage( "Folder '" + folder + "' must exist and must be a directory"); @@ -122,7 +117,7 @@ public class FileSystemWatcherTests { @Test public void sourceFolderMustBeADirectory() throws Exception { File folder = new File("pom.xml"); - assertThat(folder.isFile(), is(true)); + assertThat(folder.isFile()).isTrue(); this.thrown.expect(IllegalArgumentException.class); this.thrown.expectMessage("Folder 'pom.xml' must exist and must be a directory"); this.watcher.addSourceFolder(new File("pom.xml")); @@ -143,7 +138,7 @@ public class FileSystemWatcherTests { this.watcher.stopAfter(1); ChangedFiles changedFiles = getSingleChangedFiles(); ChangedFile expected = new ChangedFile(folder, file, Type.ADD); - assertThat(changedFiles.getFiles(), contains(expected)); + assertThat(changedFiles.getFiles()).contains(expected); } @Test @@ -153,7 +148,7 @@ public class FileSystemWatcherTests { this.watcher.stopAfter(1); ChangedFiles changedFiles = getSingleChangedFiles(); ChangedFile expected = new ChangedFile(folder, file, Type.ADD); - assertThat(changedFiles.getFiles(), contains(expected)); + assertThat(changedFiles.getFiles()).contains(expected); } @Test @@ -165,7 +160,7 @@ public class FileSystemWatcherTests { Thread.sleep(200); touch(new File(folder, "test2.txt")); this.watcher.stopAfter(1); - assertThat(this.changes.size(), equalTo(2)); + assertThat(this.changes.size()).isEqualTo(2); } @Test @@ -178,7 +173,7 @@ public class FileSystemWatcherTests { } this.watcher.stopAfter(1); ChangedFiles changedFiles = getSingleChangedFiles(); - assertThat(changedFiles.getFiles().size(), equalTo(10)); + assertThat(changedFiles.getFiles().size()).isEqualTo(10); } @Test @@ -191,7 +186,7 @@ public class FileSystemWatcherTests { this.watcher.stopAfter(1); ChangedFiles changedFiles = getSingleChangedFiles(); ChangedFile expected = new ChangedFile(folder, file, Type.ADD); - assertThat(changedFiles.getFiles(), contains(expected)); + assertThat(changedFiles.getFiles()).contains(expected); } @Test @@ -205,17 +200,15 @@ public class FileSystemWatcherTests { File file2 = touch(new File(folder2, "test.txt")); this.watcher.stopAfter(1); Set change = getSingleOnChange(); - assertThat(change.size(), equalTo(2)); + assertThat(change.size()).isEqualTo(2); for (ChangedFiles changedFiles : change) { if (changedFiles.getSourceFolder().equals(folder1)) { ChangedFile file = new ChangedFile(folder1, file1, Type.ADD); - assertEquals(new HashSet(Arrays.asList(file)), - changedFiles.getFiles()); + assertThat(changedFiles.getFiles()).containsOnly(file); } else { ChangedFile file = new ChangedFile(folder2, file2, Type.ADD); - assertEquals(new HashSet(Arrays.asList(file)), - changedFiles.getFiles()); + assertThat(changedFiles.getFiles()).containsOnly(file); } } } @@ -236,8 +229,8 @@ public class FileSystemWatcherTests { this.watcher.stopAfter(1); ChangedFiles changedFiles = getSingleChangedFiles(); ChangedFile expected = new ChangedFile(folder, file, Type.ADD); - assertThat(changedFiles.getFiles(), contains(expected)); - assertEquals(this.changes.get(0), listener2Changes); + assertThat(changedFiles.getFiles()).contains(expected); + assertThat(listener2Changes).isEqualTo(this.changes.get(0)); } @Test @@ -257,7 +250,7 @@ public class FileSystemWatcherTests { expected.add(new ChangedFile(folder, modify, Type.MODIFY)); expected.add(new ChangedFile(folder, delete, Type.DELETE)); expected.add(new ChangedFile(folder, add, Type.ADD)); - assertEquals(expected, actual); + assertThat(actual).isEqualTo(expected); } @Test @@ -277,14 +270,14 @@ public class FileSystemWatcherTests { this.watcher.start(); FileCopyUtils.copy("abc".getBytes(), file); Thread.sleep(100); - assertThat(this.changes.size(), equalTo(0)); + assertThat(this.changes.size()).isEqualTo(0); FileCopyUtils.copy("abc".getBytes(), trigger); this.watcher.stopAfter(1); ChangedFiles changedFiles = getSingleChangedFiles(); Set actual = changedFiles.getFiles(); Set expected = new HashSet(); expected.add(new ChangedFile(folder, file, Type.MODIFY)); - assertEquals(expected, actual); + assertThat(actual).isEqualTo(expected); } private void setupWatcher(long pollingInterval, long quietPeriod) { @@ -306,12 +299,12 @@ public class FileSystemWatcherTests { private ChangedFiles getSingleChangedFiles() { Set singleChange = getSingleOnChange(); - assertThat(singleChange.size(), equalTo(1)); + assertThat(singleChange.size()).isEqualTo(1); return singleChange.iterator().next(); } private Set getSingleOnChange() { - assertThat(this.changes.size(), equalTo(1)); + assertThat(this.changes.size()).isEqualTo(1); return this.changes.get(0); } diff --git a/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/filewatch/FolderSnapshotTests.java b/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/filewatch/FolderSnapshotTests.java index 1492c7211c..476106f949 100644 --- a/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/filewatch/FolderSnapshotTests.java +++ b/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/filewatch/FolderSnapshotTests.java @@ -28,9 +28,7 @@ import org.junit.rules.TemporaryFolder; import org.springframework.boot.devtools.filewatch.ChangedFile.Type; import org.springframework.util.FileCopyUtils; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.not; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link FolderSnapshot}. @@ -72,22 +70,22 @@ public class FolderSnapshotTests { @Test public void equalsWhenNothingHasChanged() throws Exception { FolderSnapshot updatedSnapshot = new FolderSnapshot(this.folder); - assertThat(this.initialSnapshot, equalTo(updatedSnapshot)); - assertThat(this.initialSnapshot.hashCode(), equalTo(updatedSnapshot.hashCode())); + assertThat(this.initialSnapshot).isEqualTo(updatedSnapshot); + assertThat(this.initialSnapshot.hashCode()).isEqualTo(updatedSnapshot.hashCode()); } @Test public void notEqualsWhenAFileIsAdded() throws Exception { new File(new File(this.folder, "folder1"), "newfile").createNewFile(); FolderSnapshot updatedSnapshot = new FolderSnapshot(this.folder); - assertThat(this.initialSnapshot, not(equalTo(updatedSnapshot))); + assertThat(this.initialSnapshot).isNotEqualTo(updatedSnapshot); } @Test public void notEqualsWhenAFileIsDeleted() throws Exception { new File(new File(this.folder, "folder1"), "file1").delete(); FolderSnapshot updatedSnapshot = new FolderSnapshot(this.folder); - assertThat(this.initialSnapshot, not(equalTo(updatedSnapshot))); + assertThat(this.initialSnapshot).isNotEqualTo(updatedSnapshot); } @Test @@ -95,7 +93,7 @@ public class FolderSnapshotTests { File file1 = new File(new File(this.folder, "folder1"), "file1"); FileCopyUtils.copy("updatedcontent".getBytes(), file1); FolderSnapshot updatedSnapshot = new FolderSnapshot(this.folder); - assertThat(this.initialSnapshot, not(equalTo(updatedSnapshot))); + assertThat(this.initialSnapshot).isNotEqualTo(updatedSnapshot); } @Test @@ -131,10 +129,10 @@ public class FolderSnapshotTests { FolderSnapshot updatedSnapshot = new FolderSnapshot(this.folder); ChangedFiles changedFiles = this.initialSnapshot.getChangedFiles(updatedSnapshot, null); - assertThat(changedFiles.getSourceFolder(), equalTo(this.folder)); - assertThat(getChangedFile(changedFiles, file1).getType(), equalTo(Type.MODIFY)); - assertThat(getChangedFile(changedFiles, file2).getType(), equalTo(Type.DELETE)); - assertThat(getChangedFile(changedFiles, newFile).getType(), equalTo(Type.ADD)); + assertThat(changedFiles.getSourceFolder()).isEqualTo(this.folder); + assertThat(getChangedFile(changedFiles, file1).getType()).isEqualTo(Type.MODIFY); + assertThat(getChangedFile(changedFiles, file2).getType()).isEqualTo(Type.DELETE); + assertThat(getChangedFile(changedFiles, newFile).getType()).isEqualTo(Type.ADD); } private ChangedFile getChangedFile(ChangedFiles changedFiles, File file) { diff --git a/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/integrationtest/HttpTunnelIntegrationTests.java b/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/integrationtest/HttpTunnelIntegrationTests.java old mode 100755 new mode 100644 index 61cd556fa5..df4f520365 --- a/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/integrationtest/HttpTunnelIntegrationTests.java +++ b/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/integrationtest/HttpTunnelIntegrationTests.java @@ -54,7 +54,7 @@ import org.springframework.web.bind.annotation.RestController; import org.springframework.web.servlet.DispatcherServlet; import org.springframework.web.servlet.config.annotation.EnableWebMvc; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * Simple integration tests for HTTP tunneling. @@ -74,8 +74,8 @@ public class HttpTunnelIntegrationTests { String url = "http://localhost:" + this.config.httpServerPort + "/hello"; ResponseEntity entity = new TestRestTemplate().getForEntity(url, String.class); - assertEquals(HttpStatus.OK, entity.getStatusCode()); - assertEquals("Hello World", entity.getBody()); + assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); + assertThat(entity.getBody()).isEqualTo("Hello World"); } @Test @@ -83,8 +83,8 @@ public class HttpTunnelIntegrationTests { String url = "http://localhost:" + this.config.clientPort + "/hello"; ResponseEntity entity = new TestRestTemplate().getForEntity(url, String.class); - assertEquals(HttpStatus.OK, entity.getStatusCode()); - assertEquals("Hello World", entity.getBody()); + assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); + assertThat(entity.getBody()).isEqualTo("Hello World"); } @Configuration diff --git a/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/livereload/ConnectionInputStreamTests.java b/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/livereload/ConnectionInputStreamTests.java index 8268cb689b..7d36dec570 100644 --- a/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/livereload/ConnectionInputStreamTests.java +++ b/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/livereload/ConnectionInputStreamTests.java @@ -25,8 +25,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 ConnectionInputStream}. @@ -51,7 +50,7 @@ public class ConnectionInputStreamTests { String data = header + "\r\n\r\n" + "content\r\n"; ConnectionInputStream inputStream = new ConnectionInputStream( new ByteArrayInputStream(data.getBytes())); - assertThat(inputStream.readHeader(), equalTo(header)); + assertThat(inputStream.readHeader()).isEqualTo(header); } @Test @@ -62,7 +61,7 @@ public class ConnectionInputStreamTests { ConnectionInputStream inputStream = new ConnectionInputStream(source); byte[] buffer = new byte[bytes.length]; inputStream.readFully(buffer, 0, buffer.length); - assertThat(buffer, equalTo(bytes)); + assertThat(buffer).isEqualTo(bytes); } @Test diff --git a/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/livereload/ConnectionOutputStreamTests.java b/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/livereload/ConnectionOutputStreamTests.java index 45e6acbefa..4cf2a62279 100644 --- a/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/livereload/ConnectionOutputStreamTests.java +++ b/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/livereload/ConnectionOutputStreamTests.java @@ -22,8 +22,7 @@ import java.io.OutputStream; 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; @@ -55,7 +54,7 @@ public class ConnectionOutputStreamTests { expected += "Content-Length: 2\r\n"; expected += "Connection: close\r\n\r\n"; expected += "hi"; - assertThat(out.toString(), equalTo(expected)); + assertThat(out.toString()).isEqualTo(expected); } @Test @@ -67,7 +66,7 @@ public class ConnectionOutputStreamTests { String expected = ""; expected += "A: a\r\n"; expected += "B: b\r\n\r\n"; - assertThat(out.toString(), equalTo(expected)); + assertThat(out.toString()).isEqualTo(expected); } } diff --git a/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/livereload/FrameTests.java b/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/livereload/FrameTests.java index dca33b7614..9fd8dd8d2d 100644 --- a/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/livereload/FrameTests.java +++ b/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/livereload/FrameTests.java @@ -24,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 Frame}. @@ -54,15 +53,15 @@ public class FrameTests { @Test public void textPayload() throws Exception { Frame frame = new Frame("abc"); - assertThat(frame.getType(), equalTo(Frame.Type.TEXT)); - assertThat(frame.getPayload(), equalTo("abc".getBytes())); + assertThat(frame.getType()).isEqualTo(Frame.Type.TEXT); + assertThat(frame.getPayload()).isEqualTo("abc".getBytes()); } @Test public void typedPayload() throws Exception { Frame frame = new Frame(Frame.Type.CLOSE); - assertThat(frame.getType(), equalTo(Frame.Type.CLOSE)); - assertThat(frame.getPayload(), equalTo(new byte[] {})); + assertThat(frame.getType()).isEqualTo(Frame.Type.CLOSE); + assertThat(frame.getPayload()).isEqualTo(new byte[] {}); } @Test @@ -71,7 +70,7 @@ public class FrameTests { Frame frame = new Frame(payload); ByteArrayOutputStream bos = new ByteArrayOutputStream(); frame.write(bos); - assertThat(bos.toByteArray(), equalTo(new byte[] { (byte) 0x81, 0x01, 0x41 })); + assertThat(bos.toByteArray()).isEqualTo(new byte[] { (byte) 0x81, 0x01, 0x41 }); } @Test @@ -81,13 +80,13 @@ public class FrameTests { ByteArrayOutputStream bos = new ByteArrayOutputStream(); frame.write(bos); byte[] bytes = bos.toByteArray(); - assertThat(bytes.length, equalTo(130)); - assertThat(bytes[0], equalTo((byte) 0x81)); - assertThat(bytes[1], equalTo((byte) 0x7E)); - assertThat(bytes[2], equalTo((byte) 0x00)); - assertThat(bytes[3], equalTo((byte) 126)); - assertThat(bytes[4], equalTo((byte) 0x41)); - assertThat(bytes[5], equalTo((byte) 0x41)); + assertThat(bytes.length).isEqualTo(130); + assertThat(bytes[0]).isEqualTo((byte) 0x81); + assertThat(bytes[1]).isEqualTo((byte) 0x7E); + assertThat(bytes[2]).isEqualTo((byte) 0x00); + assertThat(bytes[3]).isEqualTo((byte) 126); + assertThat(bytes[4]).isEqualTo((byte) 0x41); + assertThat(bytes[5]).isEqualTo((byte) 0x41); } @Test @@ -110,8 +109,8 @@ public class FrameTests { public void readSmallTextFrame() throws Exception { byte[] bytes = new byte[] { (byte) 0x81, (byte) 0x02, 0x41, 0x41 }; Frame frame = Frame.read(newConnectionInputStream(bytes)); - assertThat(frame.getType(), equalTo(Frame.Type.TEXT)); - assertThat(frame.getPayload(), equalTo(new byte[] { 0x41, 0x41 })); + assertThat(frame.getType()).isEqualTo(Frame.Type.TEXT); + assertThat(frame.getPayload()).isEqualTo(new byte[] { 0x41, 0x41 }); } @Test @@ -119,8 +118,8 @@ public class FrameTests { byte[] bytes = new byte[] { (byte) 0x81, (byte) 0x82, 0x0F, 0x0F, 0x0F, 0x0F, 0x4E, 0x4E }; Frame frame = Frame.read(newConnectionInputStream(bytes)); - assertThat(frame.getType(), equalTo(Frame.Type.TEXT)); - assertThat(frame.getPayload(), equalTo(new byte[] { 0x41, 0x41 })); + assertThat(frame.getType()).isEqualTo(Frame.Type.TEXT); + assertThat(frame.getPayload()).isEqualTo(new byte[] { 0x41, 0x41 }); } @Test @@ -136,43 +135,43 @@ public class FrameTests { bytes[6] = 0x0F; bytes[7] = 0x0F; Frame frame = Frame.read(newConnectionInputStream(bytes)); - assertThat(frame.getType(), equalTo(Frame.Type.TEXT)); - assertThat(frame.getPayload(), equalTo(createString(126).getBytes())); + assertThat(frame.getType()).isEqualTo(Frame.Type.TEXT); + assertThat(frame.getPayload()).isEqualTo(createString(126).getBytes()); } @Test public void readContinuation() throws Exception { byte[] bytes = new byte[] { (byte) 0x80, (byte) 0x00 }; Frame frame = Frame.read(newConnectionInputStream(bytes)); - assertThat(frame.getType(), equalTo(Frame.Type.CONTINUATION)); + assertThat(frame.getType()).isEqualTo(Frame.Type.CONTINUATION); } @Test public void readBinary() throws Exception { byte[] bytes = new byte[] { (byte) 0x82, (byte) 0x00 }; Frame frame = Frame.read(newConnectionInputStream(bytes)); - assertThat(frame.getType(), equalTo(Frame.Type.BINARY)); + assertThat(frame.getType()).isEqualTo(Frame.Type.BINARY); } @Test public void readClose() throws Exception { byte[] bytes = new byte[] { (byte) 0x88, (byte) 0x00 }; Frame frame = Frame.read(newConnectionInputStream(bytes)); - assertThat(frame.getType(), equalTo(Frame.Type.CLOSE)); + assertThat(frame.getType()).isEqualTo(Frame.Type.CLOSE); } @Test public void readPing() throws Exception { byte[] bytes = new byte[] { (byte) 0x89, (byte) 0x00 }; Frame frame = Frame.read(newConnectionInputStream(bytes)); - assertThat(frame.getType(), equalTo(Frame.Type.PING)); + assertThat(frame.getType()).isEqualTo(Frame.Type.PING); } @Test public void readPong() throws Exception { byte[] bytes = new byte[] { (byte) 0x8A, (byte) 0x00 }; Frame frame = Frame.read(newConnectionInputStream(bytes)); - assertThat(frame.getType(), equalTo(Frame.Type.PONG)); + assertThat(frame.getType()).isEqualTo(Frame.Type.PONG); } private ConnectionInputStream newConnectionInputStream(byte[] bytes) { diff --git a/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/livereload/LiveReloadServerTests.java b/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/livereload/LiveReloadServerTests.java index 5f01ff96de..a089b2d4c0 100644 --- a/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/livereload/LiveReloadServerTests.java +++ b/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/livereload/LiveReloadServerTests.java @@ -40,10 +40,7 @@ import org.junit.Test; import org.springframework.util.SocketUtils; import org.springframework.web.client.RestTemplate; -import static org.hamcrest.Matchers.containsString; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.greaterThan; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link LiveReloadServer}. @@ -78,7 +75,7 @@ public class LiveReloadServerTests { RestTemplate template = new RestTemplate(); URI uri = new URI("http://localhost:" + this.port + "/livereload.js"); String script = template.getForObject(uri, String.class); - assertThat(script, containsString("livereload.com/protocols/official-7")); + assertThat(script).contains("livereload.com/protocols/official-7"); } @Test @@ -89,9 +86,9 @@ public class LiveReloadServerTests { this.server.triggerReload(); Thread.sleep(500); this.server.stop(); - assertThat(socket.getMessages(0), - containsString("http://livereload.com/protocols/official-7")); - assertThat(socket.getMessages(1), containsString("command\":\"reload\"")); + assertThat(socket.getMessages(0)) + .contains("http://livereload.com/protocols/official-7"); + assertThat(socket.getMessages(1)).contains("command\":\"reload\""); } finally { client.stop(); @@ -107,7 +104,7 @@ public class LiveReloadServerTests { socket.getRemote().sendPing(NO_DATA); Thread.sleep(200); this.server.stop(); - assertThat(driver.getPongCount(), equalTo(1)); + assertThat(driver.getPongCount()).isEqualTo(1); } finally { client.stop(); @@ -125,7 +122,7 @@ public class LiveReloadServerTests { client.stop(); } awaitClosedException(); - assertThat(this.server.getClosedExceptions().size(), greaterThan(0)); + assertThat(this.server.getClosedExceptions().size()).isGreaterThan(0); } private void awaitClosedException() throws InterruptedException { @@ -144,7 +141,7 @@ public class LiveReloadServerTests { Thread.sleep(200); this.server.stop(); Thread.sleep(200); - assertThat(socket.getCloseStatus(), equalTo(1006)); + assertThat(socket.getCloseStatus()).isEqualTo(1006); } finally { client.stop(); diff --git a/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/client/ClassPathChangeUploaderTests.java b/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/client/ClassPathChangeUploaderTests.java index cb06ea1433..4df18c1d08 100644 --- a/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/client/ClassPathChangeUploaderTests.java +++ b/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/client/ClassPathChangeUploaderTests.java @@ -44,8 +44,7 @@ import org.springframework.http.HttpStatus; import org.springframework.mock.http.client.MockClientHttpRequest; import org.springframework.util.FileCopyUtils; -import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link ClassPathChangeUploader}. @@ -117,20 +116,20 @@ public class ClassPathChangeUploaderTests { MockClientHttpRequest request = this.requestFactory.getExecutedRequests().get(0); ClassLoaderFiles classLoaderFiles = deserialize(request.getBodyAsBytes()); Collection sourceFolders = classLoaderFiles.getSourceFolders(); - assertThat(sourceFolders.size(), equalTo(1)); + assertThat(sourceFolders.size()).isEqualTo(1); SourceFolder classSourceFolder = sourceFolders.iterator().next(); - assertThat(classSourceFolder.getName(), equalTo(sourceFolder.getAbsolutePath())); + assertThat(classSourceFolder.getName()).isEqualTo(sourceFolder.getAbsolutePath()); Iterator classFiles = classSourceFolder.getFiles().iterator(); assertClassFile(classFiles.next(), "File1", ClassLoaderFile.Kind.ADDED); assertClassFile(classFiles.next(), "File2", ClassLoaderFile.Kind.MODIFIED); assertClassFile(classFiles.next(), null, ClassLoaderFile.Kind.DELETED); - assertThat(classFiles.hasNext(), equalTo(false)); + assertThat(classFiles.hasNext()).isFalse(); } private void assertClassFile(ClassLoaderFile file, String content, Kind kind) { - assertThat(file.getContents(), - equalTo(content == null ? null : content.getBytes())); - assertThat(file.getKind(), equalTo(kind)); + assertThat(file.getContents()) + .isEqualTo(content == null ? null : content.getBytes()); + assertThat(file.getKind()).isEqualTo(kind); } private File createFile(File sourceFolder, String name) throws IOException { diff --git a/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/client/DelayedLiveReloadTriggerTests.java b/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/client/DelayedLiveReloadTriggerTests.java index 7921baaa31..2dd8ab01de 100644 --- a/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/client/DelayedLiveReloadTriggerTests.java +++ b/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/client/DelayedLiveReloadTriggerTests.java @@ -33,8 +33,7 @@ import org.springframework.http.client.ClientHttpRequest; import org.springframework.http.client.ClientHttpRequestFactory; import org.springframework.http.client.ClientHttpResponse; -import static org.hamcrest.Matchers.greaterThan; -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.never; import static org.mockito.Mockito.verify; @@ -119,7 +118,7 @@ public class DelayedLiveReloadTriggerTests { long startTime = System.currentTimeMillis(); this.trigger.setTimings(10, 200, 30000); this.trigger.run(); - assertThat(System.currentTimeMillis() - startTime, greaterThan(300L)); + assertThat(System.currentTimeMillis() - startTime).isGreaterThan(300L); verify(this.liveReloadServer).triggerReload(); } diff --git a/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/client/HttpHeaderInterceptorTests.java b/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/client/HttpHeaderInterceptorTests.java index f7383c7894..6b7fa4dada 100644 --- a/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/client/HttpHeaderInterceptorTests.java +++ b/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/client/HttpHeaderInterceptorTests.java @@ -32,8 +32,7 @@ import org.springframework.http.client.ClientHttpResponse; import org.springframework.http.server.ServletServerHttpRequest; import org.springframework.mock.web.MockHttpServletRequest; -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; /** @@ -109,8 +108,8 @@ public class HttpHeaderInterceptorTests { public void intercept() throws IOException { ClientHttpResponse result = this.interceptor.intercept(this.request, this.body, this.execution); - assertThat(this.request.getHeaders().getFirst(this.name), equalTo(this.value)); - assertThat(result, equalTo(this.response)); + assertThat(this.request.getHeaders().getFirst(this.name)).isEqualTo(this.value); + assertThat(result).isEqualTo(this.response); } } diff --git a/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/client/LocalDebugPortAvailableConditionTests.java b/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/client/LocalDebugPortAvailableConditionTests.java index 23e565b70c..f9e4c5d642 100644 --- a/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/client/LocalDebugPortAvailableConditionTests.java +++ b/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/client/LocalDebugPortAvailableConditionTests.java @@ -28,8 +28,7 @@ import org.springframework.context.annotation.ConditionContext; import org.springframework.mock.env.MockEnvironment; import org.springframework.util.SocketUtils; -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; @@ -47,8 +46,8 @@ public class LocalDebugPortAvailableConditionTests { @Test public void portAvailable() throws Exception { ConditionOutcome outcome = getOutcome(); - assertThat(outcome.isMatch(), equalTo(true)); - assertThat(outcome.getMessage(), equalTo("Local debug port available")); + assertThat(outcome.isMatch()).isTrue(); + assertThat(outcome.getMessage()).isEqualTo("Local debug port available"); } @Test @@ -57,8 +56,8 @@ public class LocalDebugPortAvailableConditionTests { .createServerSocket(this.port); ConditionOutcome outcome = getOutcome(); serverSocket.close(); - assertThat(outcome.isMatch(), equalTo(false)); - assertThat(outcome.getMessage(), equalTo("Local debug port unavailable")); + assertThat(outcome.isMatch()).isFalse(); + assertThat(outcome.getMessage()).isEqualTo("Local debug port unavailable"); } private ConditionOutcome getOutcome() { diff --git a/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/client/RemoteClientConfigurationTests.java b/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/client/RemoteClientConfigurationTests.java index 5483131676..d85698a8b8 100644 --- a/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/client/RemoteClientConfigurationTests.java +++ b/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/client/RemoteClientConfigurationTests.java @@ -49,9 +49,7 @@ import org.springframework.http.server.ServerHttpRequest; import org.springframework.http.server.ServerHttpResponse; import org.springframework.util.SocketUtils; -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; import static org.mockito.BDDMockito.given; import static org.mockito.Matchers.any; import static org.mockito.Mockito.mock; @@ -88,20 +86,20 @@ public class RemoteClientConfigurationTests { public void warnIfDebugAndRestartDisabled() throws Exception { configure("spring.devtools.remote.debug.enabled:false", "spring.devtools.remote.restart.enabled:false"); - assertThat(this.output.toString(), - containsString("Remote restart and debug are both disabled")); + assertThat(this.output.toString()) + .contains("Remote restart and debug are both disabled"); } @Test public void warnIfNotHttps() throws Exception { configure("http://localhost", true); - assertThat(this.output.toString(), containsString("is insecure")); + assertThat(this.output.toString()).contains("is insecure"); } @Test public void doesntWarnIfUsingHttps() throws Exception { configure("https://localhost", true); - assertThat(this.output.toString(), not(containsString("is insecure"))); + assertThat(this.output.toString()).doesNotContain("is insecure"); } @Test diff --git a/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/server/DispatcherFilterTests.java b/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/server/DispatcherFilterTests.java index 2d649c5328..216e1074a0 100644 --- a/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/server/DispatcherFilterTests.java +++ b/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/server/DispatcherFilterTests.java @@ -38,8 +38,7 @@ import org.springframework.http.server.ServletServerHttpResponse; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; -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.willReturn; import static org.mockito.Matchers.any; import static org.mockito.Mockito.mock; @@ -114,8 +113,8 @@ public class DispatcherFilterTests { ServletServerHttpRequest actualRequest = (ServletServerHttpRequest) dispatcherRequest; ServerHttpResponse dispatcherResponse = this.serverResponseCaptor.getValue(); ServletServerHttpResponse actualResponse = (ServletServerHttpResponse) dispatcherResponse; - assertThat(actualRequest.getServletRequest(), equalTo(request)); - assertThat(actualResponse.getServletResponse(), equalTo(response)); + assertThat(actualRequest.getServletRequest()).isEqualTo(request); + assertThat(actualResponse.getServletResponse()).isEqualTo(response); } } diff --git a/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/server/DispatcherTests.java b/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/server/DispatcherTests.java index 73f52af3ca..cd5c6d56af 100644 --- a/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/server/DispatcherTests.java +++ b/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/server/DispatcherTests.java @@ -36,8 +36,7 @@ import org.springframework.http.server.ServletServerHttpResponse; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; -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.Matchers.any; import static org.mockito.Mockito.inOrder; @@ -101,7 +100,7 @@ public class DispatcherTests { Collections.singleton(mapper)); dispatcher.handle(this.serverRequest, this.serverResponse); verifyZeroInteractions(handler); - assertThat(this.response.getStatus(), equalTo(403)); + assertThat(this.response.getStatus()).isEqualTo(403); } @Test diff --git a/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/server/HttpHeaderAccessManagerTests.java b/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/server/HttpHeaderAccessManagerTests.java index aa528ea52d..0e94cd95ce 100644 --- a/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/server/HttpHeaderAccessManagerTests.java +++ b/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/server/HttpHeaderAccessManagerTests.java @@ -25,8 +25,7 @@ import org.springframework.http.server.ServerHttpRequest; import org.springframework.http.server.ServletServerHttpRequest; import org.springframework.mock.web.MockHttpServletRequest; -import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link HttpHeaderAccessManager}. @@ -87,24 +86,24 @@ public class HttpHeaderAccessManagerTests { @Test public void allowsMatching() throws Exception { this.request.addHeader(HEADER, SECRET); - assertThat(this.manager.isAllowed(this.serverRequest), equalTo(true)); + assertThat(this.manager.isAllowed(this.serverRequest)).isTrue(); } @Test public void disallowsWrongSecret() throws Exception { this.request.addHeader(HEADER, "wrong"); - assertThat(this.manager.isAllowed(this.serverRequest), equalTo(false)); + assertThat(this.manager.isAllowed(this.serverRequest)).isFalse(); } @Test public void disallowsNoSecret() throws Exception { - assertThat(this.manager.isAllowed(this.serverRequest), equalTo(false)); + assertThat(this.manager.isAllowed(this.serverRequest)).isFalse(); } @Test public void disallowsWrongHeader() throws Exception { this.request.addHeader("X-WRONG", SECRET); - assertThat(this.manager.isAllowed(this.serverRequest), equalTo(false)); + assertThat(this.manager.isAllowed(this.serverRequest)).isFalse(); } } diff --git a/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/server/HttpStatusHandlerTests.java b/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/server/HttpStatusHandlerTests.java index e70543e51a..284a0353a3 100644 --- a/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/server/HttpStatusHandlerTests.java +++ b/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/server/HttpStatusHandlerTests.java @@ -29,8 +29,7 @@ import org.springframework.http.server.ServletServerHttpResponse; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; -import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link HttpStatusHandler}. @@ -69,14 +68,14 @@ public class HttpStatusHandlerTests { public void respondsOk() throws Exception { HttpStatusHandler handler = new HttpStatusHandler(); handler.handle(this.request, this.response); - assertThat(this.servletResponse.getStatus(), equalTo(200)); + assertThat(this.servletResponse.getStatus()).isEqualTo(200); } @Test public void respondsWithStatus() throws Exception { HttpStatusHandler handler = new HttpStatusHandler(HttpStatus.I_AM_A_TEAPOT); handler.handle(this.request, this.response); - assertThat(this.servletResponse.getStatus(), equalTo(418)); + assertThat(this.servletResponse.getStatus()).isEqualTo(418); } } diff --git a/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/server/UrlHandlerMapperTests.java b/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/server/UrlHandlerMapperTests.java index c87838a829..696698f6b2 100644 --- a/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/server/UrlHandlerMapperTests.java +++ b/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/server/UrlHandlerMapperTests.java @@ -26,9 +26,7 @@ import org.springframework.http.server.ServerHttpRequest; import org.springframework.http.server.ServletServerHttpRequest; import org.springframework.mock.web.MockHttpServletRequest; -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; import static org.mockito.Mockito.mock; /** @@ -70,7 +68,7 @@ public class UrlHandlerMapperTests { UrlHandlerMapper mapper = new UrlHandlerMapper("/tunnel", this.handler); HttpServletRequest servletRequest = new MockHttpServletRequest("GET", "/tunnel"); ServerHttpRequest request = new ServletServerHttpRequest(servletRequest); - assertThat(mapper.getHandler(request), equalTo(this.handler)); + assertThat(mapper.getHandler(request)).isEqualTo(this.handler); } @Test @@ -79,7 +77,7 @@ public class UrlHandlerMapperTests { HttpServletRequest servletRequest = new MockHttpServletRequest("GET", "/tunnel/other"); ServerHttpRequest request = new ServletServerHttpRequest(servletRequest); - assertThat(mapper.getHandler(request), nullValue()); + assertThat(mapper.getHandler(request)).isNull(); } } diff --git a/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/ChangeableUrlsTests.java b/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/ChangeableUrlsTests.java index efcde69446..a1842066e7 100644 --- a/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/ChangeableUrlsTests.java +++ b/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/ChangeableUrlsTests.java @@ -24,8 +24,7 @@ import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; -import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link ChangeableUrls}. @@ -40,19 +39,19 @@ public class ChangeableUrlsTests { @Test public void folderUrl() throws Exception { URL url = makeUrl("myproject"); - assertThat(ChangeableUrls.fromUrls(url).size(), equalTo(1)); + assertThat(ChangeableUrls.fromUrls(url).size()).isEqualTo(1); } @Test public void fileUrl() throws Exception { URL url = this.temporaryFolder.newFile().toURI().toURL(); - assertThat(ChangeableUrls.fromUrls(url).size(), equalTo(0)); + assertThat(ChangeableUrls.fromUrls(url).size()).isEqualTo(0); } @Test public void httpUrl() throws Exception { URL url = new URL("http://spring.io"); - assertThat(ChangeableUrls.fromUrls(url).size(), equalTo(0)); + assertThat(ChangeableUrls.fromUrls(url).size()).isEqualTo(0); } @Test @@ -61,7 +60,7 @@ public class ChangeableUrlsTests { makeUrl("spring-boot-autoconfigure"), makeUrl("spring-boot-actuator"), makeUrl("spring-boot-starter"), makeUrl("spring-boot-starter-some-thing")); - assertThat(urls.size(), equalTo(0)); + assertThat(urls.size()).isEqualTo(0); } private URL makeUrl(String name) throws IOException { diff --git a/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/DefaultRestartInitializerTests.java b/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/DefaultRestartInitializerTests.java index a3f0ea42f4..c4ff2ee1e2 100644 --- a/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/DefaultRestartInitializerTests.java +++ b/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/DefaultRestartInitializerTests.java @@ -20,10 +20,8 @@ import java.net.URL; import org.junit.Test; -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 DefaultRestartInitializer}. @@ -35,7 +33,7 @@ public class DefaultRestartInitializerTests { @Test public void nullForTests() throws Exception { MockRestartInitializer initializer = new MockRestartInitializer(true); - assertThat(initializer.getInitialUrls(Thread.currentThread()), nullValue()); + assertThat(initializer.getInitialUrls(Thread.currentThread())).isNull(); } @Test @@ -45,8 +43,8 @@ public class DefaultRestartInitializerTests { Thread thread = new Thread(); thread.setName("main"); thread.setContextClassLoader(classLoader); - assertThat(initializer.isMain(thread), equalTo(true)); - assertThat(initializer.getInitialUrls(thread), not(nullValue())); + assertThat(initializer.isMain(thread)).isTrue(); + assertThat(initializer.getInitialUrls(thread)).isNotEqualTo(nullValue()); } @Test @@ -56,8 +54,8 @@ public class DefaultRestartInitializerTests { Thread thread = new Thread(); thread.setName("buscuit"); thread.setContextClassLoader(classLoader); - assertThat(initializer.isMain(thread), equalTo(false)); - assertThat(initializer.getInitialUrls(thread), nullValue()); + assertThat(initializer.isMain(thread)).isFalse(); + assertThat(initializer.getInitialUrls(thread)).isNull(); } @Test @@ -68,8 +66,8 @@ public class DefaultRestartInitializerTests { Thread thread = new Thread(); thread.setName("main"); thread.setContextClassLoader(classLoader); - assertThat(initializer.isMain(thread), equalTo(false)); - assertThat(initializer.getInitialUrls(thread), nullValue()); + assertThat(initializer.isMain(thread)).isFalse(); + assertThat(initializer.getInitialUrls(thread)).isNull(); } @Test @@ -86,7 +84,7 @@ public class DefaultRestartInitializerTests { MockRestartInitializer initializer = new MockRestartInitializer(true); StackTraceElement element = new StackTraceElement(className, "someMethod", "someFile", 123); - assertThat(initializer.isSkippedStackElement(element), equalTo(expected)); + assertThat(initializer.isSkippedStackElement(element)).isEqualTo(expected); } private static class MockAppClassLoader extends ClassLoader { diff --git a/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/MainMethodTests.java b/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/MainMethodTests.java index 8394ad32c0..a3b5a0c34b 100644 --- a/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/MainMethodTests.java +++ b/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/MainMethodTests.java @@ -25,8 +25,7 @@ import org.junit.rules.ExpectedException; import org.springframework.util.ReflectionUtils; -import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link MainMethod}. @@ -62,9 +61,9 @@ public class MainMethodTests { Valid.main(); } }).test(); - assertThat(method.getMethod(), equalTo(this.actualMain)); - assertThat(method.getDeclaringClassName(), - equalTo(this.actualMain.getDeclaringClass().getName())); + assertThat(method.getMethod()).isEqualTo(this.actualMain); + assertThat(method.getDeclaringClassName()) + .isEqualTo(this.actualMain.getDeclaringClass().getName()); } @Test diff --git a/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/OnInitializedRestarterConditionTests.java b/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/OnInitializedRestarterConditionTests.java index 7a294b6aee..1562d6d0e6 100644 --- a/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/OnInitializedRestarterConditionTests.java +++ b/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/OnInitializedRestarterConditionTests.java @@ -27,8 +27,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.assertj.core.api.Assertions.assertThat; import static org.mockito.BDDMockito.given; import static org.mockito.Matchers.any; import static org.mockito.Mockito.mock; @@ -53,7 +52,7 @@ public class OnInitializedRestarterConditionTests { Restarter.clearInstance(); ConfigurableApplicationContext context = new AnnotationConfigApplicationContext( Config.class); - assertThat(context.containsBean("bean"), equalTo(false)); + assertThat(context.containsBean("bean")).isFalse(); context.close(); } @@ -62,7 +61,7 @@ public class OnInitializedRestarterConditionTests { Restarter.initialize(new String[0], false, RestartInitializer.NONE); ConfigurableApplicationContext context = new AnnotationConfigApplicationContext( Config.class); - assertThat(context.containsBean("bean"), equalTo(false)); + assertThat(context.containsBean("bean")).isFalse(); context.close(); } @@ -90,7 +89,7 @@ public class OnInitializedRestarterConditionTests { Restarter.initialize(new String[0], false, initializer); ConfigurableApplicationContext context = new AnnotationConfigApplicationContext( Config.class); - assertThat(context.containsBean("bean"), equalTo(true)); + assertThat(context.containsBean("bean")).isTrue(); context.close(); synchronized (wait) { wait.notify(); diff --git a/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/RestartApplicationListenerTests.java b/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/RestartApplicationListenerTests.java index f97b503c24..5a3c83b345 100644 --- a/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/RestartApplicationListenerTests.java +++ b/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/RestartApplicationListenerTests.java @@ -28,10 +28,8 @@ import org.springframework.context.ConfigurableApplicationContext; import org.springframework.core.Ordered; import org.springframework.test.util.ReflectionTestUtils; -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; import static org.mockito.Mockito.mock; /** @@ -54,32 +52,32 @@ public class RestartApplicationListenerTests { @Test public void isHighestPriority() throws Exception { - assertThat(new RestartApplicationListener().getOrder(), - equalTo(Ordered.HIGHEST_PRECEDENCE)); + assertThat(new RestartApplicationListener().getOrder()) + .isEqualTo(Ordered.HIGHEST_PRECEDENCE); } @Test public void initializeWithReady() throws Exception { testInitialize(false); - assertThat(ReflectionTestUtils.getField(Restarter.getInstance(), "args"), - equalTo((Object) ARGS)); - assertThat(Restarter.getInstance().isFinished(), equalTo(true)); + assertThat(ReflectionTestUtils.getField(Restarter.getInstance(), "args")) + .isEqualTo(ARGS); + assertThat(Restarter.getInstance().isFinished()).isTrue(); } @Test public void initializeWithFail() throws Exception { testInitialize(true); - assertThat(ReflectionTestUtils.getField(Restarter.getInstance(), "args"), - equalTo((Object) ARGS)); - assertThat(Restarter.getInstance().isFinished(), equalTo(true)); + assertThat(ReflectionTestUtils.getField(Restarter.getInstance(), "args")) + .isEqualTo(ARGS); + assertThat(Restarter.getInstance().isFinished()).isTrue(); } @Test public void disableWithSystemProperty() throws Exception { System.setProperty(ENABLED_PROPERTY, "false"); testInitialize(false); - assertThat(ReflectionTestUtils.getField(Restarter.getInstance(), "enabled"), - equalTo((Object) false)); + assertThat(ReflectionTestUtils.getField(Restarter.getInstance(), "enabled")) + .isEqualTo(false); } private void testInitialize(boolean failed) { @@ -89,8 +87,8 @@ public class RestartApplicationListenerTests { ConfigurableApplicationContext context = mock( ConfigurableApplicationContext.class); listener.onApplicationEvent(new ApplicationStartedEvent(application, ARGS)); - assertThat(Restarter.getInstance(), not(nullValue())); - assertThat(Restarter.getInstance().isFinished(), equalTo(false)); + assertThat(Restarter.getInstance()).isNotEqualTo(nullValue()); + assertThat(Restarter.getInstance().isFinished()).isFalse(); if (failed) { listener.onApplicationEvent(new ApplicationFailedEvent(application, ARGS, context, new RuntimeException())); diff --git a/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/RestartScopeInitializerTests.java b/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/RestartScopeInitializerTests.java index b1f25ae63a..e8c2a03c4d 100644 --- a/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/RestartScopeInitializerTests.java +++ b/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/RestartScopeInitializerTests.java @@ -27,8 +27,7 @@ import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.event.ContextRefreshedEvent; -import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link RestartScopeInitializer}. @@ -49,8 +48,8 @@ public class RestartScopeInitializerTests { context.close(); context = runApplication(); context.close(); - assertThat(createCount.get(), equalTo(1)); - assertThat(refreshCount.get(), equalTo(2)); + assertThat(createCount.get()).isEqualTo(1); + assertThat(refreshCount.get()).isEqualTo(2); } private ConfigurableApplicationContext runApplication() { diff --git a/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/RestarterTests.java b/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/RestarterTests.java index 94c56dd314..2fef09ff21 100644 --- a/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/RestarterTests.java +++ b/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/RestarterTests.java @@ -41,9 +41,7 @@ import org.springframework.stereotype.Component; import org.springframework.util.FileCopyUtils; import org.springframework.util.StringUtils; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.greaterThan; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.BDDMockito.given; import static org.mockito.Matchers.any; import static org.mockito.Mockito.mock; @@ -94,9 +92,9 @@ public class RestarterTests { thread.start(); Thread.sleep(2600); String output = this.out.toString(); - assertThat(StringUtils.countOccurrencesOf(output, "Tick 0"), greaterThan(1)); - assertThat(StringUtils.countOccurrencesOf(output, "Tick 1"), greaterThan(1)); - assertThat(TestRestartListener.restarts, greaterThan(0)); + assertThat(StringUtils.countOccurrencesOf(output, "Tick 0")).isGreaterThan(1); + assertThat(StringUtils.countOccurrencesOf(output, "Tick 1")).isGreaterThan(1); + assertThat(TestRestartListener.restarts).isGreaterThan(0); } @Test @@ -105,7 +103,7 @@ public class RestarterTests { ObjectFactory objectFactory = mock(ObjectFactory.class); given(objectFactory.getObject()).willReturn("abc"); Object attribute = Restarter.getInstance().getOrAddAttribute("x", objectFactory); - assertThat(attribute, equalTo((Object) "abc")); + assertThat(attribute).isEqualTo("abc"); } public void addUrlsMustNotBeNull() throws Exception { @@ -123,7 +121,7 @@ public class RestarterTests { restarter.restart(); ClassLoader classLoader = ((TestableRestarter) restarter) .getRelaunchClassLoader(); - assertThat(((URLClassLoader) classLoader).getURLs()[0], equalTo(url)); + assertThat(((URLClassLoader) classLoader).getURLs()[0]).isEqualTo(url); } @Test @@ -142,8 +140,8 @@ public class RestarterTests { restarter.restart(); ClassLoader classLoader = ((TestableRestarter) restarter) .getRelaunchClassLoader(); - assertThat(FileCopyUtils.copyToByteArray(classLoader.getResourceAsStream("f")), - equalTo("abc".getBytes())); + assertThat(FileCopyUtils.copyToByteArray(classLoader.getResourceAsStream("f"))) + .isEqualTo("abc".getBytes()); } @Test @@ -157,7 +155,7 @@ public class RestarterTests { }); ObjectFactory objectFactory = mock(ObjectFactory.class); Object attribute = Restarter.getInstance().getOrAddAttribute("x", objectFactory); - assertThat(attribute, equalTo((Object) "abc")); + assertThat(attribute).isEqualTo("abc"); verifyZeroInteractions(objectFactory); } @@ -173,9 +171,9 @@ public class RestarterTests { ThreadFactory factory = Restarter.getInstance().getThreadFactory(); Thread viaFactory = factory.newThread(runnable); // Regular threads will inherit the current thread - assertThat(regular.getContextClassLoader(), equalTo(contextClassLoader)); + assertThat(regular.getContextClassLoader()).isEqualTo(contextClassLoader); // Factory threads should should inherit from the initial thread - assertThat(viaFactory.getContextClassLoader(), equalTo(parentLoader)); + assertThat(viaFactory.getContextClassLoader()).isEqualTo(parentLoader); }; }; thread.setContextClassLoader(contextClassLoader); @@ -190,7 +188,7 @@ public class RestarterTests { URL[] urls = new URL[] { new URL("file:/proj/module-a.jar!/") }; given(initializer.getInitialUrls(any(Thread.class))).willReturn(urls); Restarter.initialize(new String[0], false, initializer, false); - assertThat(Restarter.getInstance().getInitialUrls(), equalTo(urls)); + assertThat(Restarter.getInstance().getInitialUrls()).isEqualTo(urls); } @Component diff --git a/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/SilentExitExceptionHandlerTests.java b/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/SilentExitExceptionHandlerTests.java index bea23ecc06..3ba0a98524 100644 --- a/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/SilentExitExceptionHandlerTests.java +++ b/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/SilentExitExceptionHandlerTests.java @@ -18,9 +18,7 @@ package org.springframework.boot.devtools.restart; import org.junit.Test; -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; import static org.junit.Assert.fail; /** @@ -41,7 +39,7 @@ public class SilentExitExceptionHandlerTests { }; SilentExitExceptionHandler.setup(testThread); testThread.startAndJoin(); - assertThat(testThread.getThrown(), nullValue()); + assertThat(testThread.getThrown()).isNull(); } @Test @@ -54,7 +52,7 @@ public class SilentExitExceptionHandlerTests { }; SilentExitExceptionHandler.setup(testThread); testThread.startAndJoin(); - assertThat(testThread.getThrown().getMessage(), equalTo("Expected")); + assertThat(testThread.getThrown().getMessage()).isEqualTo("Expected"); } private static abstract class TestThread extends Thread { diff --git a/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/classloader/ClassLoaderFileTests.java b/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/classloader/ClassLoaderFileTests.java index 26a5e1549d..b7a98c6d25 100644 --- a/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/classloader/ClassLoaderFileTests.java +++ b/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/classloader/ClassLoaderFileTests.java @@ -22,9 +22,7 @@ import org.junit.rules.ExpectedException; import org.springframework.boot.devtools.restart.classloader.ClassLoaderFile.Kind; -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 ClassLoaderFile}. @@ -69,22 +67,22 @@ public class ClassLoaderFileTests { @Test public void added() throws Exception { ClassLoaderFile file = new ClassLoaderFile(Kind.ADDED, BYTES); - assertThat(file.getKind(), equalTo(ClassLoaderFile.Kind.ADDED)); - assertThat(file.getContents(), equalTo(BYTES)); + assertThat(file.getKind()).isEqualTo(ClassLoaderFile.Kind.ADDED); + assertThat(file.getContents()).isEqualTo(BYTES); } @Test public void modified() throws Exception { ClassLoaderFile file = new ClassLoaderFile(Kind.MODIFIED, BYTES); - assertThat(file.getKind(), equalTo(ClassLoaderFile.Kind.MODIFIED)); - assertThat(file.getContents(), equalTo(BYTES)); + assertThat(file.getKind()).isEqualTo(ClassLoaderFile.Kind.MODIFIED); + assertThat(file.getContents()).isEqualTo(BYTES); } @Test public void deleted() throws Exception { ClassLoaderFile file = new ClassLoaderFile(Kind.DELETED, null); - assertThat(file.getKind(), equalTo(ClassLoaderFile.Kind.DELETED)); - assertThat(file.getContents(), nullValue()); + assertThat(file.getKind()).isEqualTo(ClassLoaderFile.Kind.DELETED); + assertThat(file.getContents()).isNull(); } } diff --git a/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/classloader/ClassLoaderFilesTests.java b/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/classloader/ClassLoaderFilesTests.java index df94c86a56..7cf20a34a1 100644 --- a/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/classloader/ClassLoaderFilesTests.java +++ b/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/classloader/ClassLoaderFilesTests.java @@ -20,8 +20,6 @@ import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; -import java.util.ArrayList; -import java.util.Arrays; import java.util.Iterator; import org.junit.Rule; @@ -31,10 +29,7 @@ import org.junit.rules.ExpectedException; import org.springframework.boot.devtools.restart.classloader.ClassLoaderFile.Kind; import org.springframework.boot.devtools.restart.classloader.ClassLoaderFiles.SourceFolder; -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; import static org.mockito.Mockito.mock; /** @@ -65,19 +60,19 @@ public class ClassLoaderFilesTests { @Test public void getFileWithNullName() throws Exception { - assertThat(this.files.getFile(null), nullValue()); + assertThat(this.files.getFile(null)).isNull(); } @Test public void addAndGet() throws Exception { ClassLoaderFile file = new ClassLoaderFile(Kind.ADDED, new byte[10]); this.files.addFile("myfile", file); - assertThat(this.files.getFile("myfile"), equalTo(file)); + assertThat(this.files.getFile("myfile")).isEqualTo(file); } @Test public void getMissing() throws Exception { - assertThat(this.files.getFile("missing"), nullValue()); + assertThat(this.files.getFile("missing")).isNull(); } @Test @@ -86,7 +81,7 @@ public class ClassLoaderFilesTests { ClassLoaderFile file2 = new ClassLoaderFile(Kind.MODIFIED, new byte[10]); this.files.addFile("myfile", file1); this.files.addFile("myfile", file2); - assertThat(this.files.getFile("myfile"), equalTo(file2)); + assertThat(this.files.getFile("myfile")).isEqualTo(file2); } @Test @@ -95,9 +90,11 @@ public class ClassLoaderFilesTests { ClassLoaderFile file2 = new ClassLoaderFile(Kind.MODIFIED, new byte[10]); this.files.addFile("a", "myfile", file1); this.files.addFile("b", "myfile", file2); - assertThat(this.files.getFile("myfile"), equalTo(file2)); - assertThat(this.files.getOrCreateSourceFolder("a").getFiles().size(), equalTo(0)); - assertThat(this.files.getOrCreateSourceFolder("b").getFiles().size(), equalTo(1)); + assertThat(this.files.getFile("myfile")).isEqualTo(file2); + assertThat(this.files.getOrCreateSourceFolder("a").getFiles().size()) + .isEqualTo(0); + assertThat(this.files.getOrCreateSourceFolder("b").getFiles().size()) + .isEqualTo(1); } @Test @@ -113,13 +110,11 @@ public class ClassLoaderFilesTests { Iterator sourceFolders = this.files.getSourceFolders().iterator(); SourceFolder sourceFolder1 = sourceFolders.next(); SourceFolder sourceFolder2 = sourceFolders.next(); - assertThat(sourceFolders.hasNext(), equalTo(false)); - assertThat(sourceFolder1.getName(), equalTo("a")); - assertThat(sourceFolder2.getName(), equalTo("b")); - assertThat(new ArrayList(sourceFolder1.getFiles()), - equalTo(Arrays.asList(file1, file2))); - assertThat(new ArrayList(sourceFolder2.getFiles()), - equalTo(Arrays.asList(file3, file4))); + assertThat(sourceFolders.hasNext()).isFalse(); + assertThat(sourceFolder1.getName()).isEqualTo("a"); + assertThat(sourceFolder2.getName()).isEqualTo("b"); + assertThat(sourceFolder1.getFiles()).containsOnly(file1, file2); + assertThat(sourceFolder2.getFiles()).containsOnly(file3, file4); } @Test @@ -133,7 +128,7 @@ public class ClassLoaderFilesTests { ObjectInputStream ois = new ObjectInputStream( new ByteArrayInputStream(bos.toByteArray())); ClassLoaderFiles readObject = (ClassLoaderFiles) ois.readObject(); - assertThat(readObject.getFile("myfile"), notNullValue()); + assertThat(readObject.getFile("myfile")).isNotNull(); } @Test @@ -149,11 +144,10 @@ public class ClassLoaderFilesTests { Iterator sourceFolders = this.files.getSourceFolders().iterator(); SourceFolder sourceFolder1 = sourceFolders.next(); SourceFolder sourceFolder2 = sourceFolders.next(); - assertThat(sourceFolders.hasNext(), equalTo(false)); - assertThat(sourceFolder1.getName(), equalTo("a")); - assertThat(sourceFolder2.getName(), equalTo("b")); - assertThat(new ArrayList(sourceFolder1.getFiles()), - equalTo(Arrays.asList(file1, file2))); + assertThat(sourceFolders.hasNext()).isFalse(); + assertThat(sourceFolder1.getName()).isEqualTo("a"); + assertThat(sourceFolder2.getName()).isEqualTo("b"); + assertThat(sourceFolder1.getFiles()).containsOnly(file1, file2); } @Test @@ -162,7 +156,7 @@ public class ClassLoaderFilesTests { this.files.addFile("s1", "n2", mock(ClassLoaderFile.class)); this.files.addFile("s2", "n3", mock(ClassLoaderFile.class)); this.files.addFile("s2", "n1", mock(ClassLoaderFile.class)); - assertThat(this.files.size(), equalTo(3)); + assertThat(this.files.size()).isEqualTo(3); } @Test @@ -178,8 +172,8 @@ public class ClassLoaderFilesTests { this.files.addFile("s1", "n2", mock(ClassLoaderFile.class)); ClassLoaderFiles copy = new ClassLoaderFiles(this.files); this.files.addFile("s2", "n3", mock(ClassLoaderFile.class)); - assertThat(this.files.size(), equalTo(3)); - assertThat(copy.size(), equalTo(2)); + assertThat(this.files.size()).isEqualTo(3); + assertThat(copy.size()).isEqualTo(2); } } diff --git a/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/classloader/RestartClassLoaderTests.java b/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/classloader/RestartClassLoaderTests.java index 57988fdff6..cb32c2018c 100644 --- a/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/classloader/RestartClassLoaderTests.java +++ b/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/classloader/RestartClassLoaderTests.java @@ -39,9 +39,7 @@ import org.springframework.boot.devtools.restart.classloader.ClassLoaderFile.Kin import org.springframework.util.FileCopyUtils; import org.springframework.util.StreamUtils; -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 RestartClassLoader}. @@ -115,48 +113,47 @@ public class RestartClassLoaderTests { public void getResourceFromReloadableUrl() throws Exception { String content = readString( this.reloadClassLoader.getResourceAsStream(PACKAGE_PATH + "/Sample.txt")); - assertThat(content, startsWith("fromchild")); + assertThat(content).startsWith("fromchild"); } @Test public void getResourceFromParent() throws Exception { String content = readString( this.reloadClassLoader.getResourceAsStream(PACKAGE_PATH + "/Parent.txt")); - assertThat(content, startsWith("fromparent")); + assertThat(content).startsWith("fromparent"); } @Test public void getResourcesFiltersDuplicates() throws Exception { List resources = toList( this.reloadClassLoader.getResources(PACKAGE_PATH + "/Sample.txt")); - assertThat(resources.size(), equalTo(1)); + assertThat(resources.size()).isEqualTo(1); } @Test public void loadClassFromReloadableUrl() throws Exception { Class loaded = this.reloadClassLoader.loadClass(PACKAGE + ".Sample"); - assertThat(loaded.getClassLoader(), - equalTo((ClassLoader) this.reloadClassLoader)); + assertThat(loaded.getClassLoader()).isEqualTo(this.reloadClassLoader); } @Test public void loadClassFromParent() throws Exception { Class loaded = this.reloadClassLoader.loadClass(PACKAGE + ".SampleParent"); - assertThat(loaded.getClassLoader(), equalTo(getClass().getClassLoader())); + assertThat(loaded.getClassLoader()).isEqualTo(getClass().getClassLoader()); } @Test public void getDeletedResource() throws Exception { String name = PACKAGE_PATH + "/Sample.txt"; this.updatedFiles.addFile(name, new ClassLoaderFile(Kind.DELETED, null)); - assertThat(this.reloadClassLoader.getResource(name), equalTo(null)); + assertThat(this.reloadClassLoader.getResource(name)).isEqualTo(null); } @Test public void getDeletedResourceAsStream() throws Exception { String name = PACKAGE_PATH + "/Sample.txt"; this.updatedFiles.addFile(name, new ClassLoaderFile(Kind.DELETED, null)); - assertThat(this.reloadClassLoader.getResourceAsStream(name), equalTo(null)); + assertThat(this.reloadClassLoader.getResourceAsStream(name)).isEqualTo(null); } @Test @@ -165,7 +162,7 @@ public class RestartClassLoaderTests { byte[] bytes = "abc".getBytes(); this.updatedFiles.addFile(name, new ClassLoaderFile(Kind.MODIFIED, bytes)); URL resource = this.reloadClassLoader.getResource(name); - assertThat(FileCopyUtils.copyToByteArray(resource.openStream()), equalTo(bytes)); + assertThat(FileCopyUtils.copyToByteArray(resource.openStream())).isEqualTo(bytes); } @Test @@ -173,7 +170,7 @@ public class RestartClassLoaderTests { String name = PACKAGE_PATH + "/Sample.txt"; this.updatedFiles.addFile(name, new ClassLoaderFile(Kind.DELETED, null)); List resources = toList(this.reloadClassLoader.getResources(name)); - assertThat(resources.size(), equalTo(0)); + assertThat(resources.size()).isEqualTo(0); } @Test @@ -182,8 +179,8 @@ public class RestartClassLoaderTests { byte[] bytes = "abc".getBytes(); this.updatedFiles.addFile(name, new ClassLoaderFile(Kind.MODIFIED, bytes)); List resources = toList(this.reloadClassLoader.getResources(name)); - assertThat(FileCopyUtils.copyToByteArray(resources.get(0).openStream()), - equalTo(bytes)); + assertThat(FileCopyUtils.copyToByteArray(resources.get(0).openStream())) + .isEqualTo(bytes); } @Test @@ -209,8 +206,7 @@ public class RestartClassLoaderTests { .copyToByteArray(getClass().getResourceAsStream("SampleParent.class")); this.updatedFiles.addFile(name, new ClassLoaderFile(Kind.ADDED, bytes)); Class loaded = this.reloadClassLoader.loadClass(PACKAGE + ".SampleParent"); - assertThat(loaded.getClassLoader(), - equalTo((ClassLoader) this.reloadClassLoader)); + assertThat(loaded.getClassLoader()).isEqualTo(this.reloadClassLoader); } private String readString(InputStream in) throws IOException { diff --git a/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/server/DefaultSourceFolderUrlFilterTests.java b/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/server/DefaultSourceFolderUrlFilterTests.java index 4b6e9549b4..38ecb7647e 100644 --- a/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/server/DefaultSourceFolderUrlFilterTests.java +++ b/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/server/DefaultSourceFolderUrlFilterTests.java @@ -24,8 +24,7 @@ import java.util.List; 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 DefaultSourceFolderUrlFilter}. @@ -76,14 +75,14 @@ public class DefaultSourceFolderUrlFilterTests { + "spring-boot-sample-devtools"; URL jarUrl = new URL("jar:file:/Users/me/tmp/" + "spring-boot-sample-devtools-1.3.0.BUILD-SNAPSHOT.jar!/"); - assertThat(this.filter.isMatch(sourceFolder, jarUrl), equalTo(true)); + assertThat(this.filter.isMatch(sourceFolder, jarUrl)).isTrue(); URL nestedJarUrl = new URL("jar:file:/Users/me/tmp/" + "spring-boot-sample-devtools-1.3.0.BUILD-SNAPSHOT.jar!/" + "lib/spring-boot-1.3.0.BUILD-SNAPSHOT.jar!/"); - assertThat(this.filter.isMatch(sourceFolder, nestedJarUrl), equalTo(false)); + assertThat(this.filter.isMatch(sourceFolder, nestedJarUrl)).isFalse(); URL fileUrl = new URL("file:/Users/me/tmp/" + "spring-boot-sample-devtools-1.3.0.BUILD-SNAPSHOT.jar"); - assertThat(this.filter.isMatch(sourceFolder, fileUrl), equalTo(true)); + assertThat(this.filter.isMatch(sourceFolder, fileUrl)).isTrue(); } private void doTest(String sourcePostfix) throws MalformedURLException { @@ -99,7 +98,8 @@ public class DefaultSourceFolderUrlFilterTests { for (String postfix : COMMON_POSTFIXES) { for (URL url : getUrls(moduleRoot + postfix)) { boolean match = this.filter.isMatch(sourceFolder, url); - assertThat(url + " against " + sourceFolder, match, equalTo(expected)); + assertThat(match).as(url + " against " + sourceFolder) + .isEqualTo(expected); } } } diff --git a/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/server/HttpRestartServerTests.java b/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/server/HttpRestartServerTests.java index 3a3d0e45fc..0a30f7a5d6 100644 --- a/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/server/HttpRestartServerTests.java +++ b/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/server/HttpRestartServerTests.java @@ -37,9 +37,7 @@ import org.springframework.http.server.ServletServerHttpResponse; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.notNullValue; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyZeroInteractions; @@ -92,8 +90,8 @@ public class HttpRestartServerTests { this.server.handle(new ServletServerHttpRequest(request), new ServletServerHttpResponse(response)); verify(this.delegate).updateAndRestart(this.filesCaptor.capture()); - assertThat(this.filesCaptor.getValue().getFile("name"), notNullValue()); - assertThat(response.getStatus(), equalTo(200)); + assertThat(this.filesCaptor.getValue().getFile("name")).isNotNull(); + assertThat(response.getStatus()).isEqualTo(200); } @Test @@ -103,7 +101,7 @@ public class HttpRestartServerTests { this.server.handle(new ServletServerHttpRequest(request), new ServletServerHttpResponse(response)); verifyZeroInteractions(this.delegate); - assertThat(response.getStatus(), equalTo(500)); + assertThat(response.getStatus()).isEqualTo(500); } @@ -115,7 +113,7 @@ public class HttpRestartServerTests { this.server.handle(new ServletServerHttpRequest(request), new ServletServerHttpResponse(response)); verifyZeroInteractions(this.delegate); - assertThat(response.getStatus(), equalTo(500)); + assertThat(response.getStatus()).isEqualTo(500); } private byte[] serialize(Object object) throws IOException { diff --git a/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/server/RestartServerTests.java b/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/server/RestartServerTests.java index cd3267d38e..ef773605fb 100644 --- a/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/server/RestartServerTests.java +++ b/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/server/RestartServerTests.java @@ -34,9 +34,7 @@ import org.springframework.boot.devtools.restart.classloader.ClassLoaderFile.Kin import org.springframework.boot.devtools.restart.classloader.ClassLoaderFiles; import org.springframework.util.FileCopyUtils; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.greaterThan; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link RestartServer}. @@ -76,8 +74,8 @@ public class RestartServerTests { files.addFile("my/module-c", "ClassB.class", fileB); server.updateAndRestart(files); Set expectedUrls = new LinkedHashSet(Arrays.asList(url1, url3)); - assertThat(server.restartUrls, equalTo(expectedUrls)); - assertThat(server.restartFiles, equalTo(files)); + assertThat(server.restartUrls).isEqualTo(expectedUrls); + assertThat(server.restartFiles).isEqualTo(files); } @Test @@ -95,7 +93,7 @@ public class RestartServerTests { ClassLoaderFile fileA = new ClassLoaderFile(Kind.ADDED, new byte[0]); files.addFile("my/module-a", "ClassA.class", fileA); server.updateAndRestart(files); - assertThat(jarFile.lastModified(), greaterThan(startTime - 1000)); + assertThat(jarFile.lastModified()).isGreaterThan(startTime - 1000); } @Test @@ -114,7 +112,7 @@ public class RestartServerTests { ClassLoaderFile fileA = new ClassLoaderFile(Kind.ADDED, "def".getBytes()); files.addFile("my/module-a", "ClassA.class", fileA); server.updateAndRestart(files); - assertThat(FileCopyUtils.copyToByteArray(classFile), equalTo("def".getBytes())); + assertThat(FileCopyUtils.copyToByteArray(classFile)).isEqualTo("def".getBytes()); } private static class MockRestartServer extends RestartServer { diff --git a/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/settings/DevToolsSettingsTests.java b/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/settings/DevToolsSettingsTests.java index 80f017f509..54a4475e0d 100644 --- a/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/settings/DevToolsSettingsTests.java +++ b/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/settings/DevToolsSettingsTests.java @@ -24,9 +24,7 @@ import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; -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 DevToolsSettings}. @@ -45,28 +43,30 @@ public class DevToolsSettingsTests { public void includePatterns() throws Exception { DevToolsSettings settings = DevToolsSettings .load(ROOT + "spring-devtools-include.properties"); - assertThat(settings.isRestartInclude(new URL("file://test/a")), equalTo(true)); - assertThat(settings.isRestartInclude(new URL("file://test/b")), equalTo(true)); - assertThat(settings.isRestartInclude(new URL("file://test/c")), equalTo(false)); + assertThat(settings.isRestartInclude(new URL("file://test/a"))).isTrue(); + assertThat(settings.isRestartInclude(new URL("file://test/b"))).isTrue(); + assertThat(settings.isRestartInclude(new URL("file://test/c"))).isFalse(); } @Test public void excludePatterns() throws Exception { DevToolsSettings settings = DevToolsSettings .load(ROOT + "spring-devtools-exclude.properties"); - assertThat(settings.isRestartExclude(new URL("file://test/a")), equalTo(true)); - assertThat(settings.isRestartExclude(new URL("file://test/b")), equalTo(true)); - assertThat(settings.isRestartExclude(new URL("file://test/c")), equalTo(false)); + assertThat(settings.isRestartExclude(new URL("file://test/a"))).isTrue(); + assertThat(settings.isRestartExclude(new URL("file://test/b"))).isTrue(); + assertThat(settings.isRestartExclude(new URL("file://test/c"))).isFalse(); } @Test public void defaultIncludePatterns() throws Exception { DevToolsSettings settings = DevToolsSettings.get(); - assertTrue(settings.isRestartExclude(makeUrl("spring-boot"))); - assertTrue(settings.isRestartExclude(makeUrl("spring-boot-autoconfigure"))); - assertTrue(settings.isRestartExclude(makeUrl("spring-boot-actuator"))); - assertTrue(settings.isRestartExclude(makeUrl("spring-boot-starter"))); - assertTrue(settings.isRestartExclude(makeUrl("spring-boot-starter-some-thing"))); + assertThat(settings.isRestartExclude(makeUrl("spring-boot"))).isTrue(); + assertThat(settings.isRestartExclude(makeUrl("spring-boot-autoconfigure"))) + .isTrue(); + assertThat(settings.isRestartExclude(makeUrl("spring-boot-actuator"))).isTrue(); + assertThat(settings.isRestartExclude(makeUrl("spring-boot-starter"))).isTrue(); + assertThat(settings.isRestartExclude(makeUrl("spring-boot-starter-some-thing"))) + .isTrue(); } private URL makeUrl(String name) throws IOException { diff --git a/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/tunnel/client/HttpTunnelConnectionTests.java b/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/tunnel/client/HttpTunnelConnectionTests.java index c8f0f2b8d1..1fc1106ca2 100644 --- a/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/tunnel/client/HttpTunnelConnectionTests.java +++ b/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/tunnel/client/HttpTunnelConnectionTests.java @@ -36,9 +36,7 @@ import org.springframework.boot.devtools.tunnel.client.HttpTunnelConnection.Tunn import org.springframework.http.HttpStatus; import org.springframework.util.SocketUtils; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.greaterThan; -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.times; import static org.mockito.Mockito.verify; @@ -107,9 +105,9 @@ public class HttpTunnelConnectionTests { public void closeTunnelChangesIsOpen() throws Exception { this.requestFactory.willRespondAfterDelay(1000, HttpStatus.GONE); WritableByteChannel channel = openTunnel(false); - assertThat(channel.isOpen(), equalTo(true)); + assertThat(channel.isOpen()).isTrue(); channel.close(); - assertThat(channel.isOpen(), equalTo(false)); + assertThat(channel.isOpen()).isFalse(); } @Test @@ -129,7 +127,7 @@ public class HttpTunnelConnectionTests { write(channel, "hello"); write(channel, "1+1"); write(channel, "1+2"); - assertThat(this.incomingData.toString(), equalTo("hi=2=3")); + assertThat(this.incomingData.toString()).isEqualTo("hi=2=3"); } @Test @@ -140,8 +138,8 @@ public class HttpTunnelConnectionTests { this.requestFactory.willRespond("hi"); TunnelChannel channel = openTunnel(true); write(channel, "hello"); - assertThat(this.incomingData.toString(), equalTo("hi")); - assertThat(this.requestFactory.getExecutedRequests().size(), greaterThan(10)); + assertThat(this.incomingData.toString()).isEqualTo("hi"); + assertThat(this.requestFactory.getExecutedRequests().size()).isGreaterThan(10); } private void write(TunnelChannel channel, String string) throws IOException { diff --git a/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/tunnel/client/TunnelClientTests.java b/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/tunnel/client/TunnelClientTests.java index 76a42ffa00..5ca545f54f 100644 --- a/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/tunnel/client/TunnelClientTests.java +++ b/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/tunnel/client/TunnelClientTests.java @@ -31,8 +31,7 @@ import org.junit.rules.ExpectedException; import org.springframework.util.SocketUtils; -import static org.hamcrest.Matchers.equalTo; -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.mock; import static org.mockito.Mockito.verify; @@ -76,7 +75,7 @@ public class TunnelClientTests { channel.read(buffer); channel.close(); this.tunnelConnection.verifyWritten("hello"); - assertThat(new String(buffer.array()), equalTo("olleh")); + assertThat(new String(buffer.array())).isEqualTo("olleh"); } @Test @@ -89,8 +88,8 @@ public class TunnelClientTests { channel.close(); client.getServerThread().stopAcceptingConnections(); client.getServerThread().join(2000); - assertThat(this.tunnelConnection.getOpenedTimes(), equalTo(1)); - assertThat(this.tunnelConnection.isOpen(), equalTo(false)); + assertThat(this.tunnelConnection.getOpenedTimes()).isEqualTo(1); + assertThat(this.tunnelConnection.isOpen()).isFalse(); } @Test @@ -101,9 +100,9 @@ public class TunnelClientTests { .open(new InetSocketAddress(this.listenPort)); Thread.sleep(200); client.stop(); - assertThat(this.tunnelConnection.getOpenedTimes(), equalTo(1)); - assertThat(this.tunnelConnection.isOpen(), equalTo(false)); - assertThat(channel.read(ByteBuffer.allocate(1)), equalTo(-1)); + assertThat(this.tunnelConnection.getOpenedTimes()).isEqualTo(1); + assertThat(this.tunnelConnection.isOpen()).isFalse(); + assertThat(channel.read(ByteBuffer.allocate(1))).isEqualTo(-1); } @Test @@ -144,7 +143,7 @@ public class TunnelClientTests { public void verifyWritten(byte[] expected) { synchronized (this.written) { - assertThat(this.written.toByteArray(), equalTo(expected)); + assertThat(this.written.toByteArray()).isEqualTo(expected); this.written.reset(); } } diff --git a/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/tunnel/payload/HttpTunnelPayloadForwarderTests.java b/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/tunnel/payload/HttpTunnelPayloadForwarderTests.java index aadbcd33d4..e59f3eb213 100644 --- a/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/tunnel/payload/HttpTunnelPayloadForwarderTests.java +++ b/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/tunnel/payload/HttpTunnelPayloadForwarderTests.java @@ -25,8 +25,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 HttpTunnelPayloadForwarder}. @@ -53,7 +52,7 @@ public class HttpTunnelPayloadForwarderTests { forwarder.forward(payload(1, "he")); forwarder.forward(payload(2, "ll")); forwarder.forward(payload(3, "o")); - assertThat(out.toByteArray(), equalTo("hello".getBytes())); + assertThat(out.toByteArray()).isEqualTo("hello".getBytes()); } @Test @@ -64,7 +63,7 @@ public class HttpTunnelPayloadForwarderTests { forwarder.forward(payload(3, "o")); forwarder.forward(payload(2, "ll")); forwarder.forward(payload(1, "he")); - assertThat(out.toByteArray(), equalTo("hello".getBytes())); + assertThat(out.toByteArray()).isEqualTo("hello".getBytes()); } @Test diff --git a/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/tunnel/payload/HttpTunnelPayloadTests.java b/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/tunnel/payload/HttpTunnelPayloadTests.java index 5e5d6d3aa1..29c1fab628 100644 --- a/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/tunnel/payload/HttpTunnelPayloadTests.java +++ b/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/tunnel/payload/HttpTunnelPayloadTests.java @@ -36,9 +36,7 @@ import org.springframework.http.server.ServletServerHttpResponse; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; -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; import static org.mockito.BDDMockito.given; import static org.mockito.Matchers.any; import static org.mockito.Mockito.mock; @@ -70,14 +68,14 @@ public class HttpTunnelPayloadTests { @Test public void getSequence() throws Exception { HttpTunnelPayload payload = new HttpTunnelPayload(1, ByteBuffer.allocate(1)); - assertThat(payload.getSequence(), equalTo(1L)); + assertThat(payload.getSequence()).isEqualTo(1L); } @Test public void getData() throws Exception { ByteBuffer data = ByteBuffer.wrap("hello".getBytes()); HttpTunnelPayload payload = new HttpTunnelPayload(1, data); - assertThat(getData(payload), equalTo(data.array())); + assertThat(getData(payload)).isEqualTo(data.array()); } @Test @@ -87,8 +85,8 @@ public class HttpTunnelPayloadTests { MockHttpServletResponse servletResponse = new MockHttpServletResponse(); HttpOutputMessage response = new ServletServerHttpResponse(servletResponse); payload.assignTo(response); - assertThat(servletResponse.getHeader("x-seq"), equalTo("2")); - assertThat(servletResponse.getContentAsString(), equalTo("hello")); + assertThat(servletResponse.getHeader("x-seq")).isEqualTo("2"); + assertThat(servletResponse.getContentAsString()).isEqualTo("hello"); } @Test @@ -96,7 +94,7 @@ public class HttpTunnelPayloadTests { MockHttpServletRequest servletRequest = new MockHttpServletRequest(); HttpInputMessage request = new ServletServerHttpRequest(servletRequest); HttpTunnelPayload payload = HttpTunnelPayload.get(request); - assertThat(payload, nullValue()); + assertThat(payload).isNull(); } @Test @@ -116,8 +114,8 @@ public class HttpTunnelPayloadTests { servletRequest.addHeader("x-seq", 123); HttpInputMessage request = new ServletServerHttpRequest(servletRequest); HttpTunnelPayload payload = HttpTunnelPayload.get(request); - assertThat(payload.getSequence(), equalTo(123L)); - assertThat(getData(payload), equalTo("hello".getBytes())); + assertThat(payload.getSequence()).isEqualTo(123L); + assertThat(getData(payload)).isEqualTo("hello".getBytes()); } @Test @@ -130,7 +128,7 @@ public class HttpTunnelPayloadTests { while (payloadData.hasRemaining()) { writeChannel.write(payloadData); } - assertThat(out.toByteArray(), equalTo("hello".getBytes())); + assertThat(out.toByteArray()).isEqualTo("hello".getBytes()); } @Test @@ -139,7 +137,7 @@ public class HttpTunnelPayloadTests { given(channel.read(any(ByteBuffer.class))) .willThrow(new SocketTimeoutException()); ByteBuffer payload = HttpTunnelPayload.getPayloadData(channel); - assertThat(payload, nullValue()); + assertThat(payload).isNull(); } private byte[] getData(HttpTunnelPayload payload) throws IOException { diff --git a/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/tunnel/server/HttpTunnelServerTests.java b/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/tunnel/server/HttpTunnelServerTests.java index 278743b4cf..2c8dd866c2 100644 --- a/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/tunnel/server/HttpTunnelServerTests.java +++ b/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/tunnel/server/HttpTunnelServerTests.java @@ -47,8 +47,7 @@ import org.springframework.http.server.ServletServerHttpResponse; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; -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.Matchers.anyInt; import static org.mockito.Mockito.mock; @@ -154,7 +153,7 @@ public class HttpTunnelServerTests { this.serverChannel.send("hello"); this.serverChannel.disconnect(); this.server.getServerThread().join(); - assertThat(this.servletResponse.getContentAsString(), equalTo("hello")); + assertThat(this.servletResponse.getContentAsString()).isEqualTo("hello"); this.serverChannel.verifyReceived("hello"); } @@ -193,7 +192,7 @@ public class HttpTunnelServerTests { this.server.handle(h1); this.serverChannel.disconnect(); this.server.getServerThread().join(); - assertThat(h1.getServletResponse().getStatus(), equalTo(410)); + assertThat(h1.getServletResponse().getStatus()).isEqualTo(410); } @Test @@ -204,8 +203,8 @@ public class HttpTunnelServerTests { h2.getServletRequest().addHeader("Content-Type", "application/x-disconnect"); this.server.handle(h2); this.server.getServerThread().join(); - assertThat(h1.getServletResponse().getStatus(), equalTo(410)); - assertThat(this.serverChannel.isOpen(), equalTo(false)); + assertThat(h1.getServletResponse().getStatus()).isEqualTo(410); + assertThat(this.serverChannel.isOpen()).isFalse(); } @Test @@ -217,7 +216,7 @@ public class HttpTunnelServerTests { MockHttpConnection h3 = new MockHttpConnection("2", 3); this.server.handle(h3); h1.waitForResponse(); - assertThat(h1.getServletResponse().getStatus(), equalTo(429)); + assertThat(h1.getServletResponse().getStatus()).isEqualTo(429); this.serverChannel.disconnect(); this.server.getServerThread().join(); } @@ -246,8 +245,8 @@ public class HttpTunnelServerTests { Thread.sleep(400); this.serverChannel.disconnect(); this.server.getServerThread().join(); - assertThat(h1.getServletResponse().getStatus(), equalTo(204)); - assertThat(h2.getServletResponse().getStatus(), equalTo(204)); + assertThat(h1.getServletResponse().getStatus()).isEqualTo(204); + assertThat(h2.getServletResponse().getStatus()).isEqualTo(204); } @Test @@ -258,7 +257,7 @@ public class HttpTunnelServerTests { this.server.handle(h1); this.serverChannel.send("hello"); this.server.getServerThread().join(); - assertThat(this.serverChannel.isOpen(), equalTo(false)); + assertThat(this.serverChannel.isOpen()).isFalse(); } @Test @@ -273,9 +272,9 @@ public class HttpTunnelServerTests { HttpConnection connection = new HttpConnection(this.request, this.response); connection.waitForResponse(); connection.respond(new HttpTunnelPayload(1, ByteBuffer.wrap("hello".getBytes()))); - assertThat(this.servletResponse.getStatus(), equalTo(200)); - assertThat(this.servletResponse.getContentAsString(), equalTo("hello")); - assertThat(this.servletResponse.getHeader(SEQ_HEADER), equalTo("1")); + assertThat(this.servletResponse.getStatus()).isEqualTo(200); + assertThat(this.servletResponse.getContentAsString()).isEqualTo("hello"); + assertThat(this.servletResponse.getHeader(SEQ_HEADER)).isEqualTo("1"); } @Test @@ -283,8 +282,8 @@ public class HttpTunnelServerTests { HttpConnection connection = new HttpConnection(this.request, this.response); connection.waitForResponse(); connection.respond(HttpStatus.I_AM_A_TEAPOT); - assertThat(this.servletResponse.getStatus(), equalTo(418)); - assertThat(this.servletResponse.getContentLength(), equalTo(0)); + assertThat(this.servletResponse.getStatus()).isEqualTo(418); + assertThat(this.servletResponse.getContentLength()).isEqualTo(0); } @Test @@ -322,19 +321,19 @@ public class HttpTunnelServerTests { }; connectionThread.start(); - assertThat(responded.get(), equalTo(false)); + assertThat(responded.get()).isFalse(); Thread.sleep(sleepBeforeResponse); connection.respond(HttpStatus.NO_CONTENT); connectionThread.join(); - assertThat(responded.get(), equalTo(true)); + assertThat(responded.get()).isTrue(); } @Test public void httpConnectionRunning() throws Exception { HttpConnection connection = new HttpConnection(this.request, this.response); - assertThat(connection.isOlderThan(100), equalTo(false)); + assertThat(connection.isOlderThan(100)).isFalse(); Thread.sleep(200); - assertThat(connection.isOlderThan(100), equalTo(true)); + assertThat(connection.isOlderThan(100)).isTrue(); } /** @@ -374,7 +373,7 @@ public class HttpTunnelServerTests { public void verifyReceived(byte[] expected) { synchronized (this.written) { - assertThat(this.written.toByteArray(), equalTo(expected)); + assertThat(this.written.toByteArray()).isEqualTo(expected); this.written.reset(); } } @@ -466,8 +465,8 @@ public class HttpTunnelServerTests { throws Exception { waitForServletResponse(); MockHttpServletResponse resp = getServletResponse(); - assertThat(resp.getContentAsString(), equalTo(expectedContent)); - assertThat(resp.getHeader(SEQ_HEADER), equalTo(String.valueOf(expectedSeq))); + assertThat(resp.getContentAsString()).isEqualTo(expectedContent); + assertThat(resp.getHeader(SEQ_HEADER)).isEqualTo(String.valueOf(expectedSeq)); } public void waitForServletResponse() throws InterruptedException { diff --git a/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/tunnel/server/SocketTargetServerConnectionTests.java b/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/tunnel/server/SocketTargetServerConnectionTests.java index 0d89052918..fde973ac19 100644 --- a/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/tunnel/server/SocketTargetServerConnectionTests.java +++ b/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/tunnel/server/SocketTargetServerConnectionTests.java @@ -29,10 +29,7 @@ import org.junit.Test; import org.springframework.util.SocketUtils; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.greaterThanOrEqualTo; -import static org.hamcrest.Matchers.lessThan; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.fail; /** @@ -65,7 +62,7 @@ public class SocketTargetServerConnectionTests { ByteChannel channel = this.connection.open(DEFAULT_TIMEOUT); ByteBuffer buffer = ByteBuffer.allocate(5); channel.read(buffer); - assertThat(buffer.array(), equalTo("hello".getBytes())); + assertThat(buffer.array()).isEqualTo("hello".getBytes()); } @Test @@ -91,8 +88,8 @@ public class SocketTargetServerConnectionTests { catch (SocketTimeoutException ex) { // Expected long runTime = System.currentTimeMillis() - startTime; - assertThat(runTime, greaterThanOrEqualTo(10L)); - assertThat(runTime, lessThan(10000L)); + assertThat(runTime).isGreaterThanOrEqualTo(10L); + assertThat(runTime).isLessThan(10000L); } } @@ -134,7 +131,7 @@ public class SocketTargetServerConnectionTests { public void closeAndVerify() throws InterruptedException { close(); - assertThat(this.actualRead.array(), equalTo(this.expect)); + assertThat(this.actualRead.array()).isEqualTo(this.expect); } public void close() throws InterruptedException { diff --git a/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/tunnel/server/StaticPortProviderTests.java b/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/tunnel/server/StaticPortProviderTests.java index d60a82f8f6..92e8b83634 100644 --- a/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/tunnel/server/StaticPortProviderTests.java +++ b/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/tunnel/server/StaticPortProviderTests.java @@ -20,8 +20,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 StaticPortProvider}. @@ -43,7 +42,7 @@ public class StaticPortProviderTests { @Test public void getPort() throws Exception { StaticPortProvider provider = new StaticPortProvider(123); - assertThat(provider.getPort(), equalTo(123)); + assertThat(provider.getPort()).isEqualTo(123); } } From 00cfe1d054d62b9713e3ea151c7efe38b466fe00 Mon Sep 17 00:00:00 2001 From: Phillip Webb Date: Sat, 6 Feb 2016 14:53:00 -0800 Subject: [PATCH 05/10] Use AssertJ in spring-boot-tools See gh-5083 --- .../AbstractConfigurationMetadataTests.java | 25 +- ...ionMetadataRepositoryJsonBuilderTests.java | 49 +- .../DescriptionExtractorTests.java | 14 +- .../JsonReaderTests.java | 103 +++-- ...ationMetadataAnnotationProcessorTests.java | 432 +++++++++--------- .../ConfigurationMetadataMatchers.java | 416 ----------------- .../boot/configurationprocessor/Metadata.java | 401 ++++++++++++++++ ...figurationMetadataAnnotationProcessor.java | 2 + .../AbstractFieldValuesProcessorTests.java | 73 ++- .../metadata/ConfigurationMetadataTests.java | 22 +- .../metadata/JsonMarshallerTests.java | 39 +- .../tools/DefaultLaunchScriptTests.java | 24 +- .../boot/loader/tools/FileUtilsTests.java | 25 +- .../boot/loader/tools/JvmUtilsTests.java | 8 +- .../boot/loader/tools/LayoutsTests.java | 71 ++- .../loader/tools/MainClassFinderTests.java | 21 +- .../boot/loader/tools/RepackagerTests.java | 126 +++-- .../ExecutableArchiveLauncherTests.java | 7 +- .../InputArgumentsJavaAgentDetectorTests.java | 25 +- .../loader/LaunchedURLClassLoaderTests.java | 25 +- .../boot/loader/PropertiesLauncherTests.java | 63 ++- .../boot/loader/WarLauncherTests.java | 27 +- .../loader/archive/ExplodedArchiveTests.java | 46 +- .../loader/archive/JarFileArchiveTests.java | 28 +- .../data/ByteArrayRandomAccessDataTests.java | 21 +- .../data/RandomAccessDataFileTests.java | 74 ++- .../boot/loader/jar/AsciiBytesTests.java | 76 ++- .../jar/CentralDirectoryParserTests.java | 31 +- .../boot/loader/jar/JarFileTests.java | 223 +++++---- .../loader/util/SystemPropertyUtilsTests.java | 16 +- .../boot/maven/ArtifactsLibrariesTests.java | 15 +- .../boot/maven/DependencyFilterMojoTests.java | 11 +- .../boot/maven/ExcludeFilterTests.java | 29 +- .../boot/maven/IncludeFilterTests.java | 23 +- ...ertiesMergingResourceTransformerTests.java | 15 +- .../boot/maven/RunArgumentsTests.java | 35 +- .../springframework/boot/maven/Verify.java | 87 ++-- 37 files changed, 1326 insertions(+), 1402 deletions(-) delete mode 100644 spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/ConfigurationMetadataMatchers.java create mode 100644 spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/Metadata.java diff --git a/spring-boot-tools/spring-boot-configuration-metadata/src/test/java/org/springframework/boot/configurationmetadata/AbstractConfigurationMetadataTests.java b/spring-boot-tools/spring-boot-configuration-metadata/src/test/java/org/springframework/boot/configurationmetadata/AbstractConfigurationMetadataTests.java index 1af015327f..afd39de0fb 100644 --- a/spring-boot-tools/spring-boot-configuration-metadata/src/test/java/org/springframework/boot/configurationmetadata/AbstractConfigurationMetadataTests.java +++ b/spring-boot-tools/spring-boot-configuration-metadata/src/test/java/org/springframework/boot/configurationmetadata/AbstractConfigurationMetadataTests.java @@ -25,8 +25,7 @@ import org.junit.rules.ExpectedException; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.Resource; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.assertj.core.api.Assertions.assertThat; /** * Base for configuration meta-data tests. @@ -40,25 +39,25 @@ public abstract class AbstractConfigurationMetadataTests { protected void assertSource(ConfigurationMetadataSource actual, String groupId, String type, String sourceType) { - assertNotNull(actual); - assertEquals(groupId, actual.getGroupId()); - assertEquals(type, actual.getType()); - assertEquals(sourceType, actual.getSourceType()); + assertThat(actual).isNotNull(); + assertThat(actual.getGroupId()).isEqualTo(groupId); + assertThat(actual.getType()).isEqualTo(type); + assertThat(actual.getSourceType()).isEqualTo(sourceType); } protected void assertProperty(ConfigurationMetadataProperty actual, String id, String name, Class type, Object defaultValue) { - assertNotNull(actual); - assertEquals(id, actual.getId()); - assertEquals(name, actual.getName()); + assertThat(actual).isNotNull(); + assertThat(actual.getId()).isEqualTo(id); + assertThat(actual.getName()).isEqualTo(name); String typeName = type != null ? type.getName() : null; - assertEquals(typeName, actual.getType()); - assertEquals(defaultValue, actual.getDefaultValue()); + assertThat(actual.getType()).isEqualTo(typeName); + assertThat(actual.getDefaultValue()).isEqualTo(defaultValue); } protected void assertItem(ConfigurationMetadataItem actual, String sourceType) { - assertNotNull(actual); - assertEquals(sourceType, actual.getSourceType()); + assertThat(actual).isNotNull(); + assertThat(actual.getSourceType()).isEqualTo(sourceType); } protected InputStream getInputStreamFor(String name) throws IOException { diff --git a/spring-boot-tools/spring-boot-configuration-metadata/src/test/java/org/springframework/boot/configurationmetadata/ConfigurationMetadataRepositoryJsonBuilderTests.java b/spring-boot-tools/spring-boot-configuration-metadata/src/test/java/org/springframework/boot/configurationmetadata/ConfigurationMetadataRepositoryJsonBuilderTests.java index 1107e51ce9..068412e8a1 100644 --- a/spring-boot-tools/spring-boot-configuration-metadata/src/test/java/org/springframework/boot/configurationmetadata/ConfigurationMetadataRepositoryJsonBuilderTests.java +++ b/spring-boot-tools/spring-boot-configuration-metadata/src/test/java/org/springframework/boot/configurationmetadata/ConfigurationMetadataRepositoryJsonBuilderTests.java @@ -22,9 +22,7 @@ import java.util.Map; import org.junit.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link ConfigurationMetadataRepository}. @@ -47,10 +45,10 @@ public class ConfigurationMetadataRepositoryJsonBuilderTests ConfigurationMetadataRepository repo = ConfigurationMetadataRepositoryJsonBuilder .create(foo).build(); validateFoo(repo); - assertEquals(1, repo.getAllGroups().size()); + assertThat(repo.getAllGroups()).hasSize(1); contains(repo.getAllProperties(), "spring.foo.name", "spring.foo.description", "spring.foo.counter"); - assertEquals(3, repo.getAllProperties().size()); + assertThat(repo.getAllProperties()).hasSize(3); } finally { foo.close(); @@ -66,11 +64,11 @@ public class ConfigurationMetadataRepositoryJsonBuilderTests .create(foo, bar).build(); validateFoo(repo); validateBar(repo); - assertEquals(2, repo.getAllGroups().size()); + assertThat(repo.getAllGroups()).hasSize(2); contains(repo.getAllProperties(), "spring.foo.name", "spring.foo.description", "spring.foo.counter", "spring.bar.name", "spring.bar.description", "spring.bar.counter"); - assertEquals(6, repo.getAllProperties().size()); + assertThat(repo.getAllProperties()).hasSize(6); } finally { foo.close(); @@ -86,11 +84,11 @@ public class ConfigurationMetadataRepositoryJsonBuilderTests ConfigurationMetadataRepository repo = ConfigurationMetadataRepositoryJsonBuilder .create(foo, root).build(); validateFoo(repo); - assertEquals(2, repo.getAllGroups().size()); + assertThat(repo.getAllGroups()).hasSize(2); contains(repo.getAllProperties(), "spring.foo.name", "spring.foo.description", "spring.foo.counter", "spring.root.name", "spring.root2.name"); - assertEquals(5, repo.getAllProperties().size()); + assertThat(repo.getAllProperties()).hasSize(5); } finally { foo.close(); @@ -105,17 +103,17 @@ public class ConfigurationMetadataRepositoryJsonBuilderTests try { ConfigurationMetadataRepository repo = ConfigurationMetadataRepositoryJsonBuilder .create(foo, foo2).build(); - assertEquals(1, repo.getAllGroups().size()); + assertThat(repo.getAllGroups()).hasSize(1); ConfigurationMetadataGroup group = repo.getAllGroups().get("spring.foo"); contains(group.getSources(), "org.acme.Foo", "org.acme.Foo2", "org.springframework.boot.FooProperties"); - assertEquals(3, group.getSources().size()); + assertThat(group.getSources()).hasSize(3); contains(group.getProperties(), "spring.foo.name", "spring.foo.description", "spring.foo.counter", "spring.foo.enabled", "spring.foo.type"); - assertEquals(5, group.getProperties().size()); + assertThat(group.getProperties()).hasSize(5); contains(repo.getAllProperties(), "spring.foo.name", "spring.foo.description", "spring.foo.counter", "spring.foo.enabled", "spring.foo.type"); - assertEquals(5, repo.getAllProperties().size()); + assertThat(repo.getAllProperties()).hasSize(5); } finally { foo.close(); @@ -138,11 +136,11 @@ public class ConfigurationMetadataRepositoryJsonBuilderTests validateFoo(secondRepo); validateBar(secondRepo); // first repo not impacted by second build - assertNotEquals(firstRepo, secondRepo); - assertEquals(1, firstRepo.getAllGroups().size()); - assertEquals(3, firstRepo.getAllProperties().size()); - assertEquals(2, secondRepo.getAllGroups().size()); - assertEquals(6, secondRepo.getAllProperties().size()); + assertThat(secondRepo).isNotEqualTo(firstRepo); + assertThat(firstRepo.getAllGroups()).hasSize(1); + assertThat(firstRepo.getAllProperties()).hasSize(3); + assertThat(secondRepo.getAllGroups()).hasSize(2); + assertThat(secondRepo.getAllProperties()).hasSize(6); } finally { foo.close(); @@ -156,11 +154,11 @@ public class ConfigurationMetadataRepositoryJsonBuilderTests "org.springframework.boot.FooProperties"); ConfigurationMetadataSource source = group.getSources().get("org.acme.Foo"); contains(source.getProperties(), "spring.foo.name", "spring.foo.description"); - assertEquals(2, source.getProperties().size()); + assertThat(source.getProperties()).hasSize(2); ConfigurationMetadataSource source2 = group.getSources() .get("org.springframework.boot.FooProperties"); contains(source2.getProperties(), "spring.foo.name", "spring.foo.counter"); - assertEquals(2, source2.getProperties().size()); + assertThat(source2.getProperties()).hasSize(2); validatePropertyHints(repo.getAllProperties().get("spring.foo.name"), 0, 0); validatePropertyHints(repo.getAllProperties().get("spring.foo.description"), 0, 0); @@ -173,11 +171,11 @@ public class ConfigurationMetadataRepositoryJsonBuilderTests "org.springframework.boot.BarProperties"); ConfigurationMetadataSource source = group.getSources().get("org.acme.Bar"); contains(source.getProperties(), "spring.bar.name", "spring.bar.description"); - assertEquals(2, source.getProperties().size()); + assertThat(source.getProperties()).hasSize(2); ConfigurationMetadataSource source2 = group.getSources() .get("org.springframework.boot.BarProperties"); contains(source2.getProperties(), "spring.bar.name", "spring.bar.counter"); - assertEquals(2, source2.getProperties().size()); + assertThat(source2.getProperties()).hasSize(2); validatePropertyHints(repo.getAllProperties().get("spring.bar.name"), 0, 0); validatePropertyHints(repo.getAllProperties().get("spring.bar.description"), 2, 2); @@ -186,14 +184,13 @@ public class ConfigurationMetadataRepositoryJsonBuilderTests private void validatePropertyHints(ConfigurationMetadataProperty property, int valueHints, int valueProviders) { - assertEquals(valueHints, property.getValueHints().size()); - assertEquals(valueProviders, property.getValueHints().size()); + assertThat(property.getValueHints().size()).isEqualTo(valueHints); + assertThat(property.getValueHints().size()).isEqualTo(valueProviders); } private void contains(Map source, String... keys) { for (String key : keys) { - assertTrue("Item '" + key + "' not found. Got " + source.keySet(), - source.containsKey(key)); + assertThat(source).containsKey(key); } } diff --git a/spring-boot-tools/spring-boot-configuration-metadata/src/test/java/org/springframework/boot/configurationmetadata/DescriptionExtractorTests.java b/spring-boot-tools/spring-boot-configuration-metadata/src/test/java/org/springframework/boot/configurationmetadata/DescriptionExtractorTests.java index e1ba457684..e355e48b6b 100644 --- a/spring-boot-tools/spring-boot-configuration-metadata/src/test/java/org/springframework/boot/configurationmetadata/DescriptionExtractorTests.java +++ b/spring-boot-tools/spring-boot-configuration-metadata/src/test/java/org/springframework/boot/configurationmetadata/DescriptionExtractorTests.java @@ -18,7 +18,7 @@ package org.springframework.boot.configurationmetadata; import org.junit.Test; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link DescriptionExtractor}. @@ -35,39 +35,39 @@ public class DescriptionExtractorTests { public void extractShortDescription() { String description = this.extractor .getShortDescription("My short " + "description. More stuff."); - assertEquals("My short description.", description); + assertThat(description).isEqualTo("My short description."); } @Test public void extractShortDescriptionNewLineBeforeDot() { String description = this.extractor.getShortDescription( "My short" + NEW_LINE + "description." + NEW_LINE + "More stuff."); - assertEquals("My short description.", description); + assertThat(description).isEqualTo("My short description."); } @Test public void extractShortDescriptionNewLineBeforeDotWithSpaces() { String description = this.extractor.getShortDescription( "My short " + NEW_LINE + " description. " + NEW_LINE + "More stuff."); - assertEquals("My short description.", description); + assertThat(description).isEqualTo("My short description."); } @Test public void extractShortDescriptionNoDot() { String description = this.extractor.getShortDescription("My short description"); - assertEquals("My short description", description); + assertThat(description).isEqualTo("My short description"); } @Test public void extractShortDescriptionNoDotMultipleLines() { String description = this.extractor .getShortDescription("My short description " + NEW_LINE + " More stuff"); - assertEquals("My short description", description); + assertThat(description).isEqualTo("My short description"); } @Test public void extractShortDescriptionNull() { - assertEquals(null, this.extractor.getShortDescription(null)); + assertThat(this.extractor.getShortDescription(null)).isEqualTo(null); } } diff --git a/spring-boot-tools/spring-boot-configuration-metadata/src/test/java/org/springframework/boot/configurationmetadata/JsonReaderTests.java b/spring-boot-tools/spring-boot-configuration-metadata/src/test/java/org/springframework/boot/configurationmetadata/JsonReaderTests.java index ce75549d21..51b0f94678 100644 --- a/spring-boot-tools/spring-boot-configuration-metadata/src/test/java/org/springframework/boot/configurationmetadata/JsonReaderTests.java +++ b/spring-boot-tools/spring-boot-configuration-metadata/src/test/java/org/springframework/boot/configurationmetadata/JsonReaderTests.java @@ -23,10 +23,7 @@ import java.util.List; import org.json.JSONException; import org.junit.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link JsonReader} @@ -42,8 +39,8 @@ public class JsonReaderTests extends AbstractConfigurationMetadataTests { @Test public void emptyMetadata() throws IOException { RawConfigurationMetadata rawMetadata = readFor("empty"); - assertEquals(0, rawMetadata.getSources().size()); - assertEquals(0, rawMetadata.getItems().size()); + assertThat(rawMetadata.getSources()).isEmpty(); + assertThat(rawMetadata.getItems()).isEmpty(); } @Test @@ -56,17 +53,17 @@ public class JsonReaderTests extends AbstractConfigurationMetadataTests { public void simpleMetadata() throws IOException { RawConfigurationMetadata rawMetadata = readFor("foo"); List sources = rawMetadata.getSources(); - assertEquals(2, sources.size()); + assertThat(sources).hasSize(2); List items = rawMetadata.getItems(); - assertEquals(4, items.size()); + assertThat(items).hasSize(4); List hints = rawMetadata.getHints(); - assertEquals(1, hints.size()); + assertThat(hints).hasSize(1); ConfigurationMetadataSource source = sources.get(0); assertSource(source, "spring.foo", "org.acme.Foo", "org.acme.config.FooApp"); - assertEquals("foo()", source.getSourceMethod()); - assertEquals("This is Foo.", source.getDescription()); - assertEquals("This is Foo.", source.getShortDescription()); + assertThat(source.getSourceMethod()).isEqualTo("foo()"); + assertThat(source.getDescription()).isEqualTo("This is Foo."); + assertThat(source.getShortDescription()).isEqualTo("This is Foo."); ConfigurationMetadataItem item = items.get(0); assertProperty(item, "spring.foo.name", "name", String.class, null); @@ -74,61 +71,62 @@ public class JsonReaderTests extends AbstractConfigurationMetadataTests { ConfigurationMetadataItem item2 = items.get(1); assertProperty(item2, "spring.foo.description", "description", String.class, "FooBar"); - assertEquals("Foo description.", item2.getDescription()); - assertEquals("Foo description.", item2.getShortDescription()); - assertNull(item2.getSourceMethod()); + assertThat(item2.getDescription()).isEqualTo("Foo description."); + assertThat(item2.getShortDescription()).isEqualTo("Foo description."); + assertThat(item2.getSourceMethod()).isNull(); assertItem(item2, "org.acme.Foo"); ConfigurationMetadataHint hint = hints.get(0); - assertEquals("spring.foo.counter", hint.getId()); - assertEquals(1, hint.getValueHints().size()); + assertThat(hint.getId()).isEqualTo("spring.foo.counter"); + assertThat(hint.getValueHints()).hasSize(1); ValueHint valueHint = hint.getValueHints().get(0); - assertEquals(42, valueHint.getValue()); - assertEquals("Because that's the answer to any question, choose it. \nReally.", - valueHint.getDescription()); - assertEquals("Because that's the answer to any question, choose it.", - valueHint.getShortDescription()); - assertEquals(1, hint.getValueProviders().size()); + assertThat(valueHint.getValue()).isEqualTo(42); + assertThat(valueHint.getDescription()).isEqualTo( + "Because that's the answer to any question, choose it. \nReally."); + assertThat(valueHint.getShortDescription()) + .isEqualTo("Because that's the answer to any question, choose it."); + assertThat(hint.getValueProviders()).hasSize(1); ValueProvider valueProvider = hint.getValueProviders().get(0); - assertEquals("handle-as", valueProvider.getName()); - assertEquals(1, valueProvider.getParameters().size()); - assertEquals(Integer.class.getName(), - valueProvider.getParameters().get("target")); + assertThat(valueProvider.getName()).isEqualTo("handle-as"); + assertThat(valueProvider.getParameters()).hasSize(1); + assertThat(valueProvider.getParameters().get("target")) + .isEqualTo(Integer.class.getName()); } @Test public void metadataHints() throws IOException { RawConfigurationMetadata rawMetadata = readFor("bar"); List hints = rawMetadata.getHints(); - assertEquals(1, hints.size()); + assertThat(hints).hasSize(1); ConfigurationMetadataHint hint = hints.get(0); - assertEquals("spring.bar.description", hint.getId()); - assertEquals(2, hint.getValueHints().size()); + assertThat(hint.getId()).isEqualTo("spring.bar.description"); + assertThat(hint.getValueHints()).hasSize(2); ValueHint valueHint = hint.getValueHints().get(0); - assertEquals("one", valueHint.getValue()); - assertEquals("One.", valueHint.getDescription()); + assertThat(valueHint.getValue()).isEqualTo("one"); + assertThat(valueHint.getDescription()).isEqualTo("One."); ValueHint valueHint2 = hint.getValueHints().get(1); - assertEquals("two", valueHint2.getValue()); - assertEquals(null, valueHint2.getDescription()); + assertThat(valueHint2.getValue()).isEqualTo("two"); + assertThat(valueHint2.getDescription()).isEqualTo(null); - assertEquals(2, hint.getValueProviders().size()); + assertThat(hint.getValueProviders()).hasSize(2); ValueProvider valueProvider = hint.getValueProviders().get(0); - assertEquals("handle-as", valueProvider.getName()); - assertEquals(1, valueProvider.getParameters().size()); - assertEquals(String.class.getName(), valueProvider.getParameters().get("target")); + assertThat(valueProvider.getName()).isEqualTo("handle-as"); + assertThat(valueProvider.getParameters()).hasSize(1); + assertThat(valueProvider.getParameters().get("target")) + .isEqualTo(String.class.getName()); ValueProvider valueProvider2 = hint.getValueProviders().get(1); - assertEquals("any", valueProvider2.getName()); - assertEquals(0, valueProvider2.getParameters().size()); + assertThat(valueProvider2.getName()).isEqualTo("any"); + assertThat(valueProvider2.getParameters()).isEmpty(); } @Test public void rootMetadata() throws IOException { RawConfigurationMetadata rawMetadata = readFor("root"); List sources = rawMetadata.getSources(); - assertEquals(0, sources.size()); + assertThat(sources).isEmpty(); List items = rawMetadata.getItems(); - assertEquals(2, items.size()); + assertThat(items).hasSize(2); ConfigurationMetadataItem item = items.get(0); assertProperty(item, "spring.root.name", "spring.root.name", String.class, null); } @@ -137,27 +135,28 @@ public class JsonReaderTests extends AbstractConfigurationMetadataTests { public void deprecatedMetadata() throws IOException { RawConfigurationMetadata rawMetadata = readFor("deprecated"); List items = rawMetadata.getItems(); - assertEquals(3, items.size()); + assertThat(items).hasSize(3); ConfigurationMetadataItem item = items.get(0); assertProperty(item, "server.port", "server.port", Integer.class, null); - assertTrue(item.isDeprecated()); - assertEquals("Server namespace has moved to spring.server", - item.getDeprecation().getReason()); - assertEquals("server.spring.port", item.getDeprecation().getReplacement()); + assertThat(item.isDeprecated()).isTrue(); + assertThat(item.getDeprecation().getReason()) + .isEqualTo("Server namespace has moved to spring.server"); + assertThat(item.getDeprecation().getReplacement()) + .isEqualTo("server.spring.port"); ConfigurationMetadataItem item2 = items.get(1); assertProperty(item2, "server.cluster-name", "server.cluster-name", String.class, null); - assertTrue(item2.isDeprecated()); - assertEquals(null, item2.getDeprecation().getReason()); - assertEquals(null, item2.getDeprecation().getReplacement()); + assertThat(item2.isDeprecated()).isTrue(); + assertThat(item2.getDeprecation().getReason()).isEqualTo(null); + assertThat(item2.getDeprecation().getReplacement()).isEqualTo(null); ConfigurationMetadataItem item3 = items.get(2); assertProperty(item3, "spring.server.name", "spring.server.name", String.class, null); - assertFalse(item3.isDeprecated()); - assertEquals(null, item3.getDeprecation()); + assertThat(item3.isDeprecated()).isFalse(); + assertThat(item3.getDeprecation()).isEqualTo(null); } RawConfigurationMetadata readFor(String path) throws IOException { diff --git a/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/ConfigurationMetadataAnnotationProcessorTests.java b/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/ConfigurationMetadataAnnotationProcessorTests.java index 99fa18ad0d..e19c71eaa5 100644 --- a/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/ConfigurationMetadataAnnotationProcessorTests.java +++ b/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/ConfigurationMetadataAnnotationProcessorTests.java @@ -63,16 +63,7 @@ import org.springframework.boot.configurationsample.specific.InnerClassRootConfi import org.springframework.boot.configurationsample.specific.SimplePojo; import org.springframework.util.FileCopyUtils; -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.Matchers.empty; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.not; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; -import static org.springframework.boot.configurationprocessor.ConfigurationMetadataMatchers.containsGroup; -import static org.springframework.boot.configurationprocessor.ConfigurationMetadataMatchers.containsHint; -import static org.springframework.boot.configurationprocessor.ConfigurationMetadataMatchers.containsProperty; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link ConfigurationMetadataAnnotationProcessor}. @@ -100,80 +91,88 @@ public class ConfigurationMetadataAnnotationProcessorTests { @Test public void notAnnotated() throws Exception { ConfigurationMetadata metadata = compile(NotAnnotated.class); - assertThat("No config metadata file should have been generated when " - + "no metadata is discovered", metadata.getItems(), empty()); + assertThat(metadata.getItems()).isEmpty(); } @Test public void simpleProperties() throws Exception { ConfigurationMetadata metadata = compile(SimpleProperties.class); - assertThat(metadata, containsGroup("simple").fromSource(SimpleProperties.class)); - assertThat(metadata, - containsProperty("simple.the-name", String.class) - .fromSource(SimpleProperties.class) - .withDescription("The name of this simple properties.") - .withDefaultValue(is("boot")).withDeprecation(null, null)); - assertThat(metadata, - containsProperty("simple.flag", Boolean.class) - .fromSource(SimpleProperties.class) - .withDescription("A simple flag.").withDeprecation(null, null)); - assertThat(metadata, containsProperty("simple.comparator")); - assertThat(metadata, not(containsProperty("simple.counter"))); - assertThat(metadata, not(containsProperty("simple.size"))); + assertThat(metadata) + .has(Metadata.withGroup("simple").fromSource(SimpleProperties.class)); + assertThat(metadata).has(Metadata.withProperty("simple.the-name", String.class) + .fromSource(SimpleProperties.class) + .withDescription("The name of this simple properties.") + .withDefaultValue("boot").withDeprecation(null, null)); + assertThat(metadata).has(Metadata.withProperty("simple.flag", Boolean.class) + .fromSource(SimpleProperties.class).withDescription("A simple flag.") + .withDeprecation(null, null)); + assertThat(metadata).has(Metadata.withProperty("simple.comparator")); + assertThat(metadata).doesNotHave(Metadata.withProperty("simple.counter")); + assertThat(metadata).doesNotHave(Metadata.withProperty("simple.size")); } @Test public void simplePrefixValueProperties() throws Exception { ConfigurationMetadata metadata = compile(SimplePrefixValueProperties.class); - assertThat(metadata, - containsGroup("simple").fromSource(SimplePrefixValueProperties.class)); - assertThat(metadata, containsProperty("simple.name", String.class) + assertThat(metadata).has(Metadata.withGroup("simple") + .fromSource(SimplePrefixValueProperties.class)); + assertThat(metadata).has(Metadata.withProperty("simple.name", String.class) .fromSource(SimplePrefixValueProperties.class)); } @Test public void simpleTypeProperties() throws Exception { ConfigurationMetadata metadata = compile(SimpleTypeProperties.class); - assertThat(metadata, - containsGroup("simple.type").fromSource(SimpleTypeProperties.class)); - assertThat(metadata, containsProperty("simple.type.my-string", String.class)); - assertThat(metadata, containsProperty("simple.type.my-byte", Byte.class)); - assertThat(metadata, - containsProperty("simple.type.my-primitive-byte", Byte.class)); - assertThat(metadata, containsProperty("simple.type.my-char", Character.class)); - assertThat(metadata, - containsProperty("simple.type.my-primitive-char", Character.class)); - assertThat(metadata, containsProperty("simple.type.my-boolean", Boolean.class)); - assertThat(metadata, - containsProperty("simple.type.my-primitive-boolean", Boolean.class)); - assertThat(metadata, containsProperty("simple.type.my-short", Short.class)); - assertThat(metadata, - containsProperty("simple.type.my-primitive-short", Short.class)); - assertThat(metadata, containsProperty("simple.type.my-integer", Integer.class)); - assertThat(metadata, - containsProperty("simple.type.my-primitive-integer", Integer.class)); - assertThat(metadata, containsProperty("simple.type.my-long", Long.class)); - assertThat(metadata, - containsProperty("simple.type.my-primitive-long", Long.class)); - assertThat(metadata, containsProperty("simple.type.my-double", Double.class)); - assertThat(metadata, - containsProperty("simple.type.my-primitive-double", Double.class)); - assertThat(metadata, containsProperty("simple.type.my-float", Float.class)); - assertThat(metadata, - containsProperty("simple.type.my-primitive-float", Float.class)); - assertThat(metadata.getItems().size(), equalTo(18)); + assertThat(metadata).has( + Metadata.withGroup("simple.type").fromSource(SimpleTypeProperties.class)); + assertThat(metadata) + .has(Metadata.withProperty("simple.type.my-string", String.class)); + assertThat(metadata) + .has(Metadata.withProperty("simple.type.my-byte", Byte.class)); + assertThat(metadata) + .has(Metadata.withProperty("simple.type.my-primitive-byte", Byte.class)); + assertThat(metadata) + .has(Metadata.withProperty("simple.type.my-char", Character.class)); + assertThat(metadata).has( + Metadata.withProperty("simple.type.my-primitive-char", Character.class)); + assertThat(metadata) + .has(Metadata.withProperty("simple.type.my-boolean", Boolean.class)); + assertThat(metadata).has( + Metadata.withProperty("simple.type.my-primitive-boolean", Boolean.class)); + assertThat(metadata) + .has(Metadata.withProperty("simple.type.my-short", Short.class)); + assertThat(metadata).has( + Metadata.withProperty("simple.type.my-primitive-short", Short.class)); + assertThat(metadata) + .has(Metadata.withProperty("simple.type.my-integer", Integer.class)); + assertThat(metadata).has( + Metadata.withProperty("simple.type.my-primitive-integer", Integer.class)); + assertThat(metadata) + .has(Metadata.withProperty("simple.type.my-long", Long.class)); + assertThat(metadata) + .has(Metadata.withProperty("simple.type.my-primitive-long", Long.class)); + assertThat(metadata) + .has(Metadata.withProperty("simple.type.my-double", Double.class)); + assertThat(metadata).has( + Metadata.withProperty("simple.type.my-primitive-double", Double.class)); + assertThat(metadata) + .has(Metadata.withProperty("simple.type.my-float", Float.class)); + assertThat(metadata).has( + Metadata.withProperty("simple.type.my-primitive-float", Float.class)); + assertThat(metadata.getItems().size()).isEqualTo(18); } @Test public void hierarchicalProperties() throws Exception { ConfigurationMetadata metadata = compile(HierarchicalProperties.class); - assertThat(metadata, - containsGroup("hierarchical").fromSource(HierarchicalProperties.class)); - assertThat(metadata, containsProperty("hierarchical.first", String.class) + assertThat(metadata).has(Metadata.withGroup("hierarchical") .fromSource(HierarchicalProperties.class)); - assertThat(metadata, containsProperty("hierarchical.second", String.class) + assertThat(metadata).has(Metadata.withProperty("hierarchical.first", String.class) .fromSource(HierarchicalProperties.class)); - assertThat(metadata, containsProperty("hierarchical.third", String.class) + assertThat(metadata) + .has(Metadata.withProperty("hierarchical.second", String.class) + .fromSource(HierarchicalProperties.class)); + assertThat(metadata).has(Metadata.withProperty("hierarchical.third", String.class) .fromSource(HierarchicalProperties.class)); } @@ -182,152 +181,157 @@ public class ConfigurationMetadataAnnotationProcessorTests { public void deprecatedProperties() throws Exception { Class type = org.springframework.boot.configurationsample.simple.DeprecatedProperties.class; ConfigurationMetadata metadata = compile(type); - assertThat(metadata, containsGroup("deprecated").fromSource(type)); - assertThat(metadata, containsProperty("deprecated.name", String.class) - .fromSource(type).withDeprecation(null, null)); - assertThat(metadata, containsProperty("deprecated.description", String.class) + assertThat(metadata).has(Metadata.withGroup("deprecated").fromSource(type)); + assertThat(metadata).has(Metadata.withProperty("deprecated.name", String.class) .fromSource(type).withDeprecation(null, null)); + assertThat(metadata) + .has(Metadata.withProperty("deprecated.description", String.class) + .fromSource(type).withDeprecation(null, null)); } @Test public void singleDeprecatedProperty() throws Exception { Class type = DeprecatedSingleProperty.class; ConfigurationMetadata metadata = compile(type); - assertThat(metadata, containsGroup("singledeprecated").fromSource(type)); - assertThat(metadata, containsProperty("singledeprecated.new-name", String.class) - .fromSource(type)); - assertThat(metadata, - containsProperty("singledeprecated.name", String.class).fromSource(type) - .withDeprecation("renamed", "singledeprecated.new-name")); + assertThat(metadata).has(Metadata.withGroup("singledeprecated").fromSource(type)); + assertThat(metadata) + .has(Metadata.withProperty("singledeprecated.new-name", String.class) + .fromSource(type)); + assertThat(metadata).has(Metadata + .withProperty("singledeprecated.name", String.class).fromSource(type) + .withDeprecation("renamed", "singledeprecated.new-name")); } @Test public void deprecatedOnUnrelatedSetter() throws Exception { Class type = DeprecatedUnrelatedMethodPojo.class; ConfigurationMetadata metadata = compile(type); - assertThat(metadata, containsGroup("not.deprecated").fromSource(type)); - assertThat(metadata, containsProperty("not.deprecated.counter", Integer.class) - .withNoDeprecation().fromSource(type)); - assertThat(metadata, containsProperty("not.deprecated.flag", Boolean.class) - .withNoDeprecation().fromSource(type)); + assertThat(metadata).has(Metadata.withGroup("not.deprecated").fromSource(type)); + assertThat(metadata) + .has(Metadata.withProperty("not.deprecated.counter", Integer.class) + .withNoDeprecation().fromSource(type)); + assertThat(metadata) + .has(Metadata.withProperty("not.deprecated.flag", Boolean.class) + .withNoDeprecation().fromSource(type)); } @Test public void boxingOnSetter() throws IOException { Class type = BoxingPojo.class; ConfigurationMetadata metadata = compile(type); - assertThat(metadata, containsGroup("boxing").fromSource(type)); - assertThat(metadata, - containsProperty("boxing.flag", Boolean.class).fromSource(type)); - assertThat(metadata, - containsProperty("boxing.counter", Integer.class).fromSource(type)); + assertThat(metadata).has(Metadata.withGroup("boxing").fromSource(type)); + assertThat(metadata).has( + Metadata.withProperty("boxing.flag", Boolean.class).fromSource(type)); + assertThat(metadata).has( + Metadata.withProperty("boxing.counter", Integer.class).fromSource(type)); } @Test public void parseCollectionConfig() throws Exception { ConfigurationMetadata metadata = compile(SimpleCollectionProperties.class); // getter and setter - assertThat(metadata, containsProperty("collection.integers-to-names", + assertThat(metadata).has(Metadata.withProperty("collection.integers-to-names", "java.util.Map")); - assertThat(metadata, containsProperty("collection.longs", + assertThat(metadata).has(Metadata.withProperty("collection.longs", "java.util.Collection")); - assertThat(metadata, - containsProperty("collection.floats", "java.util.List")); + assertThat(metadata).has(Metadata.withProperty("collection.floats", + "java.util.List")); // getter only - assertThat(metadata, containsProperty("collection.names-to-integers", + assertThat(metadata).has(Metadata.withProperty("collection.names-to-integers", "java.util.Map")); - assertThat(metadata, containsProperty("collection.bytes", + assertThat(metadata).has(Metadata.withProperty("collection.bytes", "java.util.Collection")); - assertThat(metadata, containsProperty("collection.doubles", + assertThat(metadata).has(Metadata.withProperty("collection.doubles", "java.util.List")); } @Test public void simpleMethodConfig() throws Exception { ConfigurationMetadata metadata = compile(SimpleMethodConfig.class); - assertThat(metadata, containsGroup("foo").fromSource(SimpleMethodConfig.class)); - assertThat(metadata, containsProperty("foo.name", String.class) + assertThat(metadata) + .has(Metadata.withGroup("foo").fromSource(SimpleMethodConfig.class)); + assertThat(metadata).has(Metadata.withProperty("foo.name", String.class) .fromSource(SimpleMethodConfig.Foo.class)); - assertThat(metadata, containsProperty("foo.flag", Boolean.class) + assertThat(metadata).has(Metadata.withProperty("foo.flag", Boolean.class) .fromSource(SimpleMethodConfig.Foo.class)); } @Test public void invalidMethodConfig() throws Exception { ConfigurationMetadata metadata = compile(InvalidMethodConfig.class); - assertThat(metadata, containsProperty("something.name", String.class) + assertThat(metadata).has(Metadata.withProperty("something.name", String.class) .fromSource(InvalidMethodConfig.class)); - assertThat(metadata, not(containsProperty("invalid.name"))); + assertThat(metadata).isNotEqualTo(Metadata.withProperty("invalid.name")); } @Test public void methodAndClassConfig() throws Exception { ConfigurationMetadata metadata = compile(MethodAndClassConfig.class); - assertThat(metadata, containsProperty("conflict.name", String.class) + assertThat(metadata).has(Metadata.withProperty("conflict.name", String.class) .fromSource(MethodAndClassConfig.Foo.class)); - assertThat(metadata, containsProperty("conflict.flag", Boolean.class) + assertThat(metadata).has(Metadata.withProperty("conflict.flag", Boolean.class) .fromSource(MethodAndClassConfig.Foo.class)); - assertThat(metadata, containsProperty("conflict.value", String.class) + assertThat(metadata).has(Metadata.withProperty("conflict.value", String.class) .fromSource(MethodAndClassConfig.class)); } @Test public void emptyTypeMethodConfig() throws Exception { ConfigurationMetadata metadata = compile(EmptyTypeMethodConfig.class); - assertThat(metadata, not(containsProperty("something.foo"))); + assertThat(metadata).isNotEqualTo(Metadata.withProperty("something.foo")); } @Test public void innerClassRootConfig() throws Exception { ConfigurationMetadata metadata = compile(InnerClassRootConfig.class); - assertThat(metadata, containsProperty("config.name")); + assertThat(metadata).has(Metadata.withProperty("config.name")); } @Test public void innerClassProperties() throws Exception { ConfigurationMetadata metadata = compile(InnerClassProperties.class); - assertThat(metadata, - containsGroup("config").fromSource(InnerClassProperties.class)); - assertThat(metadata, - containsGroup("config.first").ofType(InnerClassProperties.Foo.class) + assertThat(metadata) + .has(Metadata.withGroup("config").fromSource(InnerClassProperties.class)); + assertThat(metadata).has( + Metadata.withGroup("config.first").ofType(InnerClassProperties.Foo.class) .fromSource(InnerClassProperties.class)); - assertThat(metadata, containsProperty("config.first.name")); - assertThat(metadata, containsProperty("config.first.bar.name")); - assertThat(metadata, - containsGroup("config.the-second", InnerClassProperties.Foo.class) + assertThat(metadata).has(Metadata.withProperty("config.first.name")); + assertThat(metadata).has(Metadata.withProperty("config.first.bar.name")); + assertThat(metadata).has( + Metadata.withGroup("config.the-second", InnerClassProperties.Foo.class) .fromSource(InnerClassProperties.class)); - assertThat(metadata, containsProperty("config.the-second.name")); - assertThat(metadata, containsProperty("config.the-second.bar.name")); - assertThat(metadata, containsGroup("config.third").ofType(SimplePojo.class) - .fromSource(InnerClassProperties.class)); - assertThat(metadata, containsProperty("config.third.value")); - assertThat(metadata, containsProperty("config.fourth")); - assertThat(metadata, not(containsGroup("config.fourth"))); + assertThat(metadata).has(Metadata.withProperty("config.the-second.name")); + assertThat(metadata).has(Metadata.withProperty("config.the-second.bar.name")); + assertThat(metadata).has(Metadata.withGroup("config.third") + .ofType(SimplePojo.class).fromSource(InnerClassProperties.class)); + assertThat(metadata).has(Metadata.withProperty("config.third.value")); + assertThat(metadata).has(Metadata.withProperty("config.fourth")); + assertThat(metadata).isNotEqualTo(Metadata.withGroup("config.fourth")); } @Test public void innerClassAnnotatedGetterConfig() throws Exception { ConfigurationMetadata metadata = compile(InnerClassAnnotatedGetterConfig.class); - assertThat(metadata, containsProperty("specific.value")); - assertThat(metadata, containsProperty("foo.name")); - assertThat(metadata, not(containsProperty("specific.foo"))); + assertThat(metadata).has(Metadata.withProperty("specific.value")); + assertThat(metadata).has(Metadata.withProperty("foo.name")); + assertThat(metadata).isNotEqualTo(Metadata.withProperty("specific.foo")); } @Test public void builderPojo() throws IOException { ConfigurationMetadata metadata = compile(BuilderPojo.class); - assertThat(metadata, containsProperty("builder.name")); + assertThat(metadata).has(Metadata.withProperty("builder.name")); } @Test public void excludedTypesPojo() throws IOException { ConfigurationMetadata metadata = compile(ExcludedTypesPojo.class); - assertThat(metadata, containsProperty("excluded.name")); - assertThat(metadata, not(containsProperty("excluded.class-loader"))); - assertThat(metadata, not(containsProperty("excluded.data-source"))); - assertThat(metadata, not(containsProperty("excluded.print-writer"))); - assertThat(metadata, not(containsProperty("excluded.writer"))); - assertThat(metadata, not(containsProperty("excluded.writer-array"))); + assertThat(metadata).has(Metadata.withProperty("excluded.name")); + assertThat(metadata).isNotEqualTo(Metadata.withProperty("excluded.class-loader")); + assertThat(metadata).isNotEqualTo(Metadata.withProperty("excluded.data-source")); + assertThat(metadata).isNotEqualTo(Metadata.withProperty("excluded.print-writer")); + assertThat(metadata).isNotEqualTo(Metadata.withProperty("excluded.writer")); + assertThat(metadata).isNotEqualTo(Metadata.withProperty("excluded.writer-array")); } @Test @@ -352,28 +356,29 @@ public class ConfigurationMetadataAnnotationProcessorTests { @Test public void lombokInnerClassProperties() throws Exception { ConfigurationMetadata metadata = compile(LombokInnerClassProperties.class); - assertThat(metadata, - containsGroup("config").fromSource(LombokInnerClassProperties.class)); - assertThat(metadata, - containsGroup("config.first").ofType(LombokInnerClassProperties.Foo.class) - .fromSource(LombokInnerClassProperties.class)); - assertThat(metadata, containsProperty("config.first.name")); - assertThat(metadata, containsProperty("config.first.bar.name")); - assertThat(metadata, - containsGroup("config.second", LombokInnerClassProperties.Foo.class) - .fromSource(LombokInnerClassProperties.class)); - assertThat(metadata, containsProperty("config.second.name")); - assertThat(metadata, containsProperty("config.second.bar.name")); - assertThat(metadata, containsGroup("config.third").ofType(SimpleLombokPojo.class) + assertThat(metadata).has(Metadata.withGroup("config") .fromSource(LombokInnerClassProperties.class)); + assertThat(metadata).has(Metadata.withGroup("config.first") + .ofType(LombokInnerClassProperties.Foo.class) + .fromSource(LombokInnerClassProperties.class)); + assertThat(metadata).has(Metadata.withProperty("config.first.name")); + assertThat(metadata).has(Metadata.withProperty("config.first.bar.name")); + assertThat(metadata).has( + Metadata.withGroup("config.second", LombokInnerClassProperties.Foo.class) + .fromSource(LombokInnerClassProperties.class)); + assertThat(metadata).has(Metadata.withProperty("config.second.name")); + assertThat(metadata).has(Metadata.withProperty("config.second.bar.name")); + assertThat(metadata) + .has(Metadata.withGroup("config.third").ofType(SimpleLombokPojo.class) + .fromSource(LombokInnerClassProperties.class)); // For some reason the annotation processor resolves a type for SimpleLombokPojo // that is resolved (compiled) and the source annotations are gone. Because we // don't see the @Data annotation anymore, no field is harvested. What is crazy is // that a sample project works fine so this seem to be related to the unit test // environment for some reason. assertThat(metadata, // containsProperty("config.third.value")); - assertThat(metadata, containsProperty("config.fourth")); - assertThat(metadata, not(containsGroup("config.fourth"))); + assertThat(metadata).has(Metadata.withProperty("config.fourth")); + assertThat(metadata).isNotEqualTo(Metadata.withGroup("config.fourth")); } @Test @@ -382,8 +387,8 @@ public class ConfigurationMetadataAnnotationProcessorTests { AdditionalMetadata.class.getName(), null, null, null, null); writeAdditionalMetadata(property); ConfigurationMetadata metadata = compile(SimpleProperties.class); - assertThat(metadata, containsProperty("simple.comparator")); - assertThat(metadata, containsProperty("foo", String.class) + assertThat(metadata).has(Metadata.withProperty("simple.comparator")); + assertThat(metadata).has(Metadata.withProperty("foo", String.class) .fromSource(AdditionalMetadata.class)); } @@ -393,10 +398,10 @@ public class ConfigurationMetadataAnnotationProcessorTests { null, null, true, null); writeAdditionalMetadata(property); ConfigurationMetadata metadata = compile(SimpleProperties.class); - assertThat(metadata, containsProperty("simple.flag", Boolean.class) + assertThat(metadata).has(Metadata.withProperty("simple.flag", Boolean.class) .fromSource(SimpleProperties.class).withDescription("A simple flag.") - .withDeprecation(null, null).withDefaultValue(is(true))); - assertThat(metadata.getItems().size(), is(4)); + .withDeprecation(null, null).withDefaultValue(true)); + assertThat(metadata.getItems()).hasSize(4); } @Test @@ -405,11 +410,11 @@ public class ConfigurationMetadataAnnotationProcessorTests { null, null, "A nice comparator.", null, null); writeAdditionalMetadata(property); ConfigurationMetadata metadata = compile(SimpleProperties.class); - assertThat(metadata, - containsProperty("simple.comparator", "java.util.Comparator") + assertThat(metadata) + .has(Metadata.withProperty("simple.comparator", "java.util.Comparator") .fromSource(SimpleProperties.class) .withDescription("A nice comparator.")); - assertThat(metadata.getItems().size(), is(4)); + assertThat(metadata.getItems()).hasSize(4); } @Test @@ -419,11 +424,11 @@ public class ConfigurationMetadataAnnotationProcessorTests { new ItemDeprecation("Don't use this.", "simple.complex-comparator")); writeAdditionalMetadata(property); ConfigurationMetadata metadata = compile(SimpleProperties.class); - assertThat(metadata, - containsProperty("simple.comparator", "java.util.Comparator") + assertThat(metadata) + .has(Metadata.withProperty("simple.comparator", "java.util.Comparator") .fromSource(SimpleProperties.class) .withDeprecation("Don't use this.", "simple.complex-comparator")); - assertThat(metadata.getItems().size(), is(4)); + assertThat(metadata.getItems()).hasSize(4); } @Test @@ -433,11 +438,11 @@ public class ConfigurationMetadataAnnotationProcessorTests { new ItemDeprecation("Don't use this.", "single.name")); writeAdditionalMetadata(property); ConfigurationMetadata metadata = compile(DeprecatedSingleProperty.class); - assertThat(metadata, - containsProperty("singledeprecated.name", String.class.getName()) + assertThat(metadata).has( + Metadata.withProperty("singledeprecated.name", String.class.getName()) .fromSource(DeprecatedSingleProperty.class) .withDeprecation("Don't use this.", "single.name")); - assertThat(metadata.getItems().size(), is(3)); + assertThat(metadata.getItems()).hasSize(3); } @Test @@ -456,12 +461,11 @@ public class ConfigurationMetadataAnnotationProcessorTests { new ItemHint.ValueHint("boot", "Bla bla"), new ItemHint.ValueHint("spring", null))); ConfigurationMetadata metadata = compile(SimpleProperties.class); - assertThat(metadata, - containsProperty("simple.the-name", String.class) - .fromSource(SimpleProperties.class) - .withDescription("The name of this simple properties.") - .withDefaultValue(is("boot")).withDeprecation(null, null)); - assertThat(metadata, containsHint("simple.the-name") + assertThat(metadata).has(Metadata.withProperty("simple.the-name", String.class) + .fromSource(SimpleProperties.class) + .withDescription("The name of this simple properties.") + .withDefaultValue("boot").withDeprecation(null, null)); + assertThat(metadata).has(Metadata.withHint("simple.the-name") .withValue(0, "boot", "Bla bla").withValue(1, "spring", null)); } @@ -470,13 +474,12 @@ public class ConfigurationMetadataAnnotationProcessorTests { writeAdditionalHints(ItemHint.newHint("simple.theName", new ItemHint.ValueHint("boot", "Bla bla"))); ConfigurationMetadata metadata = compile(SimpleProperties.class); - assertThat(metadata, - containsProperty("simple.the-name", String.class) - .fromSource(SimpleProperties.class) - .withDescription("The name of this simple properties.") - .withDefaultValue(is("boot")).withDeprecation(null, null)); - assertThat(metadata, - containsHint("simple.the-name").withValue(0, "boot", "Bla bla")); + assertThat(metadata).has(Metadata.withProperty("simple.the-name", String.class) + .fromSource(SimpleProperties.class) + .withDescription("The name of this simple properties.") + .withDefaultValue("boot").withDeprecation(null, null)); + assertThat(metadata).has( + Metadata.withHint("simple.the-name").withValue(0, "boot", "Bla bla")); } @Test @@ -489,12 +492,11 @@ public class ConfigurationMetadataAnnotationProcessorTests { "org.foo")), new ItemHint.ValueProvider("second", null)))); ConfigurationMetadata metadata = compile(SimpleProperties.class); - assertThat(metadata, - containsProperty("simple.the-name", String.class) - .fromSource(SimpleProperties.class) - .withDescription("The name of this simple properties.") - .withDefaultValue(is("boot")).withDeprecation(null, null)); - assertThat(metadata, containsHint("simple.the-name") + assertThat(metadata).has(Metadata.withProperty("simple.the-name", String.class) + .fromSource(SimpleProperties.class) + .withDescription("The name of this simple properties.") + .withDefaultValue("boot").withDeprecation(null, null)); + assertThat(metadata).has(Metadata.withHint("simple.the-name") .withProvider("first", "target", "org.foo").withProvider("second")); } @@ -504,7 +506,7 @@ public class ConfigurationMetadataAnnotationProcessorTests { "java.lang.String", null, null, null, null, new ItemDeprecation("Lame name.", "simple.the-name"))); ConfigurationMetadata metadata = compile(SimpleProperties.class); - assertThat(metadata, containsProperty("simple.wrong-name", String.class) + assertThat(metadata).has(Metadata.withProperty("simple.wrong-name", String.class) .withDeprecation("Lame name.", "simple.the-name")); } @@ -527,8 +529,8 @@ public class ConfigurationMetadataAnnotationProcessorTests { additionalMetadata.write(writer); writer.flush(); ConfigurationMetadata metadata = compile(SimpleProperties.class); - assertThat(metadata, containsProperty("simple.comparator")); - assertThat(metadata, containsProperty("foo", String.class) + assertThat(metadata).has(Metadata.withProperty("simple.comparator")); + assertThat(metadata).has(Metadata.withProperty("foo", String.class) .fromSource(AdditionalMetadata.class)); } @@ -536,29 +538,29 @@ public class ConfigurationMetadataAnnotationProcessorTests { public void incrementalBuild() throws Exception { TestProject project = new TestProject(this.temporaryFolder, FooProperties.class, BarProperties.class); - assertFalse(project.getOutputFile(MetadataStore.METADATA_PATH).exists()); + assertThat(project.getOutputFile(MetadataStore.METADATA_PATH).exists()).isFalse(); ConfigurationMetadata metadata = project.fullBuild(); - assertTrue(project.getOutputFile(MetadataStore.METADATA_PATH).exists()); - assertThat(metadata, - containsProperty("foo.counter").fromSource(FooProperties.class)); - assertThat(metadata, - containsProperty("bar.counter").fromSource(BarProperties.class)); + assertThat(project.getOutputFile(MetadataStore.METADATA_PATH).exists()).isTrue(); + assertThat(metadata).has( + Metadata.withProperty("foo.counter").fromSource(FooProperties.class)); + assertThat(metadata).has( + Metadata.withProperty("bar.counter").fromSource(BarProperties.class)); metadata = project.incrementalBuild(BarProperties.class); - assertThat(metadata, - containsProperty("foo.counter").fromSource(FooProperties.class)); - assertThat(metadata, - containsProperty("bar.counter").fromSource(BarProperties.class)); + assertThat(metadata).has( + Metadata.withProperty("foo.counter").fromSource(FooProperties.class)); + assertThat(metadata).has( + Metadata.withProperty("bar.counter").fromSource(BarProperties.class)); project.addSourceCode(BarProperties.class, BarProperties.class.getResourceAsStream("BarProperties.snippet")); metadata = project.incrementalBuild(BarProperties.class); - assertThat(metadata, containsProperty("bar.extra")); - assertThat(metadata, containsProperty("foo.counter")); - assertThat(metadata, containsProperty("bar.counter")); + assertThat(metadata).has(Metadata.withProperty("bar.extra")); + assertThat(metadata).has(Metadata.withProperty("foo.counter")); + assertThat(metadata).has(Metadata.withProperty("bar.counter")); project.revert(BarProperties.class); metadata = project.incrementalBuild(BarProperties.class); - assertThat(metadata, not(containsProperty("bar.extra"))); - assertThat(metadata, containsProperty("foo.counter")); - assertThat(metadata, containsProperty("bar.counter")); + assertThat(metadata).isNotEqualTo(Metadata.withProperty("bar.extra")); + assertThat(metadata).has(Metadata.withProperty("foo.counter")); + assertThat(metadata).has(Metadata.withProperty("bar.counter")); } @Test @@ -566,13 +568,13 @@ public class ConfigurationMetadataAnnotationProcessorTests { TestProject project = new TestProject(this.temporaryFolder, FooProperties.class, BarProperties.class); ConfigurationMetadata metadata = project.fullBuild(); - assertThat(metadata, containsProperty("foo.counter")); - assertThat(metadata, containsProperty("bar.counter")); + assertThat(metadata).has(Metadata.withProperty("foo.counter")); + assertThat(metadata).has(Metadata.withProperty("bar.counter")); project.replaceText(BarProperties.class, "@ConfigurationProperties", "//@ConfigurationProperties"); metadata = project.incrementalBuild(BarProperties.class); - assertThat(metadata, containsProperty("foo.counter")); - assertThat(metadata, not(containsProperty("bar.counter"))); + assertThat(metadata).has(Metadata.withProperty("foo.counter")); + assertThat(metadata).isNotEqualTo(Metadata.withProperty("bar.counter")); } @Test @@ -580,35 +582,35 @@ public class ConfigurationMetadataAnnotationProcessorTests { TestProject project = new TestProject(this.temporaryFolder, FooProperties.class, BarProperties.class); ConfigurationMetadata metadata = project.fullBuild(); - assertThat(metadata, - containsProperty("foo.counter").fromSource(FooProperties.class)); - assertThat(metadata, - containsProperty("bar.counter").fromSource(BarProperties.class)); - assertThat(metadata, not( - containsProperty("bar.counter").fromSource(RenamedBarProperties.class))); + assertThat(metadata).has( + Metadata.withProperty("foo.counter").fromSource(FooProperties.class)); + assertThat(metadata).has( + Metadata.withProperty("bar.counter").fromSource(BarProperties.class)); + assertThat(metadata).doesNotHave(Metadata.withProperty("bar.counter") + .fromSource(RenamedBarProperties.class)); project.delete(BarProperties.class); project.add(RenamedBarProperties.class); metadata = project.incrementalBuild(RenamedBarProperties.class); - assertThat(metadata, - containsProperty("foo.counter").fromSource(FooProperties.class)); - assertThat(metadata, - not(containsProperty("bar.counter").fromSource(BarProperties.class))); - assertThat(metadata, - containsProperty("bar.counter").fromSource(RenamedBarProperties.class)); + assertThat(metadata).has( + Metadata.withProperty("foo.counter").fromSource(FooProperties.class)); + assertThat(metadata).doesNotHave( + Metadata.withProperty("bar.counter").fromSource(BarProperties.class)); + assertThat(metadata).has(Metadata.withProperty("bar.counter") + .fromSource(RenamedBarProperties.class)); } private void assertSimpleLombokProperties(ConfigurationMetadata metadata, Class source, String prefix) { - assertThat(metadata, containsGroup(prefix).fromSource(source)); - assertThat(metadata, not(containsProperty(prefix + ".id"))); - assertThat(metadata, containsProperty(prefix + ".name", String.class) + assertThat(metadata).has(Metadata.withGroup(prefix).fromSource(source)); + assertThat(metadata).doesNotHave(Metadata.withProperty(prefix + ".id")); + assertThat(metadata).has(Metadata.withProperty(prefix + ".name", String.class) .fromSource(source).withDescription("Name description.")); - assertThat(metadata, containsProperty(prefix + ".description")); - assertThat(metadata, containsProperty(prefix + ".counter")); - assertThat(metadata, containsProperty(prefix + ".number").fromSource(source) - .withDefaultValue(is(0)).withDeprecation(null, null)); - assertThat(metadata, containsProperty(prefix + ".items")); - assertThat(metadata, not(containsProperty(prefix + ".ignored"))); + assertThat(metadata).has(Metadata.withProperty(prefix + ".description")); + assertThat(metadata).has(Metadata.withProperty(prefix + ".counter")); + assertThat(metadata).has(Metadata.withProperty(prefix + ".number") + .fromSource(source).withDefaultValue(0).withDeprecation(null, null)); + assertThat(metadata).has(Metadata.withProperty(prefix + ".items")); + assertThat(metadata).doesNotHave(Metadata.withProperty(prefix + ".ignored")); } private ConfigurationMetadata compile(Class... types) throws IOException { diff --git a/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/ConfigurationMetadataMatchers.java b/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/ConfigurationMetadataMatchers.java deleted file mode 100644 index d630059a44..0000000000 --- a/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/ConfigurationMetadataMatchers.java +++ /dev/null @@ -1,416 +0,0 @@ -/* - * Copyright 2012-2015 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.boot.configurationprocessor; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.Map; - -import org.hamcrest.BaseMatcher; -import org.hamcrest.Description; -import org.hamcrest.Matcher; -import org.hamcrest.collection.IsMapContaining; - -import org.springframework.boot.configurationprocessor.metadata.ConfigurationMetadata; -import org.springframework.boot.configurationprocessor.metadata.ItemDeprecation; -import org.springframework.boot.configurationprocessor.metadata.ItemHint; -import org.springframework.boot.configurationprocessor.metadata.ItemMetadata; -import org.springframework.boot.configurationprocessor.metadata.ItemMetadata.ItemType; - -/** - * Hamcrest {@link Matcher} to help test {@link ConfigurationMetadata}. - * - * @author Phillip Webb - * @author Stephane Nicoll - */ -public final class ConfigurationMetadataMatchers { - - private ConfigurationMetadataMatchers() { - } - - public static ContainsItemMatcher containsGroup(String name) { - return new ContainsItemMatcher(ItemType.GROUP, name); - } - - public static ContainsItemMatcher containsGroup(String name, Class type) { - return new ContainsItemMatcher(ItemType.GROUP, name).ofType(type); - } - - public static ContainsItemMatcher containsGroup(String name, String type) { - return new ContainsItemMatcher(ItemType.GROUP, name).ofType(type); - } - - public static ContainsItemMatcher containsProperty(String name) { - return new ContainsItemMatcher(ItemType.PROPERTY, name); - } - - public static ContainsItemMatcher containsProperty(String name, Class type) { - return new ContainsItemMatcher(ItemType.PROPERTY, name).ofType(type); - } - - public static ContainsItemMatcher containsProperty(String name, String type) { - return new ContainsItemMatcher(ItemType.PROPERTY, name).ofType(type); - } - - public static ContainsHintMatcher containsHint(String name) { - return new ContainsHintMatcher(name); - } - - public static class ContainsItemMatcher extends BaseMatcher { - - private final ItemType itemType; - - private final String name; - - private final String type; - - private final Class sourceType; - - private final String description; - - private final Matcher defaultValue; - - private final ItemDeprecation deprecation; - - public ContainsItemMatcher(ItemType itemType, String name) { - this(itemType, name, null, null, null, null, null); - } - - public ContainsItemMatcher(ItemType itemType, String name, String type, - Class sourceType, String description, Matcher defaultValue, - ItemDeprecation deprecation) { - this.itemType = itemType; - this.name = name; - this.type = type; - this.sourceType = sourceType; - this.description = description; - this.defaultValue = defaultValue; - this.deprecation = deprecation; - } - - @Override - public boolean matches(Object item) { - ConfigurationMetadata metadata = (ConfigurationMetadata) item; - ItemMetadata itemMetadata = getFirstItemWithName(metadata, this.name); - if (itemMetadata == null) { - return false; - } - if (this.type != null && !this.type.equals(itemMetadata.getType())) { - return false; - } - if (this.sourceType != null - && !this.sourceType.getName().equals(itemMetadata.getSourceType())) { - return false; - } - if (this.defaultValue != null - && !this.defaultValue.matches(itemMetadata.getDefaultValue())) { - return false; - } - if (this.description != null - && !this.description.equals(itemMetadata.getDescription())) { - return false; - } - if (this.deprecation == null && itemMetadata.getDeprecation() != null) { - return false; - } - if (this.deprecation != null - && !this.deprecation.equals(itemMetadata.getDeprecation())) { - return false; - } - return true; - } - - @Override - public void describeMismatch(Object item, Description description) { - ConfigurationMetadata metadata = (ConfigurationMetadata) item; - ItemMetadata property = getFirstItemWithName(metadata, this.name); - if (property == null) { - description.appendText("missing " + this.itemType.toString().toLowerCase() - + " " + this.name); - } - else { - description - .appendText("was " + this.itemType.toString().toLowerCase() + " ") - .appendValue(property); - } - } - - @Override - public void describeTo(Description description) { - description.appendText("metadata containing " + this.name); - if (this.type != null) { - description.appendText(" dataType ").appendValue(this.type); - } - if (this.sourceType != null) { - description.appendText(" sourceType ").appendValue(this.sourceType); - } - if (this.defaultValue != null) { - description.appendText(" defaultValue ").appendValue(this.defaultValue); - } - if (this.description != null) { - description.appendText(" description ").appendValue(this.description); - } - if (this.deprecation != null) { - description.appendText(" deprecation ").appendValue(this.deprecation); - } - } - - public ContainsItemMatcher ofType(Class dataType) { - return new ContainsItemMatcher(this.itemType, this.name, dataType.getName(), - this.sourceType, this.description, this.defaultValue, - this.deprecation); - } - - public ContainsItemMatcher ofType(String dataType) { - return new ContainsItemMatcher(this.itemType, this.name, dataType, - this.sourceType, this.description, this.defaultValue, - this.deprecation); - } - - public ContainsItemMatcher fromSource(Class sourceType) { - return new ContainsItemMatcher(this.itemType, this.name, this.type, - sourceType, this.description, this.defaultValue, this.deprecation); - } - - public ContainsItemMatcher withDescription(String description) { - return new ContainsItemMatcher(this.itemType, this.name, this.type, - this.sourceType, description, this.defaultValue, this.deprecation); - } - - public ContainsItemMatcher withDefaultValue(Matcher defaultValue) { - return new ContainsItemMatcher(this.itemType, this.name, this.type, - this.sourceType, this.description, defaultValue, this.deprecation); - } - - public ContainsItemMatcher withDeprecation(String reason, String replacement) { - return new ContainsItemMatcher(this.itemType, this.name, this.type, - this.sourceType, this.description, this.defaultValue, - new ItemDeprecation(reason, replacement)); - } - - public ContainsItemMatcher withNoDeprecation() { - return new ContainsItemMatcher(this.itemType, this.name, this.type, - this.sourceType, this.description, this.defaultValue, null); - } - - private ItemMetadata getFirstItemWithName(ConfigurationMetadata metadata, - String name) { - for (ItemMetadata item : metadata.getItems()) { - if (item.isOfItemType(this.itemType) && name.equals(item.getName())) { - return item; - } - } - return null; - } - - } - - public static class ContainsHintMatcher extends BaseMatcher { - - private final String name; - - private final List values; - - private final List providers; - - public ContainsHintMatcher(String name) { - this(name, new ArrayList(), - new ArrayList()); - } - - public ContainsHintMatcher(String name, List values, - List providers) { - this.name = name; - this.values = values; - this.providers = providers; - } - - @Override - public boolean matches(Object item) { - ConfigurationMetadata metadata = (ConfigurationMetadata) item; - ItemHint itemHint = getFirstHintWithName(metadata, this.name); - if (itemHint == null) { - return false; - } - for (ValueHintMatcher value : this.values) { - if (!value.matches(itemHint)) { - return false; - } - } - for (ValueProviderMatcher provider : this.providers) { - if (!provider.matches(itemHint)) { - return false; - } - } - return true; - } - - @Override - public void describeMismatch(Object item, Description description) { - ConfigurationMetadata metadata = (ConfigurationMetadata) item; - ItemHint itemHint = getFirstHintWithName(metadata, this.name); - if (itemHint == null) { - description.appendText("missing hint " + this.name); - } - else { - description.appendText("was hint ").appendValue(itemHint); - } - } - - @Override - public void describeTo(Description description) { - description.appendText("hints for " + this.name); - if (this.values != null) { - description.appendText(" values ").appendValue(this.values); - } - if (this.providers != null) { - description.appendText(" providers ").appendValue(this.providers); - } - } - - public ContainsHintMatcher withValue(int index, Object value, - String description) { - List values = new ArrayList(this.values); - values.add(new ValueHintMatcher(index, value, description)); - return new ContainsHintMatcher(this.name, values, this.providers); - } - - public ContainsHintMatcher withProvider(int index, String provider, - Map parameters) { - List providers = new ArrayList( - this.providers); - providers.add(new ValueProviderMatcher(index, provider, parameters)); - return new ContainsHintMatcher(this.name, this.values, providers); - } - - public ContainsHintMatcher withProvider(String provider, String key, - Object value) { - return withProvider(this.providers.size(), provider, - Collections.singletonMap(key, value)); - } - - public ContainsHintMatcher withProvider(String provider) { - return withProvider(this.providers.size(), provider, null); - } - - private ItemHint getFirstHintWithName(ConfigurationMetadata metadata, - String name) { - for (ItemHint hint : metadata.getHints()) { - if (name.equals(hint.getName())) { - return hint; - } - } - return null; - } - - } - - public static class ValueHintMatcher extends BaseMatcher { - - private final int index; - - private final Object value; - - private final String description; - - public ValueHintMatcher(int index, Object value, String description) { - this.index = index; - this.value = value; - this.description = description; - } - - @Override - public boolean matches(Object item) { - ItemHint hint = (ItemHint) item; - if (this.index + 1 > hint.getValues().size()) { - return false; - } - ItemHint.ValueHint valueHint = hint.getValues().get(this.index); - if (this.value != null && !this.value.equals(valueHint.getValue())) { - return false; - } - if (this.description != null - && !this.description.equals(valueHint.getDescription())) { - return false; - } - return true; - } - - @Override - public void describeTo(Description description) { - description.appendText("value hint at index '" + this.index + "'"); - if (this.value != null) { - description.appendText(" value ").appendValue(this.value); - } - if (this.description != null) { - description.appendText(" description ").appendValue(this.description); - } - } - - } - - public static class ValueProviderMatcher extends BaseMatcher { - - private final int index; - - private final String name; - - private final Map parameters; - - public ValueProviderMatcher(int index, String name, - Map parameters) { - this.index = index; - this.name = name; - this.parameters = parameters; - } - - @Override - public boolean matches(Object item) { - ItemHint hint = (ItemHint) item; - if (this.index + 1 > hint.getProviders().size()) { - return false; - } - ItemHint.ValueProvider valueProvider = hint.getProviders().get(this.index); - if (this.name != null && !this.name.equals(valueProvider.getName())) { - return false; - } - if (this.parameters != null) { - for (Map.Entry entry : this.parameters.entrySet()) { - if (!IsMapContaining.hasEntry(entry.getKey(), entry.getValue()) - .matches(valueProvider.getParameters())) { - return false; - } - } - } - return true; - } - - @Override - public void describeTo(Description description) { - description.appendText("value provider "); - if (this.name != null) { - description.appendText(" name ").appendValue(this.name); - } - if (this.parameters != null) { - description.appendText(" parameters ").appendValue(this.parameters); - } - } - - } - -} diff --git a/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/Metadata.java b/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/Metadata.java new file mode 100644 index 0000000000..4dba5fa12d --- /dev/null +++ b/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/Metadata.java @@ -0,0 +1,401 @@ +/* + * Copyright 2012-2015 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.boot.configurationprocessor; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Map; + +import org.assertj.core.api.Condition; +import org.hamcrest.collection.IsMapContaining; + +import org.springframework.boot.configurationprocessor.metadata.ConfigurationMetadata; +import org.springframework.boot.configurationprocessor.metadata.ItemDeprecation; +import org.springframework.boot.configurationprocessor.metadata.ItemHint; +import org.springframework.boot.configurationprocessor.metadata.ItemMetadata; +import org.springframework.boot.configurationprocessor.metadata.ItemMetadata.ItemType; +import org.springframework.util.ObjectUtils; + +/** + * AssertJ {@link Condition} to help test {@link ConfigurationMetadata}. + * + * @author Phillip Webb + * @author Stephane Nicoll + */ +public final class Metadata { + + private Metadata() { + } + + public static MetadataItemCondition withGroup(String name) { + return new MetadataItemCondition(ItemType.GROUP, name); + } + + public static MetadataItemCondition withGroup(String name, Class type) { + return new MetadataItemCondition(ItemType.GROUP, name).ofType(type); + } + + public static MetadataItemCondition withGroup(String name, String type) { + return new MetadataItemCondition(ItemType.GROUP, name).ofType(type); + } + + public static MetadataItemCondition withProperty(String name) { + return new MetadataItemCondition(ItemType.PROPERTY, name); + } + + public static MetadataItemCondition withProperty(String name, Class type) { + return new MetadataItemCondition(ItemType.PROPERTY, name).ofType(type); + } + + public static MetadataItemCondition withProperty(String name, String type) { + return new MetadataItemCondition(ItemType.PROPERTY, name).ofType(type); + } + + public static MetadataHintCondition withHint(String name) { + return new MetadataHintCondition(name); + } + + public static class MetadataItemCondition extends Condition { + + private final ItemType itemType; + + private final String name; + + private final String type; + + private final Class sourceType; + + private final String description; + + private final Object defaultValue; + + private final ItemDeprecation deprecation; + + public MetadataItemCondition(ItemType itemType, String name) { + this(itemType, name, null, null, null, null, null); + } + + public MetadataItemCondition(ItemType itemType, String name, String type, + Class sourceType, String description, Object defaultValue, + ItemDeprecation deprecation) { + this.itemType = itemType; + this.name = name; + this.type = type; + this.sourceType = sourceType; + this.description = description; + this.defaultValue = defaultValue; + this.deprecation = deprecation; + describedAs(createDescription()); + } + + private String createDescription() { + StringBuilder description = new StringBuilder(); + description.append("an item named '" + this.name + "'"); + if (this.type != null) { + description.append(" with dataType:").append(this.type); + } + if (this.sourceType != null) { + description.append(" with sourceType:").append(this.sourceType); + } + if (this.defaultValue != null) { + description.append(" with defaultValue:").append(this.defaultValue); + } + if (this.description != null) { + description.append(" with description:").append(this.description); + } + if (this.deprecation != null) { + description.append(" with deprecation:").append(this.deprecation); + } + return description.toString(); + } + + @Override + public boolean matches(ConfigurationMetadata value) { + ItemMetadata itemMetadata = getFirstItemWithName(value, this.name); + if (itemMetadata == null) { + return false; + } + if (this.type != null && !this.type.equals(itemMetadata.getType())) { + return false; + } + if (this.sourceType != null + && !this.sourceType.getName().equals(itemMetadata.getSourceType())) { + return false; + } + if (this.defaultValue != null && !ObjectUtils + .nullSafeEquals(this.defaultValue, itemMetadata.getDefaultValue())) { + return false; + } + if (this.description != null + && !this.description.equals(itemMetadata.getDescription())) { + return false; + } + if (this.deprecation == null && itemMetadata.getDeprecation() != null) { + return false; + } + if (this.deprecation != null + && !this.deprecation.equals(itemMetadata.getDeprecation())) { + return false; + } + return true; + } + + public MetadataItemCondition ofType(Class dataType) { + return new MetadataItemCondition(this.itemType, this.name, dataType.getName(), + this.sourceType, this.description, this.defaultValue, + this.deprecation); + } + + public MetadataItemCondition ofType(String dataType) { + return new MetadataItemCondition(this.itemType, this.name, dataType, + this.sourceType, this.description, this.defaultValue, + this.deprecation); + } + + public MetadataItemCondition fromSource(Class sourceType) { + return new MetadataItemCondition(this.itemType, this.name, this.type, + sourceType, this.description, this.defaultValue, this.deprecation); + } + + public MetadataItemCondition withDescription(String description) { + return new MetadataItemCondition(this.itemType, this.name, this.type, + this.sourceType, description, this.defaultValue, this.deprecation); + } + + public MetadataItemCondition withDefaultValue(Object defaultValue) { + return new MetadataItemCondition(this.itemType, this.name, this.type, + this.sourceType, this.description, defaultValue, this.deprecation); + } + + public MetadataItemCondition withDeprecation(String reason, String replacement) { + return new MetadataItemCondition(this.itemType, this.name, this.type, + this.sourceType, this.description, this.defaultValue, + new ItemDeprecation(reason, replacement)); + } + + public MetadataItemCondition withNoDeprecation() { + return new MetadataItemCondition(this.itemType, this.name, this.type, + this.sourceType, this.description, this.defaultValue, null); + } + + private ItemMetadata getFirstItemWithName(ConfigurationMetadata metadata, + String name) { + for (ItemMetadata item : metadata.getItems()) { + if (item.isOfItemType(this.itemType) && name.equals(item.getName())) { + return item; + } + } + return null; + } + + } + + public static class MetadataHintCondition extends Condition { + + private final String name; + + private final List valueConditions; + + private final List providerConditions; + + public MetadataHintCondition(String name) { + this.name = name; + this.valueConditions = Collections.emptyList(); + this.providerConditions = Collections.emptyList(); + } + + public MetadataHintCondition(String name, + List valueConditions, + List providerConditions) { + this.name = name; + this.valueConditions = valueConditions; + this.providerConditions = providerConditions; + describedAs(createDescription()); + } + + private String createDescription() { + StringBuilder description = new StringBuilder(); + description.append("a hints name '" + this.name + "'"); + if (!this.valueConditions.isEmpty()) { + description.append(" with values:").append(this.valueConditions); + } + if (!this.providerConditions.isEmpty()) { + description.append(" with providers:").append(this.providerConditions); + } + return description.toString(); + } + + @Override + public boolean matches(ConfigurationMetadata metadata) { + ItemHint itemHint = getFirstHintWithName(metadata, this.name); + if (itemHint == null) { + return false; + } + return matches(itemHint, this.valueConditions) + && matches(itemHint, this.providerConditions); + } + + private boolean matches(ItemHint itemHint, + List> conditions) { + for (Condition condition : conditions) { + if (!condition.matches(itemHint)) { + return false; + } + } + return true; + } + + private ItemHint getFirstHintWithName(ConfigurationMetadata metadata, + String name) { + for (ItemHint hint : metadata.getHints()) { + if (name.equals(hint.getName())) { + return hint; + } + } + return null; + } + + public MetadataHintCondition withValue(int index, Object value, + String description) { + return new MetadataHintCondition(this.name, + add(this.valueConditions, + new ItemHintValueCondition(index, value, description)), + this.providerConditions); + } + + public MetadataHintCondition withProvider(String provider) { + return withProvider(this.providerConditions.size(), provider, null); + } + + public MetadataHintCondition withProvider(String provider, String key, + Object value) { + return withProvider(this.providerConditions.size(), provider, + Collections.singletonMap(key, value)); + } + + public MetadataHintCondition withProvider(int index, String provider, + Map parameters) { + return new MetadataHintCondition(this.name, this.valueConditions, + add(this.providerConditions, + new ItemHintProviderCondition(index, provider, parameters))); + } + + private List add(List items, T item) { + List result = new ArrayList(items); + result.add(item); + return result; + } + + } + + private static class ItemHintValueCondition extends Condition { + + private final int index; + + private final Object value; + + private final String description; + + ItemHintValueCondition(int index, Object value, String description) { + this.index = index; + this.value = value; + this.description = description; + describedAs(createDescription()); + } + + private String createDescription() { + StringBuilder description = new StringBuilder(); + description.append("value hint at index '" + this.index + "'"); + if (this.value != null) { + description.append(" with value:").append(this.value); + } + if (this.description != null) { + description.append(" with description:").append(this.description); + } + return description.toString(); + } + + @Override + public boolean matches(ItemHint value) { + if (this.index + 1 > value.getValues().size()) { + return false; + } + ItemHint.ValueHint valueHint = value.getValues().get(this.index); + if (this.value != null && !this.value.equals(valueHint.getValue())) { + return false; + } + if (this.description != null + && !this.description.equals(valueHint.getDescription())) { + return false; + } + return true; + } + + } + + private static class ItemHintProviderCondition extends Condition { + + private final int index; + + private final String name; + + private final Map parameters; + + ItemHintProviderCondition(int index, String name, + Map parameters) { + this.index = index; + this.name = name; + this.parameters = parameters; + describedAs(createDescription()); + } + + public String createDescription() { + StringBuilder description = new StringBuilder(); + description.append("value provider"); + if (this.name != null) { + description.append(" with name:").append(this.name); + } + if (this.parameters != null) { + description.append(" with parameters:").append(this.parameters); + } + return description.toString(); + } + + @Override + public boolean matches(ItemHint hint) { + if (this.index + 1 > hint.getProviders().size()) { + return false; + } + ItemHint.ValueProvider valueProvider = hint.getProviders().get(this.index); + if (this.name != null && !this.name.equals(valueProvider.getName())) { + return false; + } + if (this.parameters != null) { + for (Map.Entry entry : this.parameters.entrySet()) { + if (!IsMapContaining.hasEntry(entry.getKey(), entry.getValue()) + .matches(valueProvider.getParameters())) { + return false; + } + } + } + return true; + } + + } + +} diff --git a/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/TestConfigurationMetadataAnnotationProcessor.java b/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/TestConfigurationMetadataAnnotationProcessor.java index 698bf65018..6247f3e7da 100644 --- a/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/TestConfigurationMetadataAnnotationProcessor.java +++ b/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/TestConfigurationMetadataAnnotationProcessor.java @@ -28,6 +28,8 @@ import org.springframework.boot.configurationprocessor.metadata.ConfigurationMet import org.springframework.boot.configurationprocessor.metadata.JsonMarshaller; /** + * Test {@link ConfigurationMetadataAnnotationProcessor}. + * * @author Stephane Nicoll * @author Phillip Webb * @author Andy Wilkinson diff --git a/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/fieldvalues/AbstractFieldValuesProcessorTests.java b/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/fieldvalues/AbstractFieldValuesProcessorTests.java index 5f749fd4f9..f7b9f635fc 100644 --- a/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/fieldvalues/AbstractFieldValuesProcessorTests.java +++ b/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/fieldvalues/AbstractFieldValuesProcessorTests.java @@ -29,7 +29,6 @@ import javax.lang.model.SourceVersion; import javax.lang.model.element.Element; import javax.lang.model.element.TypeElement; -import org.hamcrest.Matcher; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; @@ -37,9 +36,7 @@ import org.junit.rules.TemporaryFolder; import org.springframework.boot.configurationprocessor.TestCompiler; import org.springframework.boot.configurationsample.fieldvalues.FieldValues; -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; /** * Abstract base class for {@link FieldValuesParser} tests. @@ -60,43 +57,37 @@ public abstract class AbstractFieldValuesProcessorTests { TestCompiler compiler = new TestCompiler(this.temporaryFolder); compiler.getTask(FieldValues.class).call(processor); Map values = processor.getValues(); - assertThat(values.get("string"), equalToObject("1")); - assertThat(values.get("stringNone"), nullValue()); - assertThat(values.get("stringConst"), equalToObject("c")); - assertThat(values.get("bool"), equalToObject(true)); - assertThat(values.get("boolNone"), equalToObject(false)); - assertThat(values.get("boolConst"), equalToObject(true)); - assertThat(values.get("boolObject"), equalToObject(true)); - assertThat(values.get("boolObjectNone"), nullValue()); - assertThat(values.get("boolObjectConst"), equalToObject(true)); - assertThat(values.get("integer"), equalToObject(1)); - assertThat(values.get("integerNone"), equalToObject(0)); - assertThat(values.get("integerConst"), equalToObject(2)); - assertThat(values.get("integerObject"), equalToObject(3)); - assertThat(values.get("integerObjectNone"), nullValue()); - assertThat(values.get("integerObjectConst"), equalToObject(4)); - assertThat(values.get("charset"), equalToObject("US-ASCII")); - assertThat(values.get("charsetConst"), equalToObject("UTF-8")); - assertThat(values.get("mimeType"), equalToObject("text/html")); - assertThat(values.get("mimeTypeConst"), equalToObject("text/plain")); - assertThat(values.get("object"), equalToObject(123)); - assertThat(values.get("objectNone"), nullValue()); - assertThat(values.get("objectConst"), equalToObject("c")); - assertThat(values.get("objectInstance"), nullValue()); - assertThat(values.get("stringArray"), - equalToObject(new Object[] { "FOO", "BAR" })); - assertThat(values.get("stringArrayNone"), nullValue()); - assertThat(values.get("stringEmptyArray"), equalToObject(new Object[0])); - assertThat(values.get("stringArrayConst"), - equalToObject(new Object[] { "OK", "KO" })); - assertThat(values.get("stringArrayConstElements"), - equalToObject(new Object[] { "c" })); - assertThat(values.get("integerArray"), equalToObject(new Object[] { 42, 24 })); - assertThat(values.get("unknownArray"), nullValue()); - } - - private Matcher equalToObject(Object object) { - return equalTo(object); + assertThat(values.get("string")).isEqualTo("1"); + assertThat(values.get("stringNone")).isNull(); + assertThat(values.get("stringConst")).isEqualTo("c"); + assertThat(values.get("bool")).isEqualTo(true); + assertThat(values.get("boolNone")).isEqualTo(false); + assertThat(values.get("boolConst")).isEqualTo(true); + assertThat(values.get("boolObject")).isEqualTo(true); + assertThat(values.get("boolObjectNone")).isNull(); + assertThat(values.get("boolObjectConst")).isEqualTo(true); + assertThat(values.get("integer")).isEqualTo(1); + assertThat(values.get("integerNone")).isEqualTo(0); + assertThat(values.get("integerConst")).isEqualTo(2); + assertThat(values.get("integerObject")).isEqualTo(3); + assertThat(values.get("integerObjectNone")).isNull(); + assertThat(values.get("integerObjectConst")).isEqualTo(4); + assertThat(values.get("charset")).isEqualTo("US-ASCII"); + assertThat(values.get("charsetConst")).isEqualTo("UTF-8"); + assertThat(values.get("mimeType")).isEqualTo("text/html"); + assertThat(values.get("mimeTypeConst")).isEqualTo("text/plain"); + assertThat(values.get("object")).isEqualTo(123); + assertThat(values.get("objectNone")).isNull(); + assertThat(values.get("objectConst")).isEqualTo("c"); + assertThat(values.get("objectInstance")).isNull(); + assertThat(values.get("stringArray")).isEqualTo(new Object[] { "FOO", "BAR" }); + assertThat(values.get("stringArrayNone")).isNull(); + assertThat(values.get("stringEmptyArray")).isEqualTo(new Object[0]); + assertThat(values.get("stringArrayConst")).isEqualTo(new Object[] { "OK", "KO" }); + assertThat(values.get("stringArrayConstElements")) + .isEqualTo(new Object[] { "c" }); + assertThat(values.get("integerArray")).isEqualTo(new Object[] { 42, 24 }); + assertThat(values.get("unknownArray")).isNull(); } @SupportedAnnotationTypes({ diff --git a/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/metadata/ConfigurationMetadataTests.java b/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/metadata/ConfigurationMetadataTests.java index 3f60e7406e..395f3fd577 100644 --- a/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/metadata/ConfigurationMetadataTests.java +++ b/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/metadata/ConfigurationMetadataTests.java @@ -18,8 +18,7 @@ package org.springframework.boot.configurationprocessor.metadata; import org.junit.Test; -import static org.hamcrest.CoreMatchers.is; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link ConfigurationMetadata}. @@ -30,43 +29,44 @@ public class ConfigurationMetadataTests { @Test public void toDashedCaseCamelCase() { - assertThat(toDashedCase("simpleCamelCase"), is("simple-camel-case")); + assertThat(toDashedCase("simpleCamelCase")).isEqualTo("simple-camel-case"); } @Test public void toDashedCaseWordsUnderscore() { - assertThat(toDashedCase("Word_With_underscore"), is("word_with_underscore")); + assertThat(toDashedCase("Word_With_underscore")) + .isEqualTo("word_with_underscore"); } @Test public void toDashedCaseWordsSeveralUnderscores() { - assertThat(toDashedCase("Word___With__underscore"), - is("word___with__underscore")); + assertThat(toDashedCase("Word___With__underscore")) + .isEqualTo("word___with__underscore"); } @Test public void toDashedCaseLowerCaseUnderscore() { - assertThat(toDashedCase("lower_underscore"), is("lower_underscore")); + assertThat(toDashedCase("lower_underscore")).isEqualTo("lower_underscore"); } @Test public void toDashedCaseUpperUnderscore() { - assertThat(toDashedCase("UPPER_UNDERSCORE"), is("upper_underscore")); + assertThat(toDashedCase("UPPER_UNDERSCORE")).isEqualTo("upper_underscore"); } @Test public void toDashedCaseMultipleUnderscores() { - assertThat(toDashedCase("super___crazy"), is("super___crazy")); + assertThat(toDashedCase("super___crazy")).isEqualTo("super___crazy"); } @Test public void toDashedCaseUppercase() { - assertThat(toDashedCase("UPPERCASE"), is("uppercase")); + assertThat(toDashedCase("UPPERCASE")).isEqualTo("uppercase"); } @Test public void toDashedCaseLowercase() { - assertThat(toDashedCase("lowercase"), is("lowercase")); + assertThat(toDashedCase("lowercase")).isEqualTo("lowercase"); } private String toDashedCase(String name) { diff --git a/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/metadata/JsonMarshallerTests.java b/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/metadata/JsonMarshallerTests.java index 820794eb16..bc63a345da 100644 --- a/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/metadata/JsonMarshallerTests.java +++ b/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/metadata/JsonMarshallerTests.java @@ -25,11 +25,9 @@ import java.util.Collections; import org.junit.Test; -import static org.hamcrest.CoreMatchers.is; -import static org.junit.Assert.assertThat; -import static org.springframework.boot.configurationprocessor.ConfigurationMetadataMatchers.containsGroup; -import static org.springframework.boot.configurationprocessor.ConfigurationMetadataMatchers.containsHint; -import static org.springframework.boot.configurationprocessor.ConfigurationMetadataMatchers.containsProperty; +import org.springframework.boot.configurationprocessor.Metadata; + +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link JsonMarshaller}. @@ -70,22 +68,21 @@ public class JsonMarshallerTests { marshaller.write(metadata, outputStream); ConfigurationMetadata read = marshaller .read(new ByteArrayInputStream(outputStream.toByteArray())); - assertThat(read, - containsProperty("a.b", StringBuffer.class).fromSource(InputStream.class) - .withDescription("desc").withDefaultValue(is("x")) - .withDeprecation("Deprecation comment", "b.c.d")); - assertThat(read, containsProperty("b.c.d")); - assertThat(read, containsProperty("c").withDefaultValue(is(123))); - assertThat(read, containsProperty("d").withDefaultValue(is(true))); - assertThat(read, - containsProperty("e").withDefaultValue(is(new String[] { "y", "n" }))); - assertThat(read, containsProperty("f") - .withDefaultValue(is(new boolean[] { true, false }))); - assertThat(read, containsGroup("d")); - assertThat(read, containsHint("a.b")); - assertThat(read, - containsHint("c").withValue(0, 123, "hey").withValue(1, 456, null)); - assertThat(read, containsHint("d").withProvider("first", "target", "foo") + assertThat(read).has(Metadata.withProperty("a.b", StringBuffer.class) + .fromSource(InputStream.class).withDescription("desc") + .withDefaultValue("x").withDeprecation("Deprecation comment", "b.c.d")); + assertThat(read).has(Metadata.withProperty("b.c.d")); + assertThat(read).has(Metadata.withProperty("c").withDefaultValue(123)); + assertThat(read).has(Metadata.withProperty("d").withDefaultValue(true)); + assertThat(read).has( + Metadata.withProperty("e").withDefaultValue(new String[] { "y", "n" })); + assertThat(read).has(Metadata.withProperty("f") + .withDefaultValue(new Object[] { true, false })); + assertThat(read).has(Metadata.withGroup("d")); + assertThat(read).has(Metadata.withHint("a.b")); + assertThat(read).has( + Metadata.withHint("c").withValue(0, 123, "hey").withValue(1, 456, null)); + assertThat(read).has(Metadata.withHint("d").withProvider("first", "target", "foo") .withProvider("second")); } diff --git a/spring-boot-tools/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/DefaultLaunchScriptTests.java b/spring-boot-tools/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/DefaultLaunchScriptTests.java index fec531b74e..71c54eef50 100644 --- a/spring-boot-tools/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/DefaultLaunchScriptTests.java +++ b/spring-boot-tools/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/DefaultLaunchScriptTests.java @@ -26,9 +26,7 @@ import org.junit.rules.TemporaryFolder; import org.springframework.util.FileCopyUtils; -import static org.hamcrest.Matchers.containsString; -import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link DefaultLaunchScript}. @@ -45,7 +43,7 @@ public class DefaultLaunchScriptTests { public void loadsDefaultScript() throws Exception { DefaultLaunchScript script = new DefaultLaunchScript(null, null); String content = new String(script.toByteArray()); - assertThat(content, containsString("Spring Boot Startup Script")); + assertThat(content).contains("Spring Boot Startup Script"); } @Test @@ -82,14 +80,14 @@ public class DefaultLaunchScriptTests { public void defaultForUseStartStopDaemonIsTrue() throws Exception { DefaultLaunchScript script = new DefaultLaunchScript(null, null); String content = new String(script.toByteArray()); - assertThat(content, containsString("USE_START_STOP_DAEMON=\"true\"")); + assertThat(content).contains("USE_START_STOP_DAEMON=\"true\""); } @Test public void defaultForModeIsAuto() throws Exception { DefaultLaunchScript script = new DefaultLaunchScript(null, null); String content = new String(script.toByteArray()); - assertThat(content, containsString("MODE=\"auto\"")); + assertThat(content).contains("MODE=\"auto\""); } @Test @@ -98,7 +96,7 @@ public class DefaultLaunchScriptTests { FileCopyUtils.copy("ABC".getBytes(), file); DefaultLaunchScript script = new DefaultLaunchScript(file, null); String content = new String(script.toByteArray()); - assertThat(content, equalTo("ABC")); + assertThat(content).isEqualTo("ABC"); } @Test @@ -108,7 +106,7 @@ public class DefaultLaunchScriptTests { DefaultLaunchScript script = new DefaultLaunchScript(file, createProperties("a:e", "b:o")); String content = new String(script.toByteArray()); - assertThat(content, equalTo("hello")); + assertThat(content).isEqualTo("hello"); } @Test @@ -118,7 +116,7 @@ public class DefaultLaunchScriptTests { DefaultLaunchScript script = new DefaultLaunchScript(file, createProperties("a:e", "b:o")); String content = new String(script.toByteArray()); - assertThat(content, equalTo("hel\nlo")); + assertThat(content).isEqualTo("hel\nlo"); } @Test @@ -127,7 +125,7 @@ public class DefaultLaunchScriptTests { FileCopyUtils.copy("h{{a:e}}ll{{b:o}}".getBytes(), file); DefaultLaunchScript script = new DefaultLaunchScript(file, null); String content = new String(script.toByteArray()); - assertThat(content, equalTo("hello")); + assertThat(content).isEqualTo("hello"); } @Test @@ -137,7 +135,7 @@ public class DefaultLaunchScriptTests { DefaultLaunchScript script = new DefaultLaunchScript(file, createProperties("a:a")); String content = new String(script.toByteArray()); - assertThat(content, equalTo("hallo")); + assertThat(content).isEqualTo("hallo"); } @Test @@ -146,14 +144,14 @@ public class DefaultLaunchScriptTests { FileCopyUtils.copy("h{{a}}ll{{b}}".getBytes(), file); DefaultLaunchScript script = new DefaultLaunchScript(file, null); String content = new String(script.toByteArray()); - assertThat(content, equalTo("h{{a}}ll{{b}}")); + assertThat(content).isEqualTo("h{{a}}ll{{b}}"); } private void assertThatPlaceholderCanBeReplaced(String placeholder) throws Exception { DefaultLaunchScript script = new DefaultLaunchScript(null, createProperties(placeholder + ":__test__")); String content = new String(script.toByteArray()); - assertThat(content, containsString("__test__")); + assertThat(content).contains("__test__"); } private Map createProperties(String... pairs) { diff --git a/spring-boot-tools/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/FileUtilsTests.java b/spring-boot-tools/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/FileUtilsTests.java index 25a09229c0..3525323b8f 100644 --- a/spring-boot-tools/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/FileUtilsTests.java +++ b/spring-boot-tools/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/FileUtilsTests.java @@ -28,10 +28,7 @@ import org.junit.rules.TemporaryFolder; import org.springframework.util.FileSystemUtils; -import static org.hamcrest.Matchers.equalTo; -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 FileUtils}. @@ -65,31 +62,31 @@ public class FileUtilsTests { new File(this.originDirectory, "logback.xml").createNewFile(); FileUtils.removeDuplicatesFromOutputDirectory(this.outputDirectory, this.originDirectory); - assertFalse(file.exists()); + assertThat(file.exists()).isFalse(); } @Test public void nestedDuplicateFile() throws IOException { - assertTrue(new File(this.outputDirectory, "sub").mkdirs()); - assertTrue(new File(this.originDirectory, "sub").mkdirs()); + assertThat(new File(this.outputDirectory, "sub").mkdirs()).isTrue(); + assertThat(new File(this.originDirectory, "sub").mkdirs()).isTrue(); File file = new File(this.outputDirectory, "sub/logback.xml"); file.createNewFile(); new File(this.originDirectory, "sub/logback.xml").createNewFile(); FileUtils.removeDuplicatesFromOutputDirectory(this.outputDirectory, this.originDirectory); - assertFalse(file.exists()); + assertThat(file.exists()).isFalse(); } @Test public void nestedNonDuplicateFile() throws IOException { - assertTrue(new File(this.outputDirectory, "sub").mkdirs()); - assertTrue(new File(this.originDirectory, "sub").mkdirs()); + assertThat(new File(this.outputDirectory, "sub").mkdirs()).isTrue(); + assertThat(new File(this.originDirectory, "sub").mkdirs()).isTrue(); File file = new File(this.outputDirectory, "sub/logback.xml"); file.createNewFile(); new File(this.originDirectory, "sub/different.xml").createNewFile(); FileUtils.removeDuplicatesFromOutputDirectory(this.outputDirectory, this.originDirectory); - assertTrue(file.exists()); + assertThat(file.exists()).isTrue(); } @Test @@ -99,7 +96,7 @@ public class FileUtilsTests { new File(this.originDirectory, "different.xml").createNewFile(); FileUtils.removeDuplicatesFromOutputDirectory(this.outputDirectory, this.originDirectory); - assertTrue(file.exists()); + assertThat(file.exists()).isTrue(); } @Test @@ -112,8 +109,8 @@ public class FileUtilsTests { finally { outputStream.close(); } - assertThat(FileUtils.sha1Hash(file), - equalTo("7037807198c22a7d2b0807371d763779a84fdfcf")); + assertThat(FileUtils.sha1Hash(file)) + .isEqualTo("7037807198c22a7d2b0807371d763779a84fdfcf"); } } diff --git a/spring-boot-tools/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/JvmUtilsTests.java b/spring-boot-tools/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/JvmUtilsTests.java index 8bcb4e054f..f4e321f0bf 100644 --- a/spring-boot-tools/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/JvmUtilsTests.java +++ b/spring-boot-tools/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/JvmUtilsTests.java @@ -21,9 +21,7 @@ import java.net.URL; import org.junit.Test; -import static org.hamcrest.Matchers.endsWith; -import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link JvmUtils}. @@ -36,8 +34,8 @@ public class JvmUtilsTests { public void getToolsJar() throws Exception { URL jarUrl = JvmUtils.getToolsJarUrl(); // System.out.println(jarUrl); - assertThat(jarUrl.toString(), endsWith(".jar")); - assertThat(new File(jarUrl.toURI()).exists(), equalTo(true)); + assertThat(jarUrl.toString()).endsWith(".jar"); + assertThat(new File(jarUrl.toURI()).exists()).isTrue(); } } diff --git a/spring-boot-tools/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/LayoutsTests.java b/spring-boot-tools/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/LayoutsTests.java index 8fc7597924..42ee8fad23 100644 --- a/spring-boot-tools/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/LayoutsTests.java +++ b/spring-boot-tools/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/LayoutsTests.java @@ -22,10 +22,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.instanceOf; -import static org.hamcrest.Matchers.nullValue; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link Layouts}. @@ -40,18 +37,20 @@ public class LayoutsTests { @Test public void jarFile() throws Exception { - assertThat(Layouts.forFile(new File("test.jar")), instanceOf(Layouts.Jar.class)); - assertThat(Layouts.forFile(new File("test.JAR")), instanceOf(Layouts.Jar.class)); - assertThat(Layouts.forFile(new File("test.jAr")), instanceOf(Layouts.Jar.class)); - assertThat(Layouts.forFile(new File("te.st.jar")), instanceOf(Layouts.Jar.class)); + assertThat(Layouts.forFile(new File("test.jar"))).isInstanceOf(Layouts.Jar.class); + assertThat(Layouts.forFile(new File("test.JAR"))).isInstanceOf(Layouts.Jar.class); + assertThat(Layouts.forFile(new File("test.jAr"))).isInstanceOf(Layouts.Jar.class); + assertThat(Layouts.forFile(new File("te.st.jar"))) + .isInstanceOf(Layouts.Jar.class); } @Test public void warFile() throws Exception { - assertThat(Layouts.forFile(new File("test.war")), instanceOf(Layouts.War.class)); - assertThat(Layouts.forFile(new File("test.WAR")), instanceOf(Layouts.War.class)); - assertThat(Layouts.forFile(new File("test.wAr")), instanceOf(Layouts.War.class)); - assertThat(Layouts.forFile(new File("te.st.war")), instanceOf(Layouts.War.class)); + assertThat(Layouts.forFile(new File("test.war"))).isInstanceOf(Layouts.War.class); + assertThat(Layouts.forFile(new File("test.WAR"))).isInstanceOf(Layouts.War.class); + assertThat(Layouts.forFile(new File("test.wAr"))).isInstanceOf(Layouts.War.class); + assertThat(Layouts.forFile(new File("te.st.war"))) + .isInstanceOf(Layouts.War.class); } @Test @@ -64,40 +63,40 @@ public class LayoutsTests { @Test public void jarLayout() throws Exception { Layout layout = new Layouts.Jar(); - assertThat(layout.getLibraryDestination("lib.jar", LibraryScope.COMPILE), - equalTo("lib/")); - assertThat(layout.getLibraryDestination("lib.jar", LibraryScope.CUSTOM), - equalTo("lib/")); - assertThat(layout.getLibraryDestination("lib.jar", LibraryScope.PROVIDED), - equalTo("lib/")); - assertThat(layout.getLibraryDestination("lib.jar", LibraryScope.RUNTIME), - equalTo("lib/")); + assertThat(layout.getLibraryDestination("lib.jar", LibraryScope.COMPILE)) + .isEqualTo("lib/"); + assertThat(layout.getLibraryDestination("lib.jar", LibraryScope.CUSTOM)) + .isEqualTo("lib/"); + assertThat(layout.getLibraryDestination("lib.jar", LibraryScope.PROVIDED)) + .isEqualTo("lib/"); + assertThat(layout.getLibraryDestination("lib.jar", LibraryScope.RUNTIME)) + .isEqualTo("lib/"); } @Test public void warLayout() throws Exception { Layout layout = new Layouts.War(); - assertThat(layout.getLibraryDestination("lib.jar", LibraryScope.COMPILE), - equalTo("WEB-INF/lib/")); - assertThat(layout.getLibraryDestination("lib.jar", LibraryScope.CUSTOM), - equalTo("WEB-INF/lib/")); - assertThat(layout.getLibraryDestination("lib.jar", LibraryScope.PROVIDED), - equalTo("WEB-INF/lib-provided/")); - assertThat(layout.getLibraryDestination("lib.jar", LibraryScope.RUNTIME), - equalTo("WEB-INF/lib/")); + assertThat(layout.getLibraryDestination("lib.jar", LibraryScope.COMPILE)) + .isEqualTo("WEB-INF/lib/"); + assertThat(layout.getLibraryDestination("lib.jar", LibraryScope.CUSTOM)) + .isEqualTo("WEB-INF/lib/"); + assertThat(layout.getLibraryDestination("lib.jar", LibraryScope.PROVIDED)) + .isEqualTo("WEB-INF/lib-provided/"); + assertThat(layout.getLibraryDestination("lib.jar", LibraryScope.RUNTIME)) + .isEqualTo("WEB-INF/lib/"); } @Test public void moduleLayout() throws Exception { Layout layout = new Layouts.Module(); - assertThat(layout.getLibraryDestination("lib.jar", LibraryScope.COMPILE), - equalTo("lib/")); - assertThat(layout.getLibraryDestination("lib.jar", LibraryScope.PROVIDED), - nullValue()); - assertThat(layout.getLibraryDestination("lib.jar", LibraryScope.RUNTIME), - equalTo("lib/")); - assertThat(layout.getLibraryDestination("lib.jar", LibraryScope.CUSTOM), - equalTo("lib/")); + assertThat(layout.getLibraryDestination("lib.jar", LibraryScope.COMPILE)) + .isEqualTo("lib/"); + assertThat(layout.getLibraryDestination("lib.jar", LibraryScope.PROVIDED)) + .isNull(); + assertThat(layout.getLibraryDestination("lib.jar", LibraryScope.RUNTIME)) + .isEqualTo("lib/"); + assertThat(layout.getLibraryDestination("lib.jar", LibraryScope.CUSTOM)) + .isEqualTo("lib/"); } } diff --git a/spring-boot-tools/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/MainClassFinderTests.java b/spring-boot-tools/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/MainClassFinderTests.java index fe2062e943..9d7d196d29 100644 --- a/spring-boot-tools/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/MainClassFinderTests.java +++ b/spring-boot-tools/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/MainClassFinderTests.java @@ -30,8 +30,7 @@ import org.springframework.boot.loader.tools.MainClassFinder.ClassNameCallback; import org.springframework.boot.loader.tools.sample.ClassWithMainMethod; import org.springframework.boot.loader.tools.sample.ClassWithoutMainMethod; -import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link MainClassFinder}. @@ -58,7 +57,7 @@ public class MainClassFinderTests { this.testJarFile.addClass("B.class", ClassWithMainMethod.class); this.testJarFile.addClass("A.class", ClassWithoutMainMethod.class); String actual = MainClassFinder.findMainClass(this.testJarFile.getJarFile(), ""); - assertThat(actual, equalTo("B")); + assertThat(actual).isEqualTo("B"); } @Test @@ -67,7 +66,7 @@ public class MainClassFinderTests { this.testJarFile.addClass("a/b/c/E.class", ClassWithoutMainMethod.class); this.testJarFile.addClass("a/b/F.class", ClassWithoutMainMethod.class); String actual = MainClassFinder.findMainClass(this.testJarFile.getJarFile(), ""); - assertThat(actual, equalTo("a.b.c.D")); + assertThat(actual).isEqualTo("a.b.c.D"); } @Test @@ -75,7 +74,7 @@ public class MainClassFinderTests { this.testJarFile.addClass("a/B.class", ClassWithMainMethod.class); this.testJarFile.addClass("a/b/c/E.class", ClassWithMainMethod.class); String actual = MainClassFinder.findMainClass(this.testJarFile.getJarFile(), ""); - assertThat(actual, equalTo("a.B")); + assertThat(actual).isEqualTo("a.B"); } @Test @@ -94,7 +93,7 @@ public class MainClassFinderTests { this.testJarFile.addClass("a/b/c/E.class", ClassWithMainMethod.class); String actual = MainClassFinder.findMainClass(this.testJarFile.getJarFile(), "a/"); - assertThat(actual, equalTo("B")); + assertThat(actual).isEqualTo("B"); } @@ -103,7 +102,7 @@ public class MainClassFinderTests { this.testJarFile.addClass("B.class", ClassWithMainMethod.class); this.testJarFile.addClass("A.class", ClassWithoutMainMethod.class); String actual = MainClassFinder.findMainClass(this.testJarFile.getJarSource()); - assertThat(actual, equalTo("B")); + assertThat(actual).isEqualTo("B"); } @Test @@ -112,7 +111,7 @@ public class MainClassFinderTests { this.testJarFile.addClass("a/b/c/E.class", ClassWithoutMainMethod.class); this.testJarFile.addClass("a/b/F.class", ClassWithoutMainMethod.class); String actual = MainClassFinder.findMainClass(this.testJarFile.getJarSource()); - assertThat(actual, equalTo("a.b.c.D")); + assertThat(actual).isEqualTo("a.b.c.D"); } @Test @@ -120,7 +119,7 @@ public class MainClassFinderTests { this.testJarFile.addClass("a/B.class", ClassWithMainMethod.class); this.testJarFile.addClass("a/b/c/E.class", ClassWithMainMethod.class); String actual = MainClassFinder.findMainClass(this.testJarFile.getJarSource()); - assertThat(actual, equalTo("a.B")); + assertThat(actual).isEqualTo("a.B"); } @Test @@ -141,7 +140,7 @@ public class MainClassFinderTests { this.testJarFile.addClass("a/b/G.class", ClassWithMainMethod.class); ClassNameCollector callback = new ClassNameCollector(); MainClassFinder.doWithMainClasses(this.testJarFile.getJarSource(), callback); - assertThat(callback.getClassNames().toString(), equalTo("[a.b.G, a.b.c.D]")); + assertThat(callback.getClassNames().toString()).isEqualTo("[a.b.G, a.b.c.D]"); } @Test @@ -152,7 +151,7 @@ public class MainClassFinderTests { this.testJarFile.addClass("a/b/G.class", ClassWithMainMethod.class); ClassNameCollector callback = new ClassNameCollector(); MainClassFinder.doWithMainClasses(this.testJarFile.getJarFile(), "", callback); - assertThat(callback.getClassNames().toString(), equalTo("[a.b.G, a.b.c.D]")); + assertThat(callback.getClassNames().toString()).isEqualTo("[a.b.G, a.b.c.D]"); } private static class ClassNameCollector implements ClassNameCallback { diff --git a/spring-boot-tools/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/RepackagerTests.java b/spring-boot-tools/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/RepackagerTests.java index 78ecccfc39..8d0e2707f4 100644 --- a/spring-boot-tools/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/RepackagerTests.java +++ b/spring-boot-tools/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/RepackagerTests.java @@ -38,10 +38,7 @@ import org.springframework.boot.loader.tools.sample.ClassWithMainMethod; import org.springframework.boot.loader.tools.sample.ClassWithoutMainMethod; import org.springframework.util.FileCopyUtils; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.hasItem; -import static org.hamcrest.Matchers.startsWith; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.BDDMockito.given; import static org.mockito.Matchers.anyString; import static org.mockito.Matchers.eq; @@ -112,11 +109,11 @@ public class RepackagerTests { repackager.setMainClass("a.b.C"); repackager.repackage(NO_LIBRARIES); Manifest actualManifest = getManifest(file); - assertThat(actualManifest.getMainAttributes().getValue("Main-Class"), - equalTo("org.springframework.boot.loader.JarLauncher")); - assertThat(actualManifest.getMainAttributes().getValue("Start-Class"), - equalTo("a.b.C")); - assertThat(hasLauncherClasses(file), equalTo(true)); + assertThat(actualManifest.getMainAttributes().getValue("Main-Class")) + .isEqualTo("org.springframework.boot.loader.JarLauncher"); + assertThat(actualManifest.getMainAttributes().getValue("Start-Class")) + .isEqualTo("a.b.C"); + assertThat(hasLauncherClasses(file)).isTrue(); } @Test @@ -130,11 +127,11 @@ public class RepackagerTests { Repackager repackager = new Repackager(file); repackager.repackage(NO_LIBRARIES); Manifest actualManifest = getManifest(file); - assertThat(actualManifest.getMainAttributes().getValue("Main-Class"), - equalTo("org.springframework.boot.loader.JarLauncher")); - assertThat(actualManifest.getMainAttributes().getValue("Start-Class"), - equalTo("a.b.C")); - assertThat(hasLauncherClasses(file), equalTo(true)); + assertThat(actualManifest.getMainAttributes().getValue("Main-Class")) + .isEqualTo("org.springframework.boot.loader.JarLauncher"); + assertThat(actualManifest.getMainAttributes().getValue("Start-Class")) + .isEqualTo("a.b.C"); + assertThat(hasLauncherClasses(file)).isTrue(); } @Test @@ -144,11 +141,11 @@ public class RepackagerTests { Repackager repackager = new Repackager(file); repackager.repackage(NO_LIBRARIES); Manifest actualManifest = getManifest(file); - assertThat(actualManifest.getMainAttributes().getValue("Main-Class"), - equalTo("org.springframework.boot.loader.JarLauncher")); - assertThat(actualManifest.getMainAttributes().getValue("Start-Class"), - equalTo("a.b.C")); - assertThat(hasLauncherClasses(file), equalTo(true)); + assertThat(actualManifest.getMainAttributes().getValue("Main-Class")) + .isEqualTo("org.springframework.boot.loader.JarLauncher"); + assertThat(actualManifest.getMainAttributes().getValue("Start-Class")) + .isEqualTo("a.b.C"); + assertThat(hasLauncherClasses(file)).isTrue(); } @Test @@ -159,11 +156,11 @@ public class RepackagerTests { repackager.repackage(NO_LIBRARIES); repackager.repackage(NO_LIBRARIES); Manifest actualManifest = getManifest(file); - assertThat(actualManifest.getMainAttributes().getValue("Main-Class"), - equalTo("org.springframework.boot.loader.JarLauncher")); - assertThat(actualManifest.getMainAttributes().getValue("Start-Class"), - equalTo("a.b.C")); - assertThat(hasLauncherClasses(file), equalTo(true)); + assertThat(actualManifest.getMainAttributes().getValue("Main-Class")) + .isEqualTo("org.springframework.boot.loader.JarLauncher"); + assertThat(actualManifest.getMainAttributes().getValue("Start-Class")) + .isEqualTo("a.b.C"); + assertThat(hasLauncherClasses(file)).isTrue(); } @Test @@ -194,9 +191,9 @@ public class RepackagerTests { repackager.setLayout(new Layouts.None()); repackager.repackage(file, NO_LIBRARIES); Manifest actualManifest = getManifest(file); - assertThat(actualManifest.getMainAttributes().getValue("Main-Class"), - equalTo("a.b.C")); - assertThat(hasLauncherClasses(file), equalTo(false)); + assertThat(actualManifest.getMainAttributes().getValue("Main-Class")) + .isEqualTo("a.b.C"); + assertThat(hasLauncherClasses(file)).isFalse(); } @Test @@ -207,9 +204,9 @@ public class RepackagerTests { repackager.setLayout(new Layouts.None()); repackager.repackage(file, NO_LIBRARIES); Manifest actualManifest = getManifest(file); - assertThat(actualManifest.getMainAttributes().getValue("Main-Class"), - equalTo(null)); - assertThat(hasLauncherClasses(file), equalTo(false)); + assertThat(actualManifest.getMainAttributes().getValue("Main-Class")) + .isEqualTo(null); + assertThat(hasLauncherClasses(file)).isFalse(); } @Test @@ -218,9 +215,8 @@ public class RepackagerTests { File file = this.testJarFile.getFile(); Repackager repackager = new Repackager(file); repackager.repackage(NO_LIBRARIES); - assertThat(new File(file.getParent(), file.getName() + ".original").exists(), - equalTo(true)); - assertThat(hasLauncherClasses(file), equalTo(true)); + assertThat(new File(file.getParent(), file.getName() + ".original")).exists(); + assertThat(hasLauncherClasses(file)).isTrue(); } @Test @@ -230,9 +226,9 @@ public class RepackagerTests { Repackager repackager = new Repackager(file); repackager.setBackupSource(false); repackager.repackage(NO_LIBRARIES); - assertThat(new File(file.getParent(), file.getName() + ".original").exists(), - equalTo(false)); - assertThat(hasLauncherClasses(file), equalTo(true)); + assertThat(new File(file.getParent(), file.getName() + ".original")) + .doesNotExist(); + assertThat(hasLauncherClasses(file)).isTrue(); } @Test @@ -242,10 +238,10 @@ public class RepackagerTests { File dest = this.temporaryFolder.newFile("different.jar"); Repackager repackager = new Repackager(source); repackager.repackage(dest, NO_LIBRARIES); - assertThat(new File(source.getParent(), source.getName() + ".original").exists(), - equalTo(false)); - assertThat(hasLauncherClasses(source), equalTo(false)); - assertThat(hasLauncherClasses(dest), equalTo(true)); + assertThat(new File(source.getParent(), source.getName() + ".original")) + .doesNotExist(); + assertThat(hasLauncherClasses(source)).isFalse(); + assertThat(hasLauncherClasses(dest)).isTrue(); } @Test @@ -273,7 +269,7 @@ public class RepackagerTests { File dest = this.temporaryFolder.newFile("dest.jar"); dest.createNewFile(); repackager.repackage(dest, NO_LIBRARIES); - assertThat(hasLauncherClasses(dest), equalTo(true)); + assertThat(hasLauncherClasses(dest)).isTrue(); } @Test @@ -309,14 +305,14 @@ public class RepackagerTests { callback.library(new Library(libNonJarFile, LibraryScope.COMPILE)); } }); - assertThat(hasEntry(file, "lib/" + libJarFile.getName()), equalTo(true)); - assertThat(hasEntry(file, "lib/" + libJarFileToUnpack.getName()), equalTo(true)); - assertThat(hasEntry(file, "lib/" + libNonJarFile.getName()), equalTo(false)); + assertThat(hasEntry(file, "lib/" + libJarFile.getName())).isTrue(); + assertThat(hasEntry(file, "lib/" + libJarFileToUnpack.getName())).isTrue(); + assertThat(hasEntry(file, "lib/" + libNonJarFile.getName())).isFalse(); JarEntry entry = getEntry(file, "lib/" + libJarFile.getName()); - assertThat(entry.getTime(), equalTo(JAN_1_1985)); + assertThat(entry.getTime()).isEqualTo(JAN_1_1985); entry = getEntry(file, "lib/" + libJarFileToUnpack.getName()); - assertThat(entry.getComment(), startsWith("UNPACK:")); - assertThat(entry.getComment().length(), equalTo(47)); + assertThat(entry.getComment()).startsWith("UNPACK:"); + assertThat(entry.getComment().length()).isEqualTo(47); } @Test @@ -357,9 +353,9 @@ public class RepackagerTests { callback.library(new Library(libJarFile, scope)); } }); - assertThat(hasEntry(file, "test/" + libJarFile.getName()), equalTo(true)); - assertThat(getManifest(file).getMainAttributes().getValue("Main-Class"), - equalTo("testLauncher")); + assertThat(hasEntry(file, "test/" + libJarFile.getName())).isTrue(); + assertThat(getManifest(file).getMainAttributes().getValue("Main-Class")) + .isEqualTo("testLauncher"); } @Test @@ -369,8 +365,8 @@ public class RepackagerTests { Repackager repackager = new Repackager(file); repackager.repackage(NO_LIBRARIES); Manifest actualManifest = getManifest(file); - assertThat(actualManifest.getMainAttributes() - .containsKey(new Attributes.Name("Spring-Boot-Version")), equalTo(true)); + assertThat(actualManifest.getMainAttributes()) + .containsKey(new Attributes.Name("Spring-Boot-Version")); } @Test @@ -399,10 +395,10 @@ public class RepackagerTests { }); JarFile jarFile = new JarFile(file); try { - assertThat(jarFile.getEntry("lib/" + nestedFile.getName()).getMethod(), - equalTo(ZipEntry.STORED)); - assertThat(jarFile.getEntry("test/nested.jar").getMethod(), - equalTo(ZipEntry.STORED)); + assertThat(jarFile.getEntry("lib/" + nestedFile.getName()).getMethod()) + .isEqualTo(ZipEntry.STORED); + assertThat(jarFile.getEntry("test/nested.jar").getMethod()) + .isEqualTo(ZipEntry.STORED); } finally { jarFile.close(); @@ -418,12 +414,12 @@ public class RepackagerTests { LaunchScript script = new MockLauncherScript("ABC"); repackager.repackage(dest, NO_LIBRARIES, script); byte[] bytes = FileCopyUtils.copyToByteArray(dest); - assertThat(new String(bytes), startsWith("ABC")); - assertThat(hasLauncherClasses(source), equalTo(false)); - assertThat(hasLauncherClasses(dest), equalTo(true)); + assertThat(new String(bytes)).startsWith("ABC"); + assertThat(hasLauncherClasses(source)).isFalse(); + assertThat(hasLauncherClasses(dest)).isTrue(); try { - assertThat(Files.getPosixFilePermissions(dest.toPath()), - hasItem(PosixFilePermission.OWNER_EXECUTE)); + assertThat(Files.getPosixFilePermissions(dest.toPath())) + .contains(PosixFilePermission.OWNER_EXECUTE); } catch (UnsupportedOperationException ex) { // Probably running the test on Windows @@ -450,8 +446,8 @@ public class RepackagerTests { }); JarFile jarFile = new JarFile(file); try { - assertThat(jarFile.getEntry("lib/" + nestedFile.getName()).getComment(), - startsWith("UNPACK:")); + assertThat(jarFile.getEntry("lib/" + nestedFile.getName()).getComment()) + .startsWith("UNPACK:"); } finally { jarFile.close(); @@ -482,8 +478,8 @@ public class RepackagerTests { }); JarFile jarFile = new JarFile(file); try { - assertThat(jarFile.getEntry("lib/" + nestedFile.getName()).getSize(), - equalTo(sourceLength)); + assertThat(jarFile.getEntry("lib/" + nestedFile.getName()).getSize()) + .isEqualTo(sourceLength); } finally { jarFile.close(); diff --git a/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/ExecutableArchiveLauncherTests.java b/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/ExecutableArchiveLauncherTests.java index 4d8846835e..cadfba4fe5 100644 --- a/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/ExecutableArchiveLauncherTests.java +++ b/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/ExecutableArchiveLauncherTests.java @@ -28,8 +28,7 @@ import org.mockito.MockitoAnnotations; import org.springframework.boot.loader.archive.Archive.Entry; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.BDDMockito.given; /** @@ -87,8 +86,8 @@ public class ExecutableArchiveLauncherTests { } private void assertClassLoaderUrls(ClassLoader classLoader, URL[] urls) { - assertTrue(classLoader instanceof URLClassLoader); - assertArrayEquals(urls, ((URLClassLoader) classLoader).getURLs()); + assertThat(classLoader).isInstanceOf(URLClassLoader.class); + assertThat(((URLClassLoader) classLoader).getURLs()).isEqualTo(urls); } private void doWithTccl(ClassLoader classLoader, Callable action) diff --git a/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/InputArgumentsJavaAgentDetectorTests.java b/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/InputArgumentsJavaAgentDetectorTests.java index f4d930a992..5ca75e65e0 100644 --- a/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/InputArgumentsJavaAgentDetectorTests.java +++ b/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/InputArgumentsJavaAgentDetectorTests.java @@ -23,8 +23,7 @@ import java.util.Arrays; 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 InputArgumentsJavaAgentDetector} @@ -38,24 +37,25 @@ public class InputArgumentsJavaAgentDetectorTests { throws MalformedURLException, IOException { InputArgumentsJavaAgentDetector detector = new InputArgumentsJavaAgentDetector( Arrays.asList("-javaagent:my-agent.jar")); - assertFalse(detector.isJavaAgentJar( - new File("something-else.jar").getCanonicalFile().toURI().toURL())); + assertThat(detector.isJavaAgentJar( + new File("something-else.jar").getCanonicalFile().toURI().toURL())) + .isFalse(); } @Test public void singleJavaAgent() throws MalformedURLException, IOException { InputArgumentsJavaAgentDetector detector = new InputArgumentsJavaAgentDetector( Arrays.asList("-javaagent:my-agent.jar")); - assertTrue(detector.isJavaAgentJar( - new File("my-agent.jar").getCanonicalFile().toURI().toURL())); + assertThat(detector.isJavaAgentJar( + new File("my-agent.jar").getCanonicalFile().toURI().toURL())).isTrue(); } @Test public void singleJavaAgentWithOptions() throws MalformedURLException, IOException { InputArgumentsJavaAgentDetector detector = new InputArgumentsJavaAgentDetector( Arrays.asList("-javaagent:my-agent.jar=a=alpha,b=bravo")); - assertTrue(detector.isJavaAgentJar( - new File("my-agent.jar").getCanonicalFile().toURI().toURL())); + assertThat(detector.isJavaAgentJar( + new File("my-agent.jar").getCanonicalFile().toURI().toURL())).isTrue(); } @Test @@ -63,10 +63,11 @@ public class InputArgumentsJavaAgentDetectorTests { InputArgumentsJavaAgentDetector detector = new InputArgumentsJavaAgentDetector( Arrays.asList("-javaagent:my-agent.jar", "-javaagent:my-other-agent.jar")); - assertTrue(detector.isJavaAgentJar( - new File("my-agent.jar").getCanonicalFile().toURI().toURL())); - assertTrue(detector.isJavaAgentJar( - new File("my-other-agent.jar").getCanonicalFile().toURI().toURL())); + assertThat(detector.isJavaAgentJar( + new File("my-agent.jar").getCanonicalFile().toURI().toURL())).isTrue(); + assertThat(detector.isJavaAgentJar( + new File("my-other-agent.jar").getCanonicalFile().toURI().toURL())) + .isTrue(); } } diff --git a/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/LaunchedURLClassLoaderTests.java b/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/LaunchedURLClassLoaderTests.java index 498796e7d9..bcb9b997d6 100644 --- a/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/LaunchedURLClassLoaderTests.java +++ b/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/LaunchedURLClassLoaderTests.java @@ -25,11 +25,7 @@ import org.junit.rules.TemporaryFolder; import org.springframework.boot.loader.jar.JarFile; -import static org.hamcrest.Matchers.equalTo; -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; /** * Tests for {@link LaunchedURLClassLoader}. @@ -47,13 +43,13 @@ public class LaunchedURLClassLoaderTests { public void resolveResourceFromWindowsFilesystem() throws Exception { // This path is invalid - it should return null even on Windows. // A regular URLClassLoader will deal with it gracefully. - assertNull(getClass().getClassLoader() - .getResource("c:\\Users\\user\\bar.properties")); + assertThat(getClass().getClassLoader() + .getResource("c:\\Users\\user\\bar.properties")).isNull(); LaunchedURLClassLoader loader = new LaunchedURLClassLoader( new URL[] { new URL("jar:file:src/test/resources/jars/app.jar!/") }, getClass().getClassLoader()); // So we should too... - assertNull(loader.getResource("c:\\Users\\user\\bar.properties")); + assertThat(loader.getResource("c:\\Users\\user\\bar.properties")).isNull(); } @Test @@ -61,7 +57,7 @@ public class LaunchedURLClassLoaderTests { LaunchedURLClassLoader loader = new LaunchedURLClassLoader( new URL[] { new URL("jar:file:src/test/resources/jars/app.jar!/") }, getClass().getClassLoader()); - assertNotNull(loader.getResource("demo/Application.java")); + assertThat(loader.getResource("demo/Application.java")).isNotNull(); } @Test @@ -69,7 +65,8 @@ public class LaunchedURLClassLoaderTests { LaunchedURLClassLoader loader = new LaunchedURLClassLoader( new URL[] { new URL("jar:file:src/test/resources/jars/app.jar!/") }, getClass().getClassLoader()); - assertTrue(loader.getResources("demo/Application.java").hasMoreElements()); + assertThat(loader.getResources("demo/Application.java").hasMoreElements()) + .isTrue(); } @Test @@ -77,7 +74,7 @@ public class LaunchedURLClassLoaderTests { LaunchedURLClassLoader loader = new LaunchedURLClassLoader( new URL[] { new URL("jar:file:src/test/resources/jars/app.jar!/") }, getClass().getClassLoader()); - assertNotNull(loader.getResource("")); + assertThat(loader.getResource("")).isNotNull(); } @Test @@ -85,7 +82,7 @@ public class LaunchedURLClassLoaderTests { LaunchedURLClassLoader loader = new LaunchedURLClassLoader( new URL[] { new URL("jar:file:src/test/resources/jars/app.jar!/") }, getClass().getClassLoader()); - assertTrue(loader.getResources("").hasMoreElements()); + assertThat(loader.getResources("").hasMoreElements()).isTrue(); } @Test @@ -97,8 +94,8 @@ public class LaunchedURLClassLoaderTests { LaunchedURLClassLoader loader = new LaunchedURLClassLoader(new URL[] { url }, null); URL resource = loader.getResource("nested.jar!/3.dat"); - assertThat(resource.toString(), equalTo(url + "nested.jar!/3.dat")); - assertThat(resource.openConnection().getInputStream().read(), equalTo(3)); + assertThat(resource.toString()).isEqualTo(url + "nested.jar!/3.dat"); + assertThat(resource.openConnection().getInputStream().read()).isEqualTo(3); } } diff --git a/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/PropertiesLauncherTests.java b/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/PropertiesLauncherTests.java index bcaea1d186..d0fb1c4989 100644 --- a/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/PropertiesLauncherTests.java +++ b/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/PropertiesLauncherTests.java @@ -34,13 +34,7 @@ import org.mockito.MockitoAnnotations; import org.springframework.boot.loader.archive.Archive; import org.springframework.test.util.ReflectionTestUtils; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.is; -import static org.junit.Assert.assertEquals; -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.mockito.BDDMockito.given; import static org.mockito.Mockito.verify; @@ -78,31 +72,32 @@ public class PropertiesLauncherTests { @Test public void testDefaultHome() { PropertiesLauncher launcher = new PropertiesLauncher(); - assertEquals(new File(System.getProperty("loader.home")), - launcher.getHomeDirectory()); + assertThat(launcher.getHomeDirectory()) + .isEqualTo(new File(System.getProperty("loader.home"))); } @Test public void testUserSpecifiedMain() throws Exception { PropertiesLauncher launcher = new PropertiesLauncher(); - assertEquals("demo.Application", launcher.getMainClass()); - assertNull(System.getProperty("loader.main")); + assertThat(launcher.getMainClass()).isEqualTo("demo.Application"); + assertThat(System.getProperty("loader.main")).isNull(); } @Test public void testUserSpecifiedConfigName() throws Exception { System.setProperty("loader.config.name", "foo"); PropertiesLauncher launcher = new PropertiesLauncher(); - assertEquals("my.Application", launcher.getMainClass()); - assertEquals("[etc/]", - ReflectionTestUtils.getField(launcher, "paths").toString()); + assertThat(launcher.getMainClass()).isEqualTo("my.Application"); + assertThat(ReflectionTestUtils.getField(launcher, "paths").toString()) + .isEqualTo("[etc/]"); } @Test public void testUserSpecifiedDotPath() throws Exception { System.setProperty("loader.path", "."); PropertiesLauncher launcher = new PropertiesLauncher(); - assertEquals("[.]", ReflectionTestUtils.getField(launcher, "paths").toString()); + assertThat(ReflectionTestUtils.getField(launcher, "paths").toString()) + .isEqualTo("[.]"); } @Test @@ -110,8 +105,8 @@ public class PropertiesLauncherTests { System.setProperty("loader.path", "jars/*"); System.setProperty("loader.main", "demo.Application"); PropertiesLauncher launcher = new PropertiesLauncher(); - assertEquals("[jars/]", - ReflectionTestUtils.getField(launcher, "paths").toString()); + assertThat(ReflectionTestUtils.getField(launcher, "paths").toString()) + .isEqualTo("[jars/]"); launcher.launch(new String[0]); waitFor("Hello World"); } @@ -121,8 +116,8 @@ public class PropertiesLauncherTests { System.setProperty("loader.path", "jars/app.jar"); System.setProperty("loader.main", "demo.Application"); PropertiesLauncher launcher = new PropertiesLauncher(); - assertEquals("[jars/app.jar]", - ReflectionTestUtils.getField(launcher, "paths").toString()); + assertThat(ReflectionTestUtils.getField(launcher, "paths").toString()) + .isEqualTo("[jars/app.jar]"); launcher.launch(new String[0]); waitFor("Hello World"); } @@ -132,8 +127,8 @@ public class PropertiesLauncherTests { System.setProperty("loader.path", "./jars/app.jar"); System.setProperty("loader.main", "demo.Application"); PropertiesLauncher launcher = new PropertiesLauncher(); - assertEquals("[jars/app.jar]", - ReflectionTestUtils.getField(launcher, "paths").toString()); + assertThat(ReflectionTestUtils.getField(launcher, "paths").toString()) + .isEqualTo("[jars/app.jar]"); launcher.launch(new String[0]); waitFor("Hello World"); } @@ -143,8 +138,8 @@ public class PropertiesLauncherTests { System.setProperty("loader.path", "jars/app.jar"); System.setProperty("loader.classLoader", URLClassLoader.class.getName()); PropertiesLauncher launcher = new PropertiesLauncher(); - assertEquals("[jars/app.jar]", - ReflectionTestUtils.getField(launcher, "paths").toString()); + assertThat(ReflectionTestUtils.getField(launcher, "paths").toString()) + .isEqualTo("[jars/app.jar]"); launcher.launch(new String[0]); waitFor("Hello World"); } @@ -154,8 +149,8 @@ public class PropertiesLauncherTests { System.setProperty("loader.path", "more-jars/app.jar,jars/app.jar"); System.setProperty("loader.classLoader", URLClassLoader.class.getName()); PropertiesLauncher launcher = new PropertiesLauncher(); - assertEquals("[more-jars/app.jar, jars/app.jar]", - ReflectionTestUtils.getField(launcher, "paths").toString()); + assertThat(ReflectionTestUtils.getField(launcher, "paths").toString()) + .isEqualTo("[more-jars/app.jar, jars/app.jar]"); launcher.launch(new String[0]); waitFor("Hello Other World"); } @@ -165,8 +160,8 @@ public class PropertiesLauncherTests { System.setProperty("loader.classLoader", TestLoader.class.getName()); PropertiesLauncher launcher = new PropertiesLauncher(); ClassLoader loader = launcher.createClassLoader(Collections.emptyList()); - assertNotNull(loader); - assertEquals(TestLoader.class.getName(), loader.getClass().getName()); + assertThat(loader).isNotNull(); + assertThat(loader.getClass().getName()).isEqualTo(TestLoader.class.getName()); } @Test @@ -175,28 +170,29 @@ public class PropertiesLauncherTests { System.setProperty("loader.config.name", "foo"); System.setProperty("loader.config.location", "classpath:bar.properties"); PropertiesLauncher launcher = new PropertiesLauncher(); - assertEquals("my.BarApplication", launcher.getMainClass()); + assertThat(launcher.getMainClass()).isEqualTo("my.BarApplication"); } @Test public void testSystemPropertySpecifiedMain() throws Exception { System.setProperty("loader.main", "foo.Bar"); PropertiesLauncher launcher = new PropertiesLauncher(); - assertEquals("foo.Bar", launcher.getMainClass()); + assertThat(launcher.getMainClass()).isEqualTo("foo.Bar"); } @Test public void testSystemPropertiesSet() throws Exception { System.setProperty("loader.system", "true"); new PropertiesLauncher(); - assertEquals("demo.Application", System.getProperty("loader.main")); + assertThat(System.getProperty("loader.main")).isEqualTo("demo.Application"); } @Test public void testArgsEnhanced() throws Exception { System.setProperty("loader.args", "foo"); PropertiesLauncher launcher = new PropertiesLauncher(); - assertEquals("[foo, bar]", Arrays.asList(launcher.getArgs("bar")).toString()); + assertThat(Arrays.asList(launcher.getArgs("bar")).toString()) + .isEqualTo("[foo, bar]"); } @Test @@ -208,8 +204,7 @@ public class PropertiesLauncherTests { } List nonAgentArchives = new PropertiesLauncher(this.javaAgentDetector) .getClassPathArchives(); - assertThat(nonAgentArchives.size(), - is(equalTo(allArchives.size() - parentUrls.length))); + assertThat(nonAgentArchives).hasSize(allArchives.size() - parentUrls.length); for (URL url : parentUrls) { verify(this.javaAgentDetector).isJavaAgentJar(url); } @@ -223,7 +218,7 @@ public class PropertiesLauncherTests { Thread.sleep(50L); timeout = this.output.toString().contains(value); } - assertTrue("Timed out waiting for (" + value + ")", timeout); + assertThat(timeout).as("Timed out waiting for (" + value + ")").isTrue(); } public static class TestLoader extends URLClassLoader { diff --git a/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/WarLauncherTests.java b/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/WarLauncherTests.java index 53cc6cd749..6d1e7ad0e5 100644 --- a/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/WarLauncherTests.java +++ b/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/WarLauncherTests.java @@ -38,9 +38,7 @@ import org.springframework.boot.loader.archive.ExplodedArchive; import org.springframework.boot.loader.archive.JarFileArchive; import org.springframework.util.FileSystemUtils; -import static org.hamcrest.Matchers.hasItems; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link WarLauncher} @@ -61,28 +59,23 @@ public class WarLauncherTests { webInfLib.mkdirs(); File webInfLibFoo = new File(webInfLib, "foo.jar"); new JarOutputStream(new FileOutputStream(webInfLibFoo)).close(); - WarLauncher launcher = new WarLauncher(new ExplodedArchive(warRoot, true)); List archives = launcher.getClassPathArchives(); - assertEquals(2, archives.size()); - - assertThat(getUrls(archives), hasItems(webInfClasses.toURI().toURL(), - new URL("jar:" + webInfLibFoo.toURI().toURL() + "!/"))); + assertThat(archives).hasSize(2); + assertThat(getUrls(archives)).containsOnly(webInfClasses.toURI().toURL(), + new URL("jar:" + webInfLibFoo.toURI().toURL() + "!/")); } @Test public void archivedWarHasOnlyWebInfClassesAndContentsOfWebInfLibOnClasspath() throws Exception { File warRoot = createWarArchive(); - WarLauncher launcher = new WarLauncher(new JarFileArchive(warRoot)); List archives = launcher.getClassPathArchives(); - assertEquals(2, archives.size()); - - assertThat(getUrls(archives), - hasItems(new URL("jar:" + warRoot.toURI().toURL() - + "!/WEB-INF/classes!/"), - new URL("jar:" + warRoot.toURI().toURL() + "!/WEB-INF/lib/foo.jar!/"))); + assertThat(archives).hasSize(2); + assertThat(getUrls(archives)).containsOnly( + new URL("jar:" + warRoot.toURI().toURL() + "!/WEB-INF/classes!/"), + new URL("jar:" + warRoot.toURI().toURL() + "!/WEB-INF/lib/foo.jar!/")); } private Set getUrls(List archives) throws MalformedURLException { @@ -96,14 +89,11 @@ public class WarLauncherTests { private File createWarArchive() throws IOException, FileNotFoundException { File warRoot = new File("target/archive.war"); warRoot.delete(); - JarOutputStream jarOutputStream = new JarOutputStream( new FileOutputStream(warRoot)); - jarOutputStream.putNextEntry(new JarEntry("WEB-INF/")); jarOutputStream.putNextEntry(new JarEntry("WEB-INF/classes/")); jarOutputStream.putNextEntry(new JarEntry("WEB-INF/lib/")); - JarEntry webInfLibFoo = new JarEntry("WEB-INF/lib/foo.jar"); webInfLibFoo.setMethod(ZipEntry.STORED); ByteArrayOutputStream fooJarStream = new ByteArrayOutputStream(); @@ -114,7 +104,6 @@ public class WarLauncherTests { webInfLibFoo.setCrc(crc32.getValue()); jarOutputStream.putNextEntry(webInfLibFoo); jarOutputStream.write(fooJarStream.toByteArray()); - jarOutputStream.close(); return warRoot; } diff --git a/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/archive/ExplodedArchiveTests.java b/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/archive/ExplodedArchiveTests.java index 06a9ab5a08..bad8fef271 100644 --- a/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/archive/ExplodedArchiveTests.java +++ b/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/archive/ExplodedArchiveTests.java @@ -38,10 +38,7 @@ import org.junit.rules.TemporaryFolder; import org.springframework.boot.loader.TestJarCreator; import org.springframework.boot.loader.archive.Archive.Entry; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.greaterThan; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link ExplodedArchive}. @@ -93,29 +90,29 @@ public class ExplodedArchiveTests { @Test public void getManifest() throws Exception { - assertThat(this.archive.getManifest().getMainAttributes().getValue("Built-By"), - equalTo("j1")); + assertThat(this.archive.getManifest().getMainAttributes().getValue("Built-By")) + .isEqualTo("j1"); } @Test public void getEntries() throws Exception { Map entries = getEntriesMap(this.archive); - assertThat(entries.size(), equalTo(10)); + assertThat(entries.size()).isEqualTo(10); } @Test public void getUrl() throws Exception { URL url = this.archive.getUrl(); - assertThat(new File(URLDecoder.decode(url.getFile(), "UTF-8")), - equalTo(this.rootFolder)); + assertThat(new File(URLDecoder.decode(url.getFile(), "UTF-8"))) + .isEqualTo(this.rootFolder); } @Test public void getNestedArchive() throws Exception { Entry entry = getEntriesMap(this.archive).get("nested.jar"); Archive nested = this.archive.getNestedArchive(entry); - assertThat(nested.getUrl().toString(), - equalTo("jar:" + this.rootFolder.toURI() + "nested.jar!/")); + assertThat(nested.getUrl().toString()) + .isEqualTo("jar:" + this.rootFolder.toURI() + "nested.jar!/"); } @Test @@ -123,43 +120,44 @@ public class ExplodedArchiveTests { Entry entry = getEntriesMap(this.archive).get("d/"); Archive nested = this.archive.getNestedArchive(entry); Map nestedEntries = getEntriesMap(nested); - assertThat(nestedEntries.size(), equalTo(1)); - assertThat(nested.getUrl().toString(), - equalTo("file:" + this.rootFolder.toURI().getPath() + "d/")); + assertThat(nestedEntries.size()).isEqualTo(1); + assertThat(nested.getUrl().toString()) + .isEqualTo("file:" + this.rootFolder.toURI().getPath() + "d/"); } @Test public void getNonRecursiveEntriesForRoot() throws Exception { ExplodedArchive archive = new ExplodedArchive(new File("/"), false); Map entries = getEntriesMap(archive); - assertThat(entries.size(), greaterThan(1)); + assertThat(entries.size()).isGreaterThan(1); } @Test public void getNonRecursiveManifest() throws Exception { ExplodedArchive archive = new ExplodedArchive( new File("src/test/resources/root")); - assertNotNull(archive.getManifest()); + assertThat(archive.getManifest()).isNotNull(); Map entries = getEntriesMap(archive); - assertThat(entries.size(), equalTo(4)); + assertThat(entries.size()).isEqualTo(4); } @Test public void getNonRecursiveManifestEvenIfNonRecursive() throws Exception { ExplodedArchive archive = new ExplodedArchive(new File("src/test/resources/root"), false); - assertNotNull(archive.getManifest()); + assertThat(archive.getManifest()).isNotNull(); Map entries = getEntriesMap(archive); - assertThat(entries.size(), equalTo(3)); + assertThat(entries.size()).isEqualTo(3); } @Test public void getResourceAsStream() throws Exception { ExplodedArchive archive = new ExplodedArchive( new File("src/test/resources/root")); - assertNotNull(archive.getManifest()); + assertThat(archive.getManifest()).isNotNull(); URLClassLoader loader = new URLClassLoader(new URL[] { archive.getUrl() }); - assertNotNull(loader.getResourceAsStream("META-INF/spring/application.xml")); + assertThat(loader.getResourceAsStream("META-INF/spring/application.xml")) + .isNotNull(); loader.close(); } @@ -167,9 +165,10 @@ public class ExplodedArchiveTests { public void getResourceAsStreamNonRecursive() throws Exception { ExplodedArchive archive = new ExplodedArchive(new File("src/test/resources/root"), false); - assertNotNull(archive.getManifest()); + assertThat(archive.getManifest()).isNotNull(); URLClassLoader loader = new URLClassLoader(new URL[] { archive.getUrl() }); - assertNotNull(loader.getResourceAsStream("META-INF/spring/application.xml")); + assertThat(loader.getResourceAsStream("META-INF/spring/application.xml")) + .isNotNull(); loader.close(); } @@ -180,4 +179,5 @@ public class ExplodedArchiveTests { } return entries; } + } diff --git a/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/archive/JarFileArchiveTests.java b/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/archive/JarFileArchiveTests.java index 88c4b30a89..47241af3af 100644 --- a/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/archive/JarFileArchiveTests.java +++ b/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/archive/JarFileArchiveTests.java @@ -29,12 +29,7 @@ import org.junit.rules.TemporaryFolder; import org.springframework.boot.loader.TestJarCreator; import org.springframework.boot.loader.archive.Archive.Entry; -import static org.hamcrest.Matchers.endsWith; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.not; -import static org.hamcrest.Matchers.startsWith; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link JarFileArchive}. @@ -67,28 +62,28 @@ public class JarFileArchiveTests { @Test public void getManifest() throws Exception { - assertThat(this.archive.getManifest().getMainAttributes().getValue("Built-By"), - equalTo("j1")); + assertThat(this.archive.getManifest().getMainAttributes().getValue("Built-By")) + .isEqualTo("j1"); } @Test public void getEntries() throws Exception { Map entries = getEntriesMap(this.archive); - assertThat(entries.size(), equalTo(10)); + assertThat(entries.size()).isEqualTo(10); } @Test public void getUrl() throws Exception { URL url = this.archive.getUrl(); - assertThat(url.toString(), equalTo("jar:" + this.rootJarFileUrl + "!/")); + assertThat(url.toString()).isEqualTo("jar:" + this.rootJarFileUrl + "!/"); } @Test public void getNestedArchive() throws Exception { Entry entry = getEntriesMap(this.archive).get("nested.jar"); Archive nested = this.archive.getNestedArchive(entry); - assertThat(nested.getUrl().toString(), - equalTo("jar:" + this.rootJarFileUrl + "!/nested.jar!/")); + assertThat(nested.getUrl().toString()) + .isEqualTo("jar:" + this.rootJarFileUrl + "!/nested.jar!/"); } @Test @@ -96,8 +91,8 @@ public class JarFileArchiveTests { setup(true); Entry entry = getEntriesMap(this.archive).get("nested.jar"); Archive nested = this.archive.getNestedArchive(entry); - assertThat(nested.getUrl().toString(), startsWith("file:")); - assertThat(nested.getUrl().toString(), endsWith("/nested.jar")); + assertThat(nested.getUrl().toString()).startsWith("file:"); + assertThat(nested.getUrl().toString()).endsWith("/nested.jar"); } @Test @@ -108,7 +103,7 @@ public class JarFileArchiveTests { setup(true); entry = getEntriesMap(this.archive).get("nested.jar"); URL secondNested = this.archive.getNestedArchive(entry).getUrl(); - assertThat(secondNested, is(not(equalTo(firstNested)))); + assertThat(secondNested).isNotEqualTo(firstNested); } @Test @@ -122,7 +117,7 @@ public class JarFileArchiveTests { .getNestedArchive( getEntriesMap(this.archive).get("another-nested.jar")) .getUrl().toURI()); - assertThat(nested.getParent(), is(equalTo(anotherNested.getParent()))); + assertThat(nested.getParent()).isEqualTo(anotherNested.getParent()); } private Map getEntriesMap(Archive archive) { @@ -132,4 +127,5 @@ public class JarFileArchiveTests { } return entries; } + } diff --git a/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/data/ByteArrayRandomAccessDataTests.java b/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/data/ByteArrayRandomAccessDataTests.java index 793b6edb81..e2ae903fec 100644 --- a/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/data/ByteArrayRandomAccessDataTests.java +++ b/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/data/ByteArrayRandomAccessDataTests.java @@ -16,13 +16,14 @@ package org.springframework.boot.loader.data; +import java.io.InputStream; + import org.junit.Test; import org.springframework.boot.loader.data.RandomAccessData.ResourceAccess; import org.springframework.util.FileCopyUtils; -import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link ByteArrayRandomAccessData}. @@ -35,9 +36,9 @@ public class ByteArrayRandomAccessDataTests { public void testGetInputStream() throws Exception { byte[] bytes = new byte[] { 0, 1, 2, 3, 4, 5 }; RandomAccessData data = new ByteArrayRandomAccessData(bytes); - assertThat(FileCopyUtils.copyToByteArray( - data.getInputStream(ResourceAccess.PER_READ)), equalTo(bytes)); - assertThat(data.getSize(), equalTo((long) bytes.length)); + InputStream inputStream = data.getInputStream(ResourceAccess.PER_READ); + assertThat(FileCopyUtils.copyToByteArray(inputStream)).isEqualTo(bytes); + assertThat(data.getSize()).isEqualTo(bytes.length); } @Test @@ -45,10 +46,10 @@ public class ByteArrayRandomAccessDataTests { byte[] bytes = new byte[] { 0, 1, 2, 3, 4, 5 }; RandomAccessData data = new ByteArrayRandomAccessData(bytes); data = data.getSubsection(1, 4).getSubsection(1, 2); - assertThat( - FileCopyUtils - .copyToByteArray(data.getInputStream(ResourceAccess.PER_READ)), - equalTo(new byte[] { 2, 3 })); - assertThat(data.getSize(), equalTo(2L)); + InputStream inputStream = data.getInputStream(ResourceAccess.PER_READ); + assertThat(FileCopyUtils.copyToByteArray(inputStream)) + .isEqualTo(new byte[] { 2, 3 }); + assertThat(data.getSize()).isEqualTo(2L); } + } diff --git a/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/data/RandomAccessDataFileTests.java b/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/data/RandomAccessDataFileTests.java index 95dfc74721..d9fc7ac10b 100644 --- a/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/data/RandomAccessDataFileTests.java +++ b/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/data/RandomAccessDataFileTests.java @@ -29,7 +29,6 @@ import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; -import org.hamcrest.Matcher; import org.junit.After; import org.junit.Before; import org.junit.Rule; @@ -37,11 +36,9 @@ import org.junit.Test; import org.junit.rules.ExpectedException; import org.junit.rules.TemporaryFolder; -import org.springframework.boot.loader.ByteArrayStartsWith; import org.springframework.boot.loader.data.RandomAccessData.ResourceAccess; -import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link RandomAccessDataFile}. @@ -118,7 +115,7 @@ public class RandomAccessDataFileTests { @Test public void inputStreamRead() throws Exception { for (int i = 0; i <= 255; i++) { - assertThat(this.inputStream.read(), equalTo(i)); + assertThat(this.inputStream.read()).isEqualTo(i); } } @@ -140,8 +137,8 @@ public class RandomAccessDataFileTests { public void inputStreamReadBytes() throws Exception { byte[] b = new byte[256]; int amountRead = this.inputStream.read(b); - assertThat(b, equalTo(BYTES)); - assertThat(amountRead, equalTo(256)); + assertThat(b).isEqualTo(BYTES); + assertThat(amountRead).isEqualTo(256); } @Test @@ -149,54 +146,54 @@ public class RandomAccessDataFileTests { byte[] b = new byte[7]; this.inputStream.skip(1); int amountRead = this.inputStream.read(b, 2, 3); - assertThat(b, equalTo(new byte[] { 0, 0, 1, 2, 3, 0, 0 })); - assertThat(amountRead, equalTo(3)); + assertThat(b).isEqualTo(new byte[] { 0, 0, 1, 2, 3, 0, 0 }); + assertThat(amountRead).isEqualTo(3); } @Test public void inputStreamReadMoreBytesThanAvailable() throws Exception { byte[] b = new byte[257]; int amountRead = this.inputStream.read(b); - assertThat(b, startsWith(BYTES)); - assertThat(amountRead, equalTo(256)); + assertThat(b).startsWith(BYTES); + assertThat(amountRead).isEqualTo(256); } @Test public void inputStreamReadPastEnd() throws Exception { this.inputStream.skip(255); - assertThat(this.inputStream.read(), equalTo(0xFF)); - assertThat(this.inputStream.read(), equalTo(-1)); - assertThat(this.inputStream.read(), equalTo(-1)); + assertThat(this.inputStream.read()).isEqualTo(0xFF); + assertThat(this.inputStream.read()).isEqualTo(-1); + assertThat(this.inputStream.read()).isEqualTo(-1); } @Test public void inputStreamReadZeroLength() throws Exception { byte[] b = new byte[] { 0x0F }; int amountRead = this.inputStream.read(b, 0, 0); - assertThat(b, equalTo(new byte[] { 0x0F })); - assertThat(amountRead, equalTo(0)); - assertThat(this.inputStream.read(), equalTo(0)); + assertThat(b).isEqualTo(new byte[] { 0x0F }); + assertThat(amountRead).isEqualTo(0); + assertThat(this.inputStream.read()).isEqualTo(0); } @Test public void inputStreamSkip() throws Exception { long amountSkipped = this.inputStream.skip(4); - assertThat(this.inputStream.read(), equalTo(4)); - assertThat(amountSkipped, equalTo(4L)); + assertThat(this.inputStream.read()).isEqualTo(4); + assertThat(amountSkipped).isEqualTo(4L); } @Test public void inputStreamSkipMoreThanAvailable() throws Exception { long amountSkipped = this.inputStream.skip(257); - assertThat(this.inputStream.read(), equalTo(-1)); - assertThat(amountSkipped, equalTo(256L)); + assertThat(this.inputStream.read()).isEqualTo(-1); + assertThat(amountSkipped).isEqualTo(256L); } @Test public void inputStreamSkipPastEnd() throws Exception { this.inputStream.skip(256); long amountSkipped = this.inputStream.skip(1); - assertThat(amountSkipped, equalTo(0L)); + assertThat(amountSkipped).isEqualTo(0L); } @Test @@ -214,8 +211,8 @@ public class RandomAccessDataFileTests { @Test public void subsectionZeroLength() throws Exception { RandomAccessData subsection = this.file.getSubsection(0, 0); - assertThat(subsection.getInputStream(ResourceAccess.PER_READ).read(), - equalTo(-1)); + assertThat(subsection.getInputStream(ResourceAccess.PER_READ).read()) + .isEqualTo(-1); } @Test @@ -235,16 +232,17 @@ public class RandomAccessDataFileTests { @Test public void subsection() throws Exception { RandomAccessData subsection = this.file.getSubsection(1, 1); - assertThat(subsection.getInputStream(ResourceAccess.PER_READ).read(), equalTo(1)); + assertThat(subsection.getInputStream(ResourceAccess.PER_READ).read()) + .isEqualTo(1); } @Test public void inputStreamReadPastSubsection() throws Exception { RandomAccessData subsection = this.file.getSubsection(1, 2); InputStream inputStream = subsection.getInputStream(ResourceAccess.PER_READ); - assertThat(inputStream.read(), equalTo(1)); - assertThat(inputStream.read(), equalTo(2)); - assertThat(inputStream.read(), equalTo(-1)); + assertThat(inputStream.read()).isEqualTo(1); + assertThat(inputStream.read()).isEqualTo(2); + assertThat(inputStream.read()).isEqualTo(-1); } @Test @@ -253,26 +251,26 @@ public class RandomAccessDataFileTests { InputStream inputStream = subsection.getInputStream(ResourceAccess.PER_READ); byte[] b = new byte[3]; int amountRead = inputStream.read(b); - assertThat(b, equalTo(new byte[] { 1, 2, 0 })); - assertThat(amountRead, equalTo(2)); + assertThat(b).isEqualTo(new byte[] { 1, 2, 0 }); + assertThat(amountRead).isEqualTo(2); } @Test public void inputStreamSkipPastSubsection() throws Exception { RandomAccessData subsection = this.file.getSubsection(1, 2); InputStream inputStream = subsection.getInputStream(ResourceAccess.PER_READ); - assertThat(inputStream.skip(3), equalTo(2L)); - assertThat(inputStream.read(), equalTo(-1)); + assertThat(inputStream.skip(3)).isEqualTo(2L); + assertThat(inputStream.read()).isEqualTo(-1); } @Test public void inputStreamSkipNegative() throws Exception { - assertThat(this.inputStream.skip(-1), equalTo(0L)); + assertThat(this.inputStream.skip(-1)).isEqualTo(0L); } @Test public void getFile() throws Exception { - assertThat(this.file.getFile(), equalTo(this.tempFile)); + assertThat(this.file.getFile()).isEqualTo(this.tempFile); } @Test @@ -294,7 +292,7 @@ public class RandomAccessDataFileTests { })); } for (Future future : results) { - assertThat(future.get(), equalTo(true)); + assertThat(future.get()).isTrue(); } } @@ -308,11 +306,7 @@ public class RandomAccessDataFileTests { Field filesField = filePool.getClass().getDeclaredField("files"); filesField.setAccessible(true); Queue queue = (Queue) filesField.get(filePool); - assertThat(queue.size(), equalTo(0)); - } - - private static Matcher startsWith(byte[] bytes) { - return new ByteArrayStartsWith(bytes); + assertThat(queue.size()).isEqualTo(0); } } diff --git a/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/jar/AsciiBytesTests.java b/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/jar/AsciiBytesTests.java index 7fb75241d4..9453bdf43d 100644 --- a/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/jar/AsciiBytesTests.java +++ b/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/jar/AsciiBytesTests.java @@ -20,9 +20,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.not; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link AsciiBytes}. @@ -37,27 +35,27 @@ public class AsciiBytesTests { @Test public void createFromBytes() throws Exception { AsciiBytes bytes = new AsciiBytes(new byte[] { 65, 66 }); - assertThat(bytes.toString(), equalTo("AB")); + assertThat(bytes.toString()).isEqualTo("AB"); } @Test public void createFromBytesWithOffset() throws Exception { AsciiBytes bytes = new AsciiBytes(new byte[] { 65, 66, 67, 68 }, 1, 2); - assertThat(bytes.toString(), equalTo("BC")); + assertThat(bytes.toString()).isEqualTo("BC"); } @Test public void createFromString() throws Exception { AsciiBytes bytes = new AsciiBytes("AB"); - assertThat(bytes.toString(), equalTo("AB")); + assertThat(bytes.toString()).isEqualTo("AB"); } @Test public void length() throws Exception { AsciiBytes b1 = new AsciiBytes(new byte[] { 65, 66 }); AsciiBytes b2 = new AsciiBytes(new byte[] { 65, 66, 67, 68 }, 1, 2); - assertThat(b1.length(), equalTo(2)); - assertThat(b2.length(), equalTo(2)); + assertThat(b1.length()).isEqualTo(2); + assertThat(b2.length()).isEqualTo(2); } @Test @@ -66,10 +64,10 @@ public class AsciiBytesTests { AsciiBytes ab = new AsciiBytes(new byte[] { 65, 66 }); AsciiBytes bc = new AsciiBytes(new byte[] { 65, 66, 67 }, 1, 2); AsciiBytes abcd = new AsciiBytes(new byte[] { 65, 66, 67, 68 }); - assertThat(abc.startsWith(abc), equalTo(true)); - assertThat(abc.startsWith(ab), equalTo(true)); - assertThat(abc.startsWith(bc), equalTo(false)); - assertThat(abc.startsWith(abcd), equalTo(false)); + assertThat(abc.startsWith(abc)).isTrue(); + assertThat(abc.startsWith(ab)).isTrue(); + assertThat(abc.startsWith(bc)).isFalse(); + assertThat(abc.startsWith(abcd)).isFalse(); } @Test @@ -78,20 +76,20 @@ public class AsciiBytesTests { AsciiBytes bc = new AsciiBytes(new byte[] { 65, 66, 67 }, 1, 2); AsciiBytes ab = new AsciiBytes(new byte[] { 65, 66 }); AsciiBytes aabc = new AsciiBytes(new byte[] { 65, 65, 66, 67 }); - assertThat(abc.endsWith(abc), equalTo(true)); - assertThat(abc.endsWith(bc), equalTo(true)); - assertThat(abc.endsWith(ab), equalTo(false)); - assertThat(abc.endsWith(aabc), equalTo(false)); + assertThat(abc.endsWith(abc)).isTrue(); + assertThat(abc.endsWith(bc)).isTrue(); + assertThat(abc.endsWith(ab)).isFalse(); + assertThat(abc.endsWith(aabc)).isFalse(); } @Test public void substringFromBeingIndex() throws Exception { AsciiBytes abcd = new AsciiBytes(new byte[] { 65, 66, 67, 68 }); - assertThat(abcd.substring(0).toString(), equalTo("ABCD")); - assertThat(abcd.substring(1).toString(), equalTo("BCD")); - assertThat(abcd.substring(2).toString(), equalTo("CD")); - assertThat(abcd.substring(3).toString(), equalTo("D")); - assertThat(abcd.substring(4).toString(), equalTo("")); + assertThat(abcd.substring(0).toString()).isEqualTo("ABCD"); + assertThat(abcd.substring(1).toString()).isEqualTo("BCD"); + assertThat(abcd.substring(2).toString()).isEqualTo("CD"); + assertThat(abcd.substring(3).toString()).isEqualTo("D"); + assertThat(abcd.substring(4).toString()).isEqualTo(""); this.thrown.expect(IndexOutOfBoundsException.class); abcd.substring(5); } @@ -99,10 +97,10 @@ public class AsciiBytesTests { @Test public void substring() throws Exception { AsciiBytes abcd = new AsciiBytes(new byte[] { 65, 66, 67, 68 }); - assertThat(abcd.substring(0, 4).toString(), equalTo("ABCD")); - assertThat(abcd.substring(1, 3).toString(), equalTo("BC")); - assertThat(abcd.substring(3, 4).toString(), equalTo("D")); - assertThat(abcd.substring(3, 3).toString(), equalTo("")); + assertThat(abcd.substring(0, 4).toString()).isEqualTo("ABCD"); + assertThat(abcd.substring(1, 3).toString()).isEqualTo("BC"); + assertThat(abcd.substring(3, 4).toString()).isEqualTo("D"); + assertThat(abcd.substring(3, 3).toString()).isEqualTo(""); this.thrown.expect(IndexOutOfBoundsException.class); abcd.substring(3, 5); } @@ -111,16 +109,16 @@ public class AsciiBytesTests { public void appendString() throws Exception { AsciiBytes bc = new AsciiBytes(new byte[] { 65, 66, 67, 68 }, 1, 2); AsciiBytes appended = bc.append("D"); - assertThat(bc.toString(), equalTo("BC")); - assertThat(appended.toString(), equalTo("BCD")); + assertThat(bc.toString()).isEqualTo("BC"); + assertThat(appended.toString()).isEqualTo("BCD"); } @Test public void appendBytes() throws Exception { AsciiBytes bc = new AsciiBytes(new byte[] { 65, 66, 67, 68 }, 1, 2); AsciiBytes appended = bc.append(new byte[] { 68 }); - assertThat(bc.toString(), equalTo("BC")); - assertThat(appended.toString(), equalTo("BCD")); + assertThat(bc.toString()).isEqualTo("BC"); + assertThat(appended.toString()).isEqualTo("BCD"); } @Test @@ -130,28 +128,28 @@ public class AsciiBytesTests { AsciiBytes bc_substring = new AsciiBytes(new byte[] { 65, 66, 67, 68 }) .substring(1, 3); AsciiBytes bc_string = new AsciiBytes("BC"); - assertThat(bc.hashCode(), equalTo(bc.hashCode())); - assertThat(bc.hashCode(), equalTo(bc_substring.hashCode())); - assertThat(bc.hashCode(), equalTo(bc_string.hashCode())); - assertThat(bc, equalTo(bc)); - assertThat(bc, equalTo(bc_substring)); - assertThat(bc, equalTo(bc_string)); - assertThat(bc.hashCode(), not(equalTo(abcd.hashCode()))); - assertThat(bc, not(equalTo(abcd))); + assertThat(bc.hashCode()).isEqualTo(bc.hashCode()); + assertThat(bc.hashCode()).isEqualTo(bc_substring.hashCode()); + assertThat(bc.hashCode()).isEqualTo(bc_string.hashCode()); + assertThat(bc).isEqualTo(bc); + assertThat(bc).isEqualTo(bc_substring); + assertThat(bc).isEqualTo(bc_string); + assertThat(bc.hashCode()).isNotEqualTo(abcd.hashCode()); + assertThat(bc).isNotEqualTo(abcd); } @Test public void hashCodeSameAsString() throws Exception { String s = "abcABC123xyz!"; AsciiBytes a = new AsciiBytes(s); - assertThat(s.hashCode(), equalTo(a.hashCode())); + assertThat(s.hashCode()).isEqualTo(a.hashCode()); } @Test public void hashCodeSameAsStringWithSpecial() throws Exception { String s = "special/\u00EB.dat"; AsciiBytes a = new AsciiBytes(s); - assertThat(s.hashCode(), equalTo(a.hashCode())); + assertThat(s.hashCode()).isEqualTo(a.hashCode()); } } diff --git a/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/jar/CentralDirectoryParserTests.java b/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/jar/CentralDirectoryParserTests.java index 22b7aec18c..723e9afb9b 100644 --- a/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/jar/CentralDirectoryParserTests.java +++ b/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/jar/CentralDirectoryParserTests.java @@ -31,8 +31,7 @@ import org.springframework.boot.loader.TestJarCreator; import org.springframework.boot.loader.data.RandomAccessData; import org.springframework.boot.loader.data.RandomAccessDataFile; -import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyInt; import static org.mockito.Mockito.atLeastOnce; @@ -62,7 +61,7 @@ public class CentralDirectoryParserTests { @Test public void visitsInOrder() throws Exception { - CentralDirectoryVisitor visitor = mock(CentralDirectoryVisitor.class); + CentralDirectoryVisitor visitor = mock(TestCentralDirectoryVisitor.class); CentralDirectoryParser parser = new CentralDirectoryParser(); parser.addVisitor(visitor); parser.parse(this.jarData, false); @@ -81,17 +80,17 @@ public class CentralDirectoryParserTests { parser.addVisitor(collector); parser.parse(this.jarData, false); Iterator headers = collector.getHeaders().iterator(); - assertThat(headers.next().getName().toString(), equalTo("META-INF/")); - assertThat(headers.next().getName().toString(), equalTo("META-INF/MANIFEST.MF")); - assertThat(headers.next().getName().toString(), equalTo("1.dat")); - assertThat(headers.next().getName().toString(), equalTo("2.dat")); - assertThat(headers.next().getName().toString(), equalTo("d/")); - assertThat(headers.next().getName().toString(), equalTo("d/9.dat")); - assertThat(headers.next().getName().toString(), equalTo("special/")); - assertThat(headers.next().getName().toString(), equalTo("special/\u00EB.dat")); - assertThat(headers.next().getName().toString(), equalTo("nested.jar")); - assertThat(headers.next().getName().toString(), equalTo("another-nested.jar")); - assertThat(headers.hasNext(), equalTo(false)); + assertThat(headers.next().getName().toString()).isEqualTo("META-INF/"); + assertThat(headers.next().getName().toString()).isEqualTo("META-INF/MANIFEST.MF"); + assertThat(headers.next().getName().toString()).isEqualTo("1.dat"); + assertThat(headers.next().getName().toString()).isEqualTo("2.dat"); + assertThat(headers.next().getName().toString()).isEqualTo("d/"); + assertThat(headers.next().getName().toString()).isEqualTo("d/9.dat"); + assertThat(headers.next().getName().toString()).isEqualTo("special/"); + assertThat(headers.next().getName().toString()).isEqualTo("special/\u00EB.dat"); + assertThat(headers.next().getName().toString()).isEqualTo("nested.jar"); + assertThat(headers.next().getName().toString()).isEqualTo("another-nested.jar"); + assertThat(headers.hasNext()).isFalse(); } private static class Collector implements CentralDirectoryVisitor { @@ -119,4 +118,8 @@ public class CentralDirectoryParserTests { } + public interface TestCentralDirectoryVisitor extends CentralDirectoryVisitor { + + } + } diff --git a/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/jar/JarFileTests.java b/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/jar/JarFileTests.java index 20ec637fa2..85418c9cf7 100644 --- a/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/jar/JarFileTests.java +++ b/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/jar/JarFileTests.java @@ -41,14 +41,7 @@ import org.springframework.boot.loader.data.RandomAccessDataFile; import org.springframework.util.FileCopyUtils; import org.springframework.util.StreamUtils; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.greaterThan; -import static org.hamcrest.Matchers.instanceOf; -import static org.hamcrest.Matchers.notNullValue; -import static org.hamcrest.Matchers.nullValue; -import static org.hamcrest.Matchers.sameInstance; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.verify; @@ -82,21 +75,21 @@ public class JarFileTests { // Sanity checks to see how the default jar file operates java.util.jar.JarFile jarFile = new java.util.jar.JarFile(this.rootJarFile); Enumeration entries = jarFile.entries(); - assertThat(entries.nextElement().getName(), equalTo("META-INF/")); - assertThat(entries.nextElement().getName(), equalTo("META-INF/MANIFEST.MF")); - assertThat(entries.nextElement().getName(), equalTo("1.dat")); - assertThat(entries.nextElement().getName(), equalTo("2.dat")); - assertThat(entries.nextElement().getName(), equalTo("d/")); - assertThat(entries.nextElement().getName(), equalTo("d/9.dat")); - assertThat(entries.nextElement().getName(), equalTo("special/")); - assertThat(entries.nextElement().getName(), equalTo("special/\u00EB.dat")); - assertThat(entries.nextElement().getName(), equalTo("nested.jar")); - assertThat(entries.nextElement().getName(), equalTo("another-nested.jar")); - assertThat(entries.hasMoreElements(), equalTo(false)); + assertThat(entries.nextElement().getName()).isEqualTo("META-INF/"); + assertThat(entries.nextElement().getName()).isEqualTo("META-INF/MANIFEST.MF"); + assertThat(entries.nextElement().getName()).isEqualTo("1.dat"); + assertThat(entries.nextElement().getName()).isEqualTo("2.dat"); + assertThat(entries.nextElement().getName()).isEqualTo("d/"); + assertThat(entries.nextElement().getName()).isEqualTo("d/9.dat"); + assertThat(entries.nextElement().getName()).isEqualTo("special/"); + assertThat(entries.nextElement().getName()).isEqualTo("special/\u00EB.dat"); + assertThat(entries.nextElement().getName()).isEqualTo("nested.jar"); + assertThat(entries.nextElement().getName()).isEqualTo("another-nested.jar"); + assertThat(entries.hasMoreElements()).isFalse(); URL jarUrl = new URL("jar:" + this.rootJarFile.toURI() + "!/"); URLClassLoader urlClassLoader = new URLClassLoader(new URL[] { jarUrl }); - assertThat(urlClassLoader.getResource("special/\u00EB.dat"), notNullValue()); - assertThat(urlClassLoader.getResource("d/9.dat"), notNullValue()); + assertThat(urlClassLoader.getResource("special/\u00EB.dat")).isNotNull(); + assertThat(urlClassLoader.getResource("d/9.dat")).isNotNull(); jarFile.close(); urlClassLoader.close(); } @@ -104,79 +97,79 @@ public class JarFileTests { @Test public void createFromFile() throws Exception { JarFile jarFile = new JarFile(this.rootJarFile); - assertThat(jarFile.getName(), notNullValue(String.class)); + assertThat(jarFile.getName()).isNotNull(); jarFile.close(); } @Test public void getManifest() throws Exception { - assertThat(this.jarFile.getManifest().getMainAttributes().getValue("Built-By"), - equalTo("j1")); + assertThat(this.jarFile.getManifest().getMainAttributes().getValue("Built-By")) + .isEqualTo("j1"); } @Test public void getManifestEntry() throws Exception { ZipEntry entry = this.jarFile.getJarEntry("META-INF/MANIFEST.MF"); Manifest manifest = new Manifest(this.jarFile.getInputStream(entry)); - assertThat(manifest.getMainAttributes().getValue("Built-By"), equalTo("j1")); + assertThat(manifest.getMainAttributes().getValue("Built-By")).isEqualTo("j1"); } @Test public void getEntries() throws Exception { Enumeration entries = this.jarFile.entries(); - assertThat(entries.nextElement().getName(), equalTo("META-INF/")); - assertThat(entries.nextElement().getName(), equalTo("META-INF/MANIFEST.MF")); - assertThat(entries.nextElement().getName(), equalTo("1.dat")); - assertThat(entries.nextElement().getName(), equalTo("2.dat")); - assertThat(entries.nextElement().getName(), equalTo("d/")); - assertThat(entries.nextElement().getName(), equalTo("d/9.dat")); - assertThat(entries.nextElement().getName(), equalTo("special/")); - assertThat(entries.nextElement().getName(), equalTo("special/\u00EB.dat")); - assertThat(entries.nextElement().getName(), equalTo("nested.jar")); - assertThat(entries.nextElement().getName(), equalTo("another-nested.jar")); - assertThat(entries.hasMoreElements(), equalTo(false)); + assertThat(entries.nextElement().getName()).isEqualTo("META-INF/"); + assertThat(entries.nextElement().getName()).isEqualTo("META-INF/MANIFEST.MF"); + assertThat(entries.nextElement().getName()).isEqualTo("1.dat"); + assertThat(entries.nextElement().getName()).isEqualTo("2.dat"); + assertThat(entries.nextElement().getName()).isEqualTo("d/"); + assertThat(entries.nextElement().getName()).isEqualTo("d/9.dat"); + assertThat(entries.nextElement().getName()).isEqualTo("special/"); + assertThat(entries.nextElement().getName()).isEqualTo("special/\u00EB.dat"); + assertThat(entries.nextElement().getName()).isEqualTo("nested.jar"); + assertThat(entries.nextElement().getName()).isEqualTo("another-nested.jar"); + assertThat(entries.hasMoreElements()).isFalse(); } @Test public void getSpecialResourceViaClassLoader() throws Exception { URLClassLoader urlClassLoader = new URLClassLoader( new URL[] { this.jarFile.getUrl() }); - assertThat(urlClassLoader.getResource("special/\u00EB.dat"), notNullValue()); + assertThat(urlClassLoader.getResource("special/\u00EB.dat")).isNotNull(); urlClassLoader.close(); } @Test public void getJarEntry() throws Exception { java.util.jar.JarEntry entry = this.jarFile.getJarEntry("1.dat"); - assertThat(entry, notNullValue(ZipEntry.class)); - assertThat(entry.getName(), equalTo("1.dat")); + assertThat(entry).isNotNull(); + assertThat(entry.getName()).isEqualTo("1.dat"); } @Test public void getInputStream() throws Exception { InputStream inputStream = this.jarFile .getInputStream(this.jarFile.getEntry("1.dat")); - assertThat(inputStream.available(), equalTo(1)); - assertThat(inputStream.read(), equalTo(1)); - assertThat(inputStream.available(), equalTo(0)); - assertThat(inputStream.read(), equalTo(-1)); + assertThat(inputStream.available()).isEqualTo(1); + assertThat(inputStream.read()).isEqualTo(1); + assertThat(inputStream.available()).isEqualTo(0); + assertThat(inputStream.read()).isEqualTo(-1); } @Test public void getName() throws Exception { - assertThat(this.jarFile.getName(), equalTo(this.rootJarFile.getPath())); + assertThat(this.jarFile.getName()).isEqualTo(this.rootJarFile.getPath()); } @Test public void getSize() throws Exception { - assertThat(this.jarFile.size(), equalTo((int) this.rootJarFile.length())); + assertThat(this.jarFile.size()).isEqualTo((int) this.rootJarFile.length()); } @Test public void getEntryTime() throws Exception { java.util.jar.JarFile jdkJarFile = new java.util.jar.JarFile(this.rootJarFile); - assertThat(this.jarFile.getEntry("META-INF/MANIFEST.MF").getTime(), - equalTo(jdkJarFile.getEntry("META-INF/MANIFEST.MF").getTime())); + assertThat(this.jarFile.getEntry("META-INF/MANIFEST.MF").getTime()) + .isEqualTo(jdkJarFile.getEntry("META-INF/MANIFEST.MF").getTime()); jdkJarFile.close(); } @@ -192,36 +185,36 @@ public class JarFileTests { @Test public void getUrl() throws Exception { URL url = this.jarFile.getUrl(); - assertThat(url.toString(), equalTo("jar:" + this.rootJarFile.toURI() + "!/")); + assertThat(url.toString()).isEqualTo("jar:" + this.rootJarFile.toURI() + "!/"); JarURLConnection jarURLConnection = (JarURLConnection) url.openConnection(); - assertThat(jarURLConnection.getJarFile(), sameInstance(this.jarFile)); - assertThat(jarURLConnection.getJarEntry(), nullValue()); - assertThat(jarURLConnection.getContentLength(), greaterThan(1)); - assertThat(jarURLConnection.getContent(), sameInstance((Object) this.jarFile)); - assertThat(jarURLConnection.getContentType(), equalTo("x-java/jar")); - assertThat(jarURLConnection.getJarFileURL().toURI(), - equalTo(this.rootJarFile.toURI())); + assertThat(jarURLConnection.getJarFile()).isSameAs(this.jarFile); + assertThat(jarURLConnection.getJarEntry()).isNull(); + assertThat(jarURLConnection.getContentLength()).isGreaterThan(1); + assertThat(jarURLConnection.getContent()).isSameAs(this.jarFile); + assertThat(jarURLConnection.getContentType()).isEqualTo("x-java/jar"); + assertThat(jarURLConnection.getJarFileURL().toURI()) + .isEqualTo(this.rootJarFile.toURI()); } @Test public void createEntryUrl() throws Exception { URL url = new URL(this.jarFile.getUrl(), "1.dat"); - assertThat(url.toString(), - equalTo("jar:" + this.rootJarFile.toURI() + "!/1.dat")); + assertThat(url.toString()) + .isEqualTo("jar:" + this.rootJarFile.toURI() + "!/1.dat"); JarURLConnection jarURLConnection = (JarURLConnection) url.openConnection(); - assertThat(jarURLConnection.getJarFile(), sameInstance(this.jarFile)); - assertThat(jarURLConnection.getJarEntry(), - sameInstance(this.jarFile.getJarEntry("1.dat"))); - assertThat(jarURLConnection.getContentLength(), equalTo(1)); - assertThat(jarURLConnection.getContent(), instanceOf(InputStream.class)); - assertThat(jarURLConnection.getContentType(), equalTo("content/unknown")); + assertThat(jarURLConnection.getJarFile()).isSameAs(this.jarFile); + assertThat(jarURLConnection.getJarEntry()) + .isSameAs(this.jarFile.getJarEntry("1.dat")); + assertThat(jarURLConnection.getContentLength()).isEqualTo(1); + assertThat(jarURLConnection.getContent()).isInstanceOf(InputStream.class); + assertThat(jarURLConnection.getContentType()).isEqualTo("content/unknown"); } @Test public void getMissingEntryUrl() throws Exception { URL url = new URL(this.jarFile.getUrl(), "missing.dat"); - assertThat(url.toString(), - equalTo("jar:" + this.rootJarFile.toURI() + "!/missing.dat")); + assertThat(url.toString()) + .isEqualTo("jar:" + this.rootJarFile.toURI() + "!/missing.dat"); this.thrown.expect(FileNotFoundException.class); ((JarURLConnection) url.openConnection()).getJarEntry(); } @@ -239,8 +232,8 @@ public class JarFileTests { URL url = new URL(this.jarFile.getUrl(), "1.dat"); url.openConnection(); InputStream stream = url.openStream(); - assertThat(stream.read(), equalTo(1)); - assertThat(stream.read(), equalTo(-1)); + assertThat(stream.read()).isEqualTo(1); + assertThat(stream.read()).isEqualTo(-1); } @Test @@ -249,25 +242,25 @@ public class JarFileTests { .getNestedJarFile(this.jarFile.getEntry("nested.jar")); Enumeration entries = nestedJarFile.entries(); - assertThat(entries.nextElement().getName(), equalTo("META-INF/")); - assertThat(entries.nextElement().getName(), equalTo("META-INF/MANIFEST.MF")); - assertThat(entries.nextElement().getName(), equalTo("3.dat")); - assertThat(entries.nextElement().getName(), equalTo("4.dat")); - assertThat(entries.nextElement().getName(), equalTo("\u00E4.dat")); - assertThat(entries.hasMoreElements(), equalTo(false)); + assertThat(entries.nextElement().getName()).isEqualTo("META-INF/"); + assertThat(entries.nextElement().getName()).isEqualTo("META-INF/MANIFEST.MF"); + assertThat(entries.nextElement().getName()).isEqualTo("3.dat"); + assertThat(entries.nextElement().getName()).isEqualTo("4.dat"); + assertThat(entries.nextElement().getName()).isEqualTo("\u00E4.dat"); + assertThat(entries.hasMoreElements()).isFalse(); InputStream inputStream = nestedJarFile .getInputStream(nestedJarFile.getEntry("3.dat")); - assertThat(inputStream.read(), equalTo(3)); - assertThat(inputStream.read(), equalTo(-1)); + assertThat(inputStream.read()).isEqualTo(3); + assertThat(inputStream.read()).isEqualTo(-1); URL url = nestedJarFile.getUrl(); - assertThat(url.toString(), - equalTo("jar:" + this.rootJarFile.toURI() + "!/nested.jar!/")); + assertThat(url.toString()) + .isEqualTo("jar:" + this.rootJarFile.toURI() + "!/nested.jar!/"); JarURLConnection conn = (JarURLConnection) url.openConnection(); - assertThat(conn.getJarFile(), sameInstance(nestedJarFile)); - assertThat(conn.getJarFileURL().toString(), - equalTo("jar:" + this.rootJarFile.toURI() + "!/nested.jar")); + assertThat(conn.getJarFile()).isSameAs(nestedJarFile); + assertThat(conn.getJarFileURL().toString()) + .isEqualTo("jar:" + this.rootJarFile.toURI() + "!/nested.jar"); } @Test @@ -276,18 +269,18 @@ public class JarFileTests { .getNestedJarFile(this.jarFile.getEntry("d/")); Enumeration entries = nestedJarFile.entries(); - assertThat(entries.nextElement().getName(), equalTo("9.dat")); - assertThat(entries.hasMoreElements(), equalTo(false)); + assertThat(entries.nextElement().getName()).isEqualTo("9.dat"); + assertThat(entries.hasMoreElements()).isFalse(); InputStream inputStream = nestedJarFile .getInputStream(nestedJarFile.getEntry("9.dat")); - assertThat(inputStream.read(), equalTo(9)); - assertThat(inputStream.read(), equalTo(-1)); + assertThat(inputStream.read()).isEqualTo(9); + assertThat(inputStream.read()).isEqualTo(-1); URL url = nestedJarFile.getUrl(); - assertThat(url.toString(), equalTo("jar:" + this.rootJarFile.toURI() + "!/d!/")); - assertThat(((JarURLConnection) url.openConnection()).getJarFile(), - sameInstance(nestedJarFile)); + assertThat(url.toString()).isEqualTo("jar:" + this.rootJarFile.toURI() + "!/d!/"); + assertThat(((JarURLConnection) url.openConnection()).getJarFile()) + .isSameAs(nestedJarFile); } @Test @@ -295,11 +288,11 @@ public class JarFileTests { JarFile nestedJarFile = this.jarFile .getNestedJarFile(this.jarFile.getEntry("nested.jar")); URL url = nestedJarFile.getJarEntry("3.dat").getUrl(); - assertThat(url.toString(), - equalTo("jar:" + this.rootJarFile.toURI() + "!/nested.jar!/3.dat")); + assertThat(url.toString()) + .isEqualTo("jar:" + this.rootJarFile.toURI() + "!/nested.jar!/3.dat"); InputStream inputStream = url.openStream(); - assertThat(inputStream, notNullValue()); - assertThat(inputStream.read(), equalTo(3)); + assertThat(inputStream).isNotNull(); + assertThat(inputStream.read()).isEqualTo(3); } @Test @@ -307,15 +300,15 @@ public class JarFileTests { JarFile.registerUrlProtocolHandler(); String spec = "jar:" + this.rootJarFile.toURI() + "!/nested.jar!/3.dat"; URL url = new URL(spec); - assertThat(url.toString(), equalTo(spec)); + assertThat(url.toString()).isEqualTo(spec); InputStream inputStream = url.openStream(); - assertThat(inputStream, notNullValue()); - assertThat(inputStream.read(), equalTo(3)); + assertThat(inputStream).isNotNull(); + assertThat(inputStream.read()).isEqualTo(3); JarURLConnection connection = (JarURLConnection) url.openConnection(); - assertThat(connection.getURL().toString(), equalTo(spec)); - assertThat(connection.getJarFileURL().toString(), - equalTo("jar:" + this.rootJarFile.toURI() + "!/nested.jar")); - assertThat(connection.getEntryName(), equalTo("3.dat")); + assertThat(connection.getURL().toString()).isEqualTo(spec); + assertThat(connection.getJarFileURL().toString()) + .isEqualTo("jar:" + this.rootJarFile.toURI() + "!/nested.jar"); + assertThat(connection.getEntryName()).isEqualTo("3.dat"); } @Test @@ -323,38 +316,37 @@ public class JarFileTests { JarFile.registerUrlProtocolHandler(); String spec = "jar:" + this.rootJarFile.toURI() + "!/2.dat"; URL url = new URL(spec); - assertThat(url.toString(), equalTo(spec)); + assertThat(url.toString()).isEqualTo(spec); InputStream inputStream = url.openStream(); - assertThat(inputStream, notNullValue()); - assertThat(inputStream.read(), equalTo(2)); + assertThat(inputStream).isNotNull(); + assertThat(inputStream.read()).isEqualTo(2); JarURLConnection connection = (JarURLConnection) url.openConnection(); - assertThat(connection.getURL().toString(), equalTo(spec)); - assertThat(connection.getJarFileURL().toURI(), equalTo(this.rootJarFile.toURI())); - assertThat(connection.getEntryName(), equalTo("2.dat")); + assertThat(connection.getURL().toString()).isEqualTo(spec); + assertThat(connection.getJarFileURL().toURI()) + .isEqualTo(this.rootJarFile.toURI()); + assertThat(connection.getEntryName()).isEqualTo("2.dat"); } @Test public void getDirectoryInputStream() throws Exception { InputStream inputStream = this.jarFile .getInputStream(this.jarFile.getEntry("d/")); - assertThat(inputStream, notNullValue()); - assertThat(inputStream.read(), equalTo(-1)); + assertThat(inputStream).isNotNull(); + assertThat(inputStream.read()).isEqualTo(-1); } @Test public void getDirectoryInputStreamWithoutSlash() throws Exception { InputStream inputStream = this.jarFile.getInputStream(this.jarFile.getEntry("d")); - assertThat(inputStream, notNullValue()); - assertThat(inputStream.read(), equalTo(-1)); + assertThat(inputStream).isNotNull(); + assertThat(inputStream.read()).isEqualTo(-1); } @Test public void sensibleToString() throws Exception { - assertThat(this.jarFile.toString(), equalTo(this.rootJarFile.getPath())); - assertThat( - this.jarFile.getNestedJarFile(this.jarFile.getEntry("nested.jar")) - .toString(), - equalTo(this.rootJarFile.getPath() + "!/nested.jar")); + assertThat(this.jarFile.toString()).isEqualTo(this.rootJarFile.getPath()); + assertThat(this.jarFile.getNestedJarFile(this.jarFile.getEntry("nested.jar")) + .toString()).isEqualTo(this.rootJarFile.getPath() + "!/nested.jar"); } @Test @@ -367,7 +359,7 @@ public class JarFileTests { signedJarFile = entry; } } - assertNotNull(signedJarFile); + assertThat(signedJarFile).isNotNull(); java.util.jar.JarFile jarFile = new JarFile(new File(signedJarFile)); jarFile.getManifest(); Enumeration jarEntries = jarFile.entries(); @@ -378,8 +370,7 @@ public class JarFileTests { inputStream.close(); if (!jarEntry.getName().startsWith("META-INF") && !jarEntry.isDirectory() && !jarEntry.getName().endsWith("TigerDigest.class")) { - assertNotNull("Missing cert " + jarEntry.getName(), - jarEntry.getCertificates()); + assertThat(jarEntry.getCertificates()).isNotNull(); } } jarFile.close(); diff --git a/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/util/SystemPropertyUtilsTests.java b/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/util/SystemPropertyUtilsTests.java index 17111bc125..9a8e349257 100644 --- a/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/util/SystemPropertyUtilsTests.java +++ b/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/util/SystemPropertyUtilsTests.java @@ -20,9 +20,11 @@ import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** + * Tests for {@link SystemPropertyUtils}. + * * @author Dave Syer */ public class SystemPropertyUtilsTests { @@ -39,23 +41,25 @@ public class SystemPropertyUtilsTests { @Test public void testVanillaPlaceholder() { - assertEquals("bar", SystemPropertyUtils.resolvePlaceholders("${foo}")); + assertThat(SystemPropertyUtils.resolvePlaceholders("${foo}")).isEqualTo("bar"); } @Test public void testDefaultValue() { - assertEquals("foo", SystemPropertyUtils.resolvePlaceholders("${bar:foo}")); + assertThat(SystemPropertyUtils.resolvePlaceholders("${bar:foo}")) + .isEqualTo("foo"); } @Test public void testNestedPlaceholder() { - assertEquals("foo", - SystemPropertyUtils.resolvePlaceholders("${bar:${spam:foo}}")); + assertThat(SystemPropertyUtils.resolvePlaceholders("${bar:${spam:foo}}")) + .isEqualTo("foo"); } @Test public void testEnvVar() { - assertEquals(System.getenv("LANG"), SystemPropertyUtils.getProperty("lang")); + assertThat(SystemPropertyUtils.getProperty("lang")) + .isEqualTo(System.getenv("LANG")); } } diff --git a/spring-boot-tools/spring-boot-maven-plugin/src/test/java/org/springframework/boot/maven/ArtifactsLibrariesTests.java b/spring-boot-tools/spring-boot-maven-plugin/src/test/java/org/springframework/boot/maven/ArtifactsLibrariesTests.java index b083d977ca..e95bbb8bf8 100644 --- a/spring-boot-tools/spring-boot-maven-plugin/src/test/java/org/springframework/boot/maven/ArtifactsLibrariesTests.java +++ b/spring-boot-tools/spring-boot-maven-plugin/src/test/java/org/springframework/boot/maven/ArtifactsLibrariesTests.java @@ -36,8 +36,7 @@ import org.springframework.boot.loader.tools.Library; import org.springframework.boot.loader.tools.LibraryCallback; import org.springframework.boot.loader.tools.LibraryScope; -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.times; @@ -80,9 +79,9 @@ public class ArtifactsLibrariesTests { this.libs.doWithLibraries(this.callback); verify(this.callback).library(this.libraryCaptor.capture()); Library library = this.libraryCaptor.getValue(); - assertThat(library.getFile(), equalTo(this.file)); - assertThat(library.getScope(), equalTo(LibraryScope.COMPILE)); - assertThat(library.isUnpackRequired(), equalTo(false)); + assertThat(library.getFile()).isEqualTo(this.file); + assertThat(library.getScope()).isEqualTo(LibraryScope.COMPILE); + assertThat(library.isUnpackRequired()).isFalse(); } @Test @@ -98,7 +97,7 @@ public class ArtifactsLibrariesTests { mock(Log.class)); this.libs.doWithLibraries(this.callback); verify(this.callback).library(this.libraryCaptor.capture()); - assertThat(this.libraryCaptor.getValue().isUnpackRequired(), equalTo(true)); + assertThat(this.libraryCaptor.getValue().isUnpackRequired()).isTrue(); } @Test @@ -117,8 +116,8 @@ public class ArtifactsLibrariesTests { this.libs = new ArtifactsLibraries(this.artifacts, null, mock(Log.class)); this.libs.doWithLibraries(this.callback); verify(this.callback, times(2)).library(this.libraryCaptor.capture()); - assertThat(this.libraryCaptor.getAllValues().get(0).getName(), equalTo("g1-a")); - assertThat(this.libraryCaptor.getAllValues().get(1).getName(), equalTo("g2-a")); + assertThat(this.libraryCaptor.getAllValues().get(0).getName()).isEqualTo("g1-a"); + assertThat(this.libraryCaptor.getAllValues().get(1).getName()).isEqualTo("g2-a"); } } diff --git a/spring-boot-tools/spring-boot-maven-plugin/src/test/java/org/springframework/boot/maven/DependencyFilterMojoTests.java b/spring-boot-tools/spring-boot-maven-plugin/src/test/java/org/springframework/boot/maven/DependencyFilterMojoTests.java index e637e61c0e..c5d5b23b2d 100644 --- a/spring-boot-tools/spring-boot-maven-plugin/src/test/java/org/springframework/boot/maven/DependencyFilterMojoTests.java +++ b/spring-boot-tools/spring-boot-maven-plugin/src/test/java/org/springframework/boot/maven/DependencyFilterMojoTests.java @@ -27,8 +27,7 @@ import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; import org.junit.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertSame; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; @@ -48,8 +47,8 @@ public class DependencyFilterMojoTests { Set artifacts = mojo.filterDependencies( createArtifact("com.foo", "one"), createArtifact("com.foo", "two"), createArtifact("com.bar", "exclude-id"), artifact); - assertEquals("wrong filtering of artifacts", 1, artifacts.size()); - assertSame("Wrong filtered artifact", artifact, artifacts.iterator().next()); + assertThat(artifacts).hasSize(1); + assertThat(artifacts.iterator().next()).isSameAs(artifact); } @Test @@ -61,8 +60,8 @@ public class DependencyFilterMojoTests { Set artifacts = mojo.filterDependencies( createArtifact("com.foo", "one"), createArtifact("com.foo", "two"), artifact); - assertEquals("wrong filtering of artifacts", 1, artifacts.size()); - assertSame("Wrong filtered artifact", artifact, artifacts.iterator().next()); + assertThat(artifacts).hasSize(1); + assertThat(artifacts.iterator().next()).isSameAs(artifact); } private Artifact createArtifact(String groupId, String artifactId) { diff --git a/spring-boot-tools/spring-boot-maven-plugin/src/test/java/org/springframework/boot/maven/ExcludeFilterTests.java b/spring-boot-tools/spring-boot-maven-plugin/src/test/java/org/springframework/boot/maven/ExcludeFilterTests.java index 880e9c8b58..6fd6d8a362 100644 --- a/spring-boot-tools/spring-boot-maven-plugin/src/test/java/org/springframework/boot/maven/ExcludeFilterTests.java +++ b/spring-boot-tools/spring-boot-maven-plugin/src/test/java/org/springframework/boot/maven/ExcludeFilterTests.java @@ -25,8 +25,7 @@ import org.apache.maven.artifact.Artifact; import org.apache.maven.shared.artifact.filter.collection.ArtifactFilterException; import org.junit.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertSame; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; @@ -36,7 +35,7 @@ import static org.mockito.Mockito.mock; * @author Stephane Nicoll * @author David Turanski */ -@SuppressWarnings("rawtypes") +@SuppressWarnings({ "rawtypes", "unchecked" }) public class ExcludeFilterTests { @Test @@ -45,7 +44,7 @@ public class ExcludeFilterTests { Arrays.asList(createExclude("com.foo", "bar"))); Set result = filter .filter(Collections.singleton(createArtifact("com.foo", "bar"))); - assertEquals("Should have been filtered", 0, result.size()); + assertThat(result).isEmpty(); } @Test @@ -54,8 +53,8 @@ public class ExcludeFilterTests { Arrays.asList(createExclude("com.foo", "bar"))); Artifact artifact = createArtifact("com.baz", "bar"); Set result = filter.filter(Collections.singleton(artifact)); - assertEquals("Should not have been filtered", 1, result.size()); - assertSame(artifact, result.iterator().next()); + assertThat(result).hasSize(1); + assertThat(result.iterator().next()).isSameAs(artifact); } @Test @@ -64,8 +63,8 @@ public class ExcludeFilterTests { Arrays.asList(createExclude("com.foo", "bar"))); Artifact artifact = createArtifact("com.foo", "biz"); Set result = filter.filter(Collections.singleton(artifact)); - assertEquals("Should not have been filtered", 1, result.size()); - assertSame(artifact, result.iterator().next()); + assertThat(result).hasSize(1); + assertThat(result.iterator().next()).isSameAs(artifact); } @Test @@ -74,7 +73,7 @@ public class ExcludeFilterTests { Arrays.asList(createExclude("com.foo", "bar", "jdk5"))); Set result = filter .filter(Collections.singleton(createArtifact("com.foo", "bar", "jdk5"))); - assertEquals("Should have been filtered", 0, result.size()); + assertThat(result).isEmpty(); } @Test @@ -83,8 +82,8 @@ public class ExcludeFilterTests { Arrays.asList(createExclude("com.foo", "bar", "jdk5"))); Artifact artifact = createArtifact("com.foo", "bar"); Set result = filter.filter(Collections.singleton(artifact)); - assertEquals("Should not have been filtered", 1, result.size()); - assertSame(artifact, result.iterator().next()); + assertThat(result).hasSize(1); + assertThat(result.iterator().next()).isSameAs(artifact); } @Test @@ -93,8 +92,8 @@ public class ExcludeFilterTests { Arrays.asList(createExclude("com.foo", "bar", "jdk5"))); Artifact artifact = createArtifact("com.foo", "bar", "jdk6"); Set result = filter.filter(Collections.singleton(artifact)); - assertEquals("Should not have been filtered", 1, result.size()); - assertSame(artifact, result.iterator().next()); + assertThat(result).hasSize(1); + assertThat(result.iterator().next()).isSameAs(artifact); } @Test @@ -108,8 +107,8 @@ public class ExcludeFilterTests { Artifact anotherAcme = createArtifact("org.acme", "another-app"); artifacts.add(anotherAcme); Set result = filter.filter(artifacts); - assertEquals("Two dependencies should have been filtered", 1, result.size()); - assertSame(anotherAcme, result.iterator().next()); + assertThat(result).hasSize(1); + assertThat(result.iterator().next()).isSameAs(anotherAcme); } private Exclude createExclude(String groupId, String artifactId) { diff --git a/spring-boot-tools/spring-boot-maven-plugin/src/test/java/org/springframework/boot/maven/IncludeFilterTests.java b/spring-boot-tools/spring-boot-maven-plugin/src/test/java/org/springframework/boot/maven/IncludeFilterTests.java index 3f99067ff2..cda8d6b987 100644 --- a/spring-boot-tools/spring-boot-maven-plugin/src/test/java/org/springframework/boot/maven/IncludeFilterTests.java +++ b/spring-boot-tools/spring-boot-maven-plugin/src/test/java/org/springframework/boot/maven/IncludeFilterTests.java @@ -25,8 +25,7 @@ import org.apache.maven.artifact.Artifact; import org.apache.maven.shared.artifact.filter.collection.ArtifactFilterException; import org.junit.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertSame; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; @@ -35,7 +34,7 @@ import static org.mockito.Mockito.mock; * * @author David Turanski */ -@SuppressWarnings("rawtypes") +@SuppressWarnings({ "rawtypes", "unchecked" }) public class IncludeFilterTests { @Test @@ -44,8 +43,8 @@ public class IncludeFilterTests { Arrays.asList(createInclude("com.foo", "bar"))); Artifact artifact = createArtifact("com.foo", "bar"); Set result = filter.filter(Collections.singleton(artifact)); - assertEquals("Should not have been filtered", 1, result.size()); - assertSame(artifact, result.iterator().next()); + assertThat(result).hasSize(1); + assertThat(result.iterator().next()).isSameAs(artifact); } @Test @@ -54,7 +53,7 @@ public class IncludeFilterTests { Arrays.asList(createInclude("com.foo", "bar"))); Artifact artifact = createArtifact("com.baz", "bar"); Set result = filter.filter(Collections.singleton(artifact)); - assertEquals("Should have been filtered", 0, result.size()); + assertThat(result).isEmpty(); } @Test @@ -63,7 +62,7 @@ public class IncludeFilterTests { Arrays.asList(createInclude("com.foo", "bar"))); Artifact artifact = createArtifact("com.foo", "biz"); Set result = filter.filter(Collections.singleton(artifact)); - assertEquals("Should have been filtered", 0, result.size()); + assertThat(result).isEmpty(); } @Test @@ -72,8 +71,8 @@ public class IncludeFilterTests { Arrays.asList(createInclude("com.foo", "bar", "jdk5"))); Artifact artifact = createArtifact("com.foo", "bar", "jdk5"); Set result = filter.filter(Collections.singleton(artifact)); - assertEquals("Should not have been filtered", 1, result.size()); - assertSame(artifact, result.iterator().next()); + assertThat(result).hasSize(1); + assertThat(result.iterator().next()).isSameAs(artifact); } @Test @@ -82,7 +81,7 @@ public class IncludeFilterTests { Arrays.asList(createInclude("com.foo", "bar", "jdk5"))); Artifact artifact = createArtifact("com.foo", "bar"); Set result = filter.filter(Collections.singleton(artifact)); - assertEquals("Should have been filtered", 0, result.size()); + assertThat(result).isEmpty(); } @Test @@ -91,7 +90,7 @@ public class IncludeFilterTests { Arrays.asList(createInclude("com.foo", "bar", "jdk5"))); Artifact artifact = createArtifact("com.foo", "bar", "jdk6"); Set result = filter.filter(Collections.singleton(artifact)); - assertEquals("Should have been filtered", 0, result.size()); + assertThat(result).isEmpty(); } @Test @@ -105,7 +104,7 @@ public class IncludeFilterTests { Artifact anotherAcme = createArtifact("org.acme", "another-app"); artifacts.add(anotherAcme); Set result = filter.filter(artifacts); - assertEquals("One dependency should have been filtered", 2, result.size()); + assertThat(result).hasSize(2); } private Include createInclude(String groupId, String artifactId) { diff --git a/spring-boot-tools/spring-boot-maven-plugin/src/test/java/org/springframework/boot/maven/PropertiesMergingResourceTransformerTests.java b/spring-boot-tools/spring-boot-maven-plugin/src/test/java/org/springframework/boot/maven/PropertiesMergingResourceTransformerTests.java index 469e887043..84ba464573 100644 --- a/spring-boot-tools/spring-boot-maven-plugin/src/test/java/org/springframework/boot/maven/PropertiesMergingResourceTransformerTests.java +++ b/spring-boot-tools/spring-boot-maven-plugin/src/test/java/org/springframework/boot/maven/PropertiesMergingResourceTransformerTests.java @@ -22,10 +22,7 @@ import java.util.jar.JarOutputStream; import org.junit.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link PropertiesMergingResourceTransformer}. @@ -38,10 +35,10 @@ public class PropertiesMergingResourceTransformerTests { @Test public void testProcess() throws Exception { - assertFalse(this.transformer.hasTransformedResource()); + assertThat(this.transformer.hasTransformedResource()).isFalse(); this.transformer.processResource("foo", new ByteArrayInputStream("foo=bar".getBytes()), null); - assertTrue(this.transformer.hasTransformedResource()); + assertThat(this.transformer.hasTransformedResource()).isTrue(); } @Test @@ -50,7 +47,7 @@ public class PropertiesMergingResourceTransformerTests { new ByteArrayInputStream("foo=bar".getBytes()), null); this.transformer.processResource("bar", new ByteArrayInputStream("foo=spam".getBytes()), null); - assertEquals("bar,spam", this.transformer.getData().getProperty("foo")); + assertThat(this.transformer.getData().getProperty("foo")).isEqualTo("bar,spam"); } @Test @@ -63,8 +60,8 @@ public class PropertiesMergingResourceTransformerTests { this.transformer.modifyOutputStream(os); os.flush(); os.close(); - assertNotNull(out.toByteArray()); - assertTrue(out.toByteArray().length > 0); + assertThat(out.toByteArray()).isNotNull(); + assertThat(out.toByteArray().length > 0).isTrue(); } } diff --git a/spring-boot-tools/spring-boot-maven-plugin/src/test/java/org/springframework/boot/maven/RunArgumentsTests.java b/spring-boot-tools/spring-boot-maven-plugin/src/test/java/org/springframework/boot/maven/RunArgumentsTests.java index 89a6e10798..e1f33f83bc 100644 --- a/spring-boot-tools/spring-boot-maven-plugin/src/test/java/org/springframework/boot/maven/RunArgumentsTests.java +++ b/spring-boot-tools/spring-boot-maven-plugin/src/test/java/org/springframework/boot/maven/RunArgumentsTests.java @@ -18,8 +18,7 @@ package org.springframework.boot.maven; import org.junit.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link RunArguments}. @@ -31,48 +30,48 @@ public class RunArgumentsTests { @Test public void parseNull() { String[] args = parseArgs(null); - assertNotNull(args); - assertEquals(0, args.length); + assertThat(args).isNotNull(); + assertThat(args.length).isEqualTo(0); } @Test public void parseEmpty() { String[] args = parseArgs(" "); - assertNotNull(args); - assertEquals(0, args.length); + assertThat(args).isNotNull(); + assertThat(args.length).isEqualTo(0); } @Test public void parseDebugFlags() { String[] args = parseArgs( "-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=5005"); - assertEquals(2, args.length); - assertEquals("-Xdebug", args[0]); - assertEquals("-Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=5005", - args[1]); + assertThat(args.length).isEqualTo(2); + assertThat(args[0]).isEqualTo("-Xdebug"); + assertThat(args[1]).isEqualTo( + "-Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=5005"); } @Test public void parseWithExtraSpaces() { String[] args = parseArgs(" -Dfoo=bar -Dfoo2=bar2 "); - assertEquals(2, args.length); - assertEquals("-Dfoo=bar", args[0]); - assertEquals("-Dfoo2=bar2", args[1]); + assertThat(args.length).isEqualTo(2); + assertThat(args[0]).isEqualTo("-Dfoo=bar"); + assertThat(args[1]).isEqualTo("-Dfoo2=bar2"); } @Test public void parseWithNewLinesAndTabs() { String[] args = parseArgs(" -Dfoo=bar \n" + "\t\t -Dfoo2=bar2 "); - assertEquals(2, args.length); - assertEquals("-Dfoo=bar", args[0]); - assertEquals("-Dfoo2=bar2", args[1]); + assertThat(args.length).isEqualTo(2); + assertThat(args[0]).isEqualTo("-Dfoo=bar"); + assertThat(args[1]).isEqualTo("-Dfoo2=bar2"); } @Test public void quoteHandledProperly() { String[] args = parseArgs("-Dvalue=\"My Value\" "); - assertEquals(1, args.length); - assertEquals("-Dvalue=My Value", args[0]); + assertThat(args.length).isEqualTo(1); + assertThat(args[0]).isEqualTo("-Dvalue=My Value"); } private String[] parseArgs(String args) { diff --git a/spring-boot-tools/spring-boot-maven-plugin/src/test/java/org/springframework/boot/maven/Verify.java b/spring-boot-tools/spring-boot-maven-plugin/src/test/java/org/springframework/boot/maven/Verify.java index d44eb33221..351d20ae4e 100644 --- a/spring-boot-tools/spring-boot-maven-plugin/src/test/java/org/springframework/boot/maven/Verify.java +++ b/spring-boot-tools/spring-boot-maven-plugin/src/test/java/org/springframework/boot/maven/Verify.java @@ -28,11 +28,7 @@ import java.util.zip.ZipFile; import org.springframework.util.FileCopyUtils; -import static org.hamcrest.Matchers.containsString; -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; /** * Verification utility for use with maven-invoker-plugin verification scripts. @@ -107,13 +103,15 @@ public final class Verify { } public void assertHasNonUnpackEntry(String entryName) { - assertTrue("Entry starting with " + entryName + " was an UNPACK entry", - hasNonUnpackEntry(entryName)); + assertThat(hasNonUnpackEntry(entryName)) + .as("Entry starting with " + entryName + " was an UNPACK entry") + .isTrue(); } public void assertHasUnpackEntry(String entryName) { - assertTrue("Entry starting with " + entryName + " was not an UNPACK entry", - hasUnpackEntry(entryName)); + assertThat(hasUnpackEntry(entryName)) + .as("Entry starting with " + entryName + " was not an UNPACK entry") + .isTrue(); } private boolean hasNonUnpackEntry(String entryName) { @@ -167,22 +165,21 @@ public final class Verify { public void verify(boolean executable, String... scriptContents) throws Exception { - assertTrue("Archive missing", this.file.exists()); - assertTrue("Archive not a file", this.file.isFile()); + assertThat(this.file).exists().isFile(); if (scriptContents.length > 0 && executable) { String contents = new String(FileCopyUtils.copyToByteArray(this.file)); contents = contents.substring(0, contents .indexOf(new String(new byte[] { 0x50, 0x4b, 0x03, 0x04 }))); for (String content : scriptContents) { - assertThat(contents, containsString(content)); + assertThat(contents).contains(content); } } if (!executable) { String contents = new String(FileCopyUtils.copyToByteArray(this.file)); - assertTrue("Is executable", contents - .startsWith(new String(new byte[] { 0x50, 0x4b, 0x03, 0x04 }))); + assertThat(contents).as("Is executable") + .startsWith(new String(new byte[] { 0x50, 0x4b, 0x03, 0x04 })); } ZipFile zipFile = new ZipFile(this.file); @@ -224,18 +221,21 @@ public final class Verify { verifier.assertHasEntryNameStartingWith("lib/spring-context"); verifier.assertHasEntryNameStartingWith("lib/spring-core"); verifier.assertHasEntryNameStartingWith("lib/javax.servlet-api-3"); - assertTrue("Unpacked launcher classes", verifier - .hasEntry("org/" + "springframework/boot/loader/JarLauncher.class")); - assertTrue("Own classes", - verifier.hasEntry("org/" + "test/SampleApplication.class")); + assertThat(verifier + .hasEntry("org/" + "springframework/boot/loader/JarLauncher.class")) + .as("Unpacked launcher classes").isTrue(); + assertThat(verifier.hasEntry("org/" + "test/SampleApplication.class")) + .as("Own classes").isTrue(); } @Override protected void verifyManifest(Manifest manifest) throws Exception { - assertEquals("org.springframework.boot.loader.JarLauncher", - manifest.getMainAttributes().getValue("Main-Class")); - assertEquals(this.main, manifest.getMainAttributes().getValue("Start-Class")); - assertEquals("Foo", manifest.getMainAttributes().getValue("Not-Used")); + assertThat(manifest.getMainAttributes().getValue("Main-Class")) + .isEqualTo("org.springframework.boot.loader.JarLauncher"); + assertThat(manifest.getMainAttributes().getValue("Start-Class")) + .isEqualTo(this.main); + assertThat(manifest.getMainAttributes().getValue("Not-Used")) + .isEqualTo("Foo"); } } @@ -252,20 +252,23 @@ public final class Verify { verifier.assertHasEntryNameStartingWith("WEB-INF/lib/spring-core"); verifier.assertHasEntryNameStartingWith( "WEB-INF/lib-provided/javax.servlet-api-3"); - assertTrue("Unpacked launcher classes", verifier - .hasEntry("org/" + "springframework/boot/loader/JarLauncher.class")); - assertTrue("Own classes", verifier - .hasEntry("WEB-INF/classes/org/" + "test/SampleApplication.class")); - assertTrue("Web content", verifier.hasEntry("index.html")); + assertThat(verifier + .hasEntry("org/" + "springframework/boot/loader/JarLauncher.class")) + .as("Unpacked launcher classes").isTrue(); + assertThat(verifier + .hasEntry("WEB-INF/classes/org/" + "test/SampleApplication.class")) + .as("Own classes").isTrue(); + assertThat(verifier.hasEntry("index.html")).as("Web content").isTrue(); } @Override protected void verifyManifest(Manifest manifest) throws Exception { - assertEquals("org.springframework.boot.loader.WarLauncher", - manifest.getMainAttributes().getValue("Main-Class")); - assertEquals("org.test.SampleApplication", - manifest.getMainAttributes().getValue("Start-Class")); - assertEquals("Foo", manifest.getMainAttributes().getValue("Not-Used")); + assertThat(manifest.getMainAttributes().getValue("Main-Class")) + .isEqualTo("org.springframework.boot.loader.WarLauncher"); + assertThat(manifest.getMainAttributes().getValue("Start-Class")) + .isEqualTo("org.test.SampleApplication"); + assertThat(manifest.getMainAttributes().getValue("Not-Used")) + .isEqualTo("Foo"); } } @@ -277,11 +280,12 @@ public final class Verify { @Override protected void verifyManifest(Manifest manifest) throws Exception { - assertEquals("org.springframework.boot.loader.PropertiesLauncher", - manifest.getMainAttributes().getValue("Main-Class")); - assertEquals("org.test.SampleApplication", - manifest.getMainAttributes().getValue("Start-Class")); - assertEquals("Foo", manifest.getMainAttributes().getValue("Not-Used")); + assertThat(manifest.getMainAttributes().getValue("Main-Class")) + .isEqualTo("org.springframework.boot.loader.PropertiesLauncher"); + assertThat(manifest.getMainAttributes().getValue("Start-Class")) + .isEqualTo("org.test.SampleApplication"); + assertThat(manifest.getMainAttributes().getValue("Not-Used")) + .isEqualTo("Foo"); } } @@ -297,10 +301,11 @@ public final class Verify { verifier.assertHasEntryNameStartingWith("lib/spring-context"); verifier.assertHasEntryNameStartingWith("lib/spring-core"); verifier.assertHasNoEntryNameStartingWith("lib/javax.servlet-api-3"); - assertFalse("Unpacked launcher classes", verifier - .hasEntry("org/" + "springframework/boot/loader/JarLauncher.class")); - assertTrue("Own classes", - verifier.hasEntry("org/" + "test/SampleModule.class")); + assertThat(verifier + .hasEntry("org/" + "springframework/boot/loader/JarLauncher.class")) + .as("Unpacked launcher classes").isFalse(); + assertThat(verifier.hasEntry("org/" + "test/SampleModule.class")) + .as("Own classes").isTrue(); } @Override From 962a598531e9f08715f8c0750f4ebd58e0052f2f Mon Sep 17 00:00:00 2001 From: Phillip Webb Date: Sat, 6 Feb 2016 14:52:28 -0800 Subject: [PATCH 06/10] Use AssertJ in spring-boot-cli See gh-5083 --- .../boot/cli/ClassLoaderIntegrationTests.java | 6 +- .../cli/DirectorySourcesIntegrationTests.java | 10 +- .../boot/cli/GrabCommandIntegrationTests.java | 16 +- .../boot/cli/ReproIntegrationTests.java | 13 +- .../boot/cli/SampleIntegrationTests.java | 57 +++---- .../boot/cli/TestCommandIntegrationTests.java | 24 +-- .../app/SpringApplicationLauncherTests.java | 23 +-- .../CommandRunnerIntegrationTests.java | 7 +- .../boot/cli/command/CommandRunnerTests.java | 42 ++--- .../command/OptionParsingCommandTests.java | 17 +- .../command/archive/ResourceMatcherTests.java | 96 +++++------ .../cli/command/init/InitCommandTests.java | 161 +++++++++--------- .../init/InitializrServiceMetadataTests.java | 51 +++--- .../command/init/InitializrServiceTests.java | 17 +- .../init/ProjectGenerationRequestTests.java | 78 ++++----- ...rviceCapabilitiesReportGeneratorTests.java | 14 +- .../GroovyGrabDependencyResolverTests.java | 29 ++-- .../cli/command/install/InstallerTests.java | 35 ++-- ...AwareWhiteSpaceArgumentDelimiterTests.java | 62 +++---- .../compiler/DependencyCustomizerTests.java | 36 ++-- .../ExtendedGroovyClassLoaderTests.java | 5 +- .../GenericBomAstTransformationTests.java | 9 +- .../RepositoryConfigurationFactoryTests.java | 9 +- ...endencyCoordinatesTransformationTests.java | 8 +- .../CompositeDependencyManagementTests.java | 31 ++-- ...ementArtifactCoordinatesResolverTests.java | 12 +- ...DependenciesDependencyManagementTests.java | 16 +- .../grape/AetherGrapeEngineTests.java | 42 +++-- .../grape/DetailedProgressReporterTests.java | 20 +-- ...rySystemSessionAutoConfigurationTests.java | 18 +- ...rySystemSessionAutoConfigurationTests.java | 36 ++-- .../boot/cli/util/ResourceUtilsTests.java | 55 +++--- 32 files changed, 479 insertions(+), 576 deletions(-) diff --git a/spring-boot-cli/src/test/java/org/springframework/boot/cli/ClassLoaderIntegrationTests.java b/spring-boot-cli/src/test/java/org/springframework/boot/cli/ClassLoaderIntegrationTests.java index 82b2885096..966ff169bb 100644 --- a/spring-boot-cli/src/test/java/org/springframework/boot/cli/ClassLoaderIntegrationTests.java +++ b/spring-boot-cli/src/test/java/org/springframework/boot/cli/ClassLoaderIntegrationTests.java @@ -19,8 +19,7 @@ package org.springframework.boot.cli; import org.junit.Rule; import org.junit.Test; -import static org.hamcrest.Matchers.containsString; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for CLI Classloader issues. @@ -37,6 +36,7 @@ public class ClassLoaderIntegrationTests { // CLI classes or dependencies should not be exposed to the app String output = this.cli.run("classloader-test-app.groovy", SpringCli.class.getName()); - assertThat(output, containsString("HasClasses-false-true-false")); + assertThat(output).contains("HasClasses-false-true-false"); } + } diff --git a/spring-boot-cli/src/test/java/org/springframework/boot/cli/DirectorySourcesIntegrationTests.java b/spring-boot-cli/src/test/java/org/springframework/boot/cli/DirectorySourcesIntegrationTests.java index b655af8337..2144a3e08c 100644 --- a/spring-boot-cli/src/test/java/org/springframework/boot/cli/DirectorySourcesIntegrationTests.java +++ b/spring-boot-cli/src/test/java/org/springframework/boot/cli/DirectorySourcesIntegrationTests.java @@ -19,8 +19,7 @@ package org.springframework.boot.cli; import org.junit.Rule; import org.junit.Test; -import static org.hamcrest.Matchers.containsString; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; /** * Integration tests for code in directories. @@ -35,18 +34,19 @@ public class DirectorySourcesIntegrationTests { @Test public void runDirectory() throws Exception { this.cli.run("code"); - assertThat(this.cli.getOutput(), containsString("Hello World")); + assertThat(this.cli.getOutput()).contains("Hello World"); } @Test public void runDirectoryRecursive() throws Exception { this.cli.run(""); - assertThat(this.cli.getOutput(), containsString("Hello World")); + assertThat(this.cli.getOutput()).contains("Hello World"); } @Test public void runPathPattern() throws Exception { this.cli.run("**/*.groovy"); - assertThat(this.cli.getOutput(), containsString("Hello World")); + assertThat(this.cli.getOutput()).contains("Hello World"); } + } diff --git a/spring-boot-cli/src/test/java/org/springframework/boot/cli/GrabCommandIntegrationTests.java b/spring-boot-cli/src/test/java/org/springframework/boot/cli/GrabCommandIntegrationTests.java index 481d831534..0036ab2033 100644 --- a/spring-boot-cli/src/test/java/org/springframework/boot/cli/GrabCommandIntegrationTests.java +++ b/spring-boot-cli/src/test/java/org/springframework/boot/cli/GrabCommandIntegrationTests.java @@ -26,9 +26,7 @@ import org.junit.Test; import org.springframework.boot.cli.command.grab.GrabCommand; import org.springframework.util.FileSystemUtils; -import static org.hamcrest.Matchers.containsString; -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; /** @@ -58,9 +56,10 @@ public class GrabCommandIntegrationTests { // Use --autoconfigure=false to limit the amount of downloaded dependencies String output = this.cli.grab("grab.groovy", "--autoconfigure=false"); - assertTrue(new File("target/repository/joda-time/joda-time").isDirectory()); + assertThat(new File("target/repository/joda-time/joda-time").isDirectory()) + .isTrue(); // Should be resolved from local repository cache - assertTrue(output.contains("Downloading: file:")); + assertThat(output.contains("Downloading: file:")).isTrue(); } @Test @@ -71,8 +70,8 @@ public class GrabCommandIntegrationTests { fail(); } catch (Exception ex) { - assertThat(ex.getMessage(), - containsString("Duplicate @DependencyManagementBom annotation")); + assertThat(ex.getMessage()) + .contains("Duplicate @DependencyManagementBom annotation"); } } @@ -83,6 +82,7 @@ public class GrabCommandIntegrationTests { new File("src/test/resources/grab-samples/repository"), new File("target/repository")); this.cli.grab("customDependencyManagement.groovy", "--autoconfigure=false"); - assertTrue(new File("target/repository/javax/ejb/ejb-api/3.0").isDirectory()); + assertThat(new File("target/repository/javax/ejb/ejb-api/3.0").isDirectory()) + .isTrue(); } } diff --git a/spring-boot-cli/src/test/java/org/springframework/boot/cli/ReproIntegrationTests.java b/spring-boot-cli/src/test/java/org/springframework/boot/cli/ReproIntegrationTests.java index 5067a43efa..831520f144 100644 --- a/spring-boot-cli/src/test/java/org/springframework/boot/cli/ReproIntegrationTests.java +++ b/spring-boot-cli/src/test/java/org/springframework/boot/cli/ReproIntegrationTests.java @@ -20,8 +20,7 @@ import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; -import static org.hamcrest.Matchers.containsString; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; /** * Integration tests to exercise and reproduce specific issues. @@ -41,8 +40,7 @@ public class ReproIntegrationTests { @Test public void grabAntBuilder() throws Exception { this.cli.run("grab-ant-builder.groovy"); - assertThat(this.cli.getHttpOutput(), - containsString("{\"message\":\"Hello World\"}")); + assertThat(this.cli.getHttpOutput()).contains("{\"message\":\"Hello World\"}"); } // Security depends on old versions of Spring so if the dependencies aren't pinned @@ -50,20 +48,19 @@ public class ReproIntegrationTests { @Test public void securityDependencies() throws Exception { this.cli.run("secure.groovy"); - assertThat(this.cli.getOutput(), containsString("Hello World")); + assertThat(this.cli.getOutput()).contains("Hello World"); } @Test public void shellDependencies() throws Exception { this.cli.run("crsh.groovy"); - assertThat(this.cli.getHttpOutput(), - containsString("{\"message\":\"Hello World\"}")); + assertThat(this.cli.getHttpOutput()).contains("{\"message\":\"Hello World\"}"); } @Test public void dataJpaDependencies() throws Exception { this.cli.run("data-jpa.groovy"); - assertThat(this.cli.getOutput(), containsString("Hello World")); + assertThat(this.cli.getOutput()).contains("Hello World"); } @Test diff --git a/spring-boot-cli/src/test/java/org/springframework/boot/cli/SampleIntegrationTests.java b/spring-boot-cli/src/test/java/org/springframework/boot/cli/SampleIntegrationTests.java index 20bb38164b..1da93844cc 100644 --- a/spring-boot-cli/src/test/java/org/springframework/boot/cli/SampleIntegrationTests.java +++ b/spring-boot-cli/src/test/java/org/springframework/boot/cli/SampleIntegrationTests.java @@ -23,10 +23,7 @@ import org.junit.Ignore; import org.junit.Rule; import org.junit.Test; -import static org.hamcrest.Matchers.containsString; -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; /** * Integration tests to exercise the samples. @@ -45,45 +42,40 @@ public class SampleIntegrationTests { public void appSample() throws Exception { String output = this.cli.run("app.groovy"); URI scriptUri = new File("samples/app.groovy").toURI(); - assertTrue("Wrong output: " + output, - output.contains("Hello World! From " + scriptUri)); + assertThat(output).contains("Hello World! From " + scriptUri); } @Test public void retrySample() throws Exception { String output = this.cli.run("retry.groovy"); URI scriptUri = new File("samples/retry.groovy").toURI(); - assertTrue("Wrong output: " + output, - output.contains("Hello World! From " + scriptUri)); + assertThat(output).contains("Hello World! From " + scriptUri); } @Test public void beansSample() throws Exception { this.cli.run("beans.groovy"); String output = this.cli.getHttpOutput(); - assertTrue("Wrong output: " + output, output.contains("Hello World!")); + assertThat(output).contains("Hello World!"); } @Test public void templateSample() throws Exception { String output = this.cli.run("template.groovy"); - assertTrue("Wrong output: " + output, output.contains("Hello World!")); + assertThat(output).contains("Hello World!"); } @Test public void jobSample() throws Exception { String output = this.cli.run("job.groovy", "foo=bar"); - assertTrue("Wrong output: " + output, - output.contains("completed with the following parameters")); + assertThat(output).contains("completed with the following parameters"); } @Test public void oauth2Sample() throws Exception { String output = this.cli.run("oauth2.groovy"); - assertTrue("Wrong output: " + output, - output.contains("security.oauth2.client.clientId")); - assertTrue("Wrong output: " + output, - output.contains("security.oauth2.client.secret =")); + assertThat(output).contains("security.oauth2.client.clientId"); + assertThat(output).contains("security.oauth2.client.secret ="); } @Test @@ -94,88 +86,85 @@ public class SampleIntegrationTests { Thread.sleep(200); output = this.cli.getOutput(); } - assertTrue("Wrong output: " + output, output.contains("Hello Phil")); + assertThat(output).contains("Hello Phil"); } @Test public void jobWebSample() throws Exception { String output = this.cli.run("job.groovy", "web.groovy", "foo=bar"); - assertTrue("Wrong output: " + output, - output.contains("completed with the following parameters")); + assertThat(output).contains("completed with the following parameters"); String result = this.cli.getHttpOutput(); - assertEquals("World!", result); + assertThat(result).isEqualTo("World!"); } @Test public void webSample() throws Exception { this.cli.run("web.groovy"); - assertEquals("World!", this.cli.getHttpOutput()); + assertThat(this.cli.getHttpOutput()).isEqualTo("World!"); } @Test public void uiSample() throws Exception { this.cli.run("ui.groovy", "--classpath=.:src/test/resources"); String result = this.cli.getHttpOutput(); - assertTrue("Wrong output: " + result, result.contains("Hello World")); + assertThat(result).contains("Hello World"); result = this.cli.getHttpOutput("/css/bootstrap.min.css"); - assertTrue("Wrong output: " + result, result.contains("container")); + assertThat(result).contains("container"); } @Test public void actuatorSample() throws Exception { this.cli.run("actuator.groovy"); - assertEquals("{\"message\":\"Hello World!\"}", this.cli.getHttpOutput()); + assertThat(this.cli.getHttpOutput()).isEqualTo("{\"message\":\"Hello World!\"}"); } @Test public void httpSample() throws Exception { String output = this.cli.run("http.groovy"); - assertTrue("Wrong output: " + output, output.contains("Hello World")); + assertThat(output).contains("Hello World"); } @Test public void integrationSample() throws Exception { String output = this.cli.run("integration.groovy"); - assertTrue("Wrong output: " + output, output.contains("Hello, World")); + assertThat(output).contains("Hello, World"); } @Test public void xmlSample() throws Exception { String output = this.cli.run("runner.xml", "runner.groovy"); - assertTrue("Wrong output: " + output, output.contains("Hello World")); + assertThat(output).contains("Hello World"); } @Test public void txSample() throws Exception { String output = this.cli.run("tx.groovy"); - assertTrue("Wrong output: " + output, output.contains("Foo count=")); + assertThat(output).contains("Foo count="); } @Test public void jmsSample() throws Exception { String output = this.cli.run("jms.groovy"); - assertTrue("Wrong output: " + output, - output.contains("Received Greetings from Spring Boot via HornetQ")); + assertThat(output).contains("Received Greetings from Spring Boot via HornetQ"); } @Test @Ignore("Requires RabbitMQ to be run, so disable it be default") public void rabbitSample() throws Exception { String output = this.cli.run("rabbit.groovy"); - assertTrue("Wrong output: " + output, - output.contains("Received Greetings from Spring Boot via RabbitMQ")); + assertThat(output).contains("Received Greetings from Spring Boot via RabbitMQ"); } @Test public void deviceSample() throws Exception { this.cli.run("device.groovy"); - assertEquals("Hello Normal Device!", this.cli.getHttpOutput()); + assertThat(this.cli.getHttpOutput()).isEqualTo("Hello Normal Device!"); } @Test public void caching() throws Exception { this.cli.run("caching.groovy"); - assertThat(this.cli.getOutput(), containsString("Hello World")); + assertThat(this.cli.getOutput()).contains("Hello World"); } } diff --git a/spring-boot-cli/src/test/java/org/springframework/boot/cli/TestCommandIntegrationTests.java b/spring-boot-cli/src/test/java/org/springframework/boot/cli/TestCommandIntegrationTests.java index 38b0813149..f6ff0bb598 100644 --- a/spring-boot-cli/src/test/java/org/springframework/boot/cli/TestCommandIntegrationTests.java +++ b/spring-boot-cli/src/test/java/org/springframework/boot/cli/TestCommandIntegrationTests.java @@ -24,8 +24,7 @@ import org.junit.rules.ExpectedException; import org.springframework.boot.cli.command.test.TestCommand; -import static org.hamcrest.Matchers.containsString; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; /** * Integration tests to exercise the CLI's test command. @@ -54,13 +53,13 @@ public class TestCommandIntegrationTests { @Test public void noTests() throws Throwable { String output = this.cli.test("book.groovy"); - assertThat(output, containsString("No tests found")); + assertThat(output).contains("No tests found"); } @Test public void empty() throws Exception { String output = this.cli.test("empty.groovy"); - assertThat(output, containsString("No tests found")); + assertThat(output).contains("No tests found"); } @Test @@ -74,48 +73,49 @@ public class TestCommandIntegrationTests { @Test public void appAndTestsInOneFile() throws Exception { String output = this.cli.test("book_and_tests.groovy"); - assertThat(output, containsString("OK (1 test)")); + assertThat(output).contains("OK (1 test)"); } @Test public void appInOneFileTestsInAnotherFile() throws Exception { String output = this.cli.test("book.groovy", "test.groovy"); - assertThat(output, containsString("OK (1 test)")); + assertThat(output).contains("OK (1 test)"); } @Test public void integrationTest() throws Exception { String output = this.cli.test("integration.groovy"); - assertThat(output, containsString("OK (1 test)")); + assertThat(output).contains("OK (1 test)"); } @Test public void integrationAutoConfigEmbeddedTest() throws Exception { String output = this.cli.test("integration_auto.groovy"); - assertThat(output, containsString("OK (1 test)")); + assertThat(output).contains("OK (1 test)"); } @Test public void integrationAutoConfigTest() throws Exception { String output = this.cli.test("integration_auto_test.groovy", "reactor.groovy"); - assertThat(output, containsString("OK (1 test)")); + assertThat(output).contains("OK (1 test)"); } @Test public void spockTester() throws Exception { String output = this.cli.test("spock.groovy"); - assertThat(output, containsString("OK (1 test)")); + assertThat(output).contains("OK (1 test)"); } @Test public void spockAndJunitTester() throws Exception { String output = this.cli.test("spock.groovy", "book_and_tests.groovy"); - assertThat(output, containsString("OK (2 tests)")); + assertThat(output).contains("OK (2 tests)"); } @Test public void verifyFailures() throws Exception { String output = this.cli.test("failures.groovy"); - assertThat(output, containsString("Tests run: 5, Failures: 3")); + assertThat(output).contains("Tests run: 5, Failures: 3"); } + } diff --git a/spring-boot-cli/src/test/java/org/springframework/boot/cli/app/SpringApplicationLauncherTests.java b/spring-boot-cli/src/test/java/org/springframework/boot/cli/app/SpringApplicationLauncherTests.java index 95bbf004d9..dfcc2804b4 100644 --- a/spring-boot-cli/src/test/java/org/springframework/boot/cli/app/SpringApplicationLauncherTests.java +++ b/spring-boot-cli/src/test/java/org/springframework/boot/cli/app/SpringApplicationLauncherTests.java @@ -24,10 +24,7 @@ import java.util.Set; import org.junit.After; import org.junit.Test; -import static org.hamcrest.Matchers.contains; -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 SpringApplicationLauncher} @@ -45,21 +42,21 @@ public class SpringApplicationLauncherTests { @Test public void defaultLaunch() throws Exception { - assertThat(launch(), contains("org.springframework.boot.SpringApplication")); + assertThat(launch()).contains("org.springframework.boot.SpringApplication"); } @Test public void launchWithClassConfiguredBySystemProperty() { System.setProperty("spring.application.class.name", "system.property.SpringApplication"); - assertThat(launch(), contains("system.property.SpringApplication")); + assertThat(launch()).contains("system.property.SpringApplication"); } @Test public void launchWithClassConfiguredByEnvironmentVariable() { this.env.put("SPRING_APPLICATION_CLASS_NAME", "environment.variable.SpringApplication"); - assertThat(launch(), contains("environment.variable.SpringApplication")); + assertThat(launch()).contains("environment.variable.SpringApplication"); } @Test @@ -68,7 +65,7 @@ public class SpringApplicationLauncherTests { "system.property.SpringApplication"); this.env.put("SPRING_APPLICATION_CLASS_NAME", "environment.variable.SpringApplication"); - assertThat(launch(), contains("system.property.SpringApplication")); + assertThat(launch()).contains("system.property.SpringApplication"); } @@ -80,14 +77,12 @@ public class SpringApplicationLauncherTests { String[] args = new String[0]; new SpringApplicationLauncher(getClass().getClassLoader()).launch(sources, args); - assertTrue(sources == TestSpringApplication.sources); - assertTrue(args == TestSpringApplication.args); + assertThat(sources == TestSpringApplication.sources).isTrue(); + assertThat(args == TestSpringApplication.args).isTrue(); Map defaultProperties = TestSpringApplication.defaultProperties; - assertThat(defaultProperties.size(), equalTo(1)); - assertThat( - defaultProperties.get("spring.groovy.template.check-template-location"), - equalTo("false")); + assertThat(defaultProperties).hasSize(1) + .containsEntry("spring.groovy.template.check-template-location", "false"); } private Set launch() { diff --git a/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/CommandRunnerIntegrationTests.java b/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/CommandRunnerIntegrationTests.java index c726b37199..ccdd31bf85 100644 --- a/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/CommandRunnerIntegrationTests.java +++ b/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/CommandRunnerIntegrationTests.java @@ -22,8 +22,7 @@ import org.junit.Test; import org.springframework.boot.cli.command.run.RunCommand; import org.springframework.boot.cli.util.OutputCapture; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Dave Syer @@ -40,7 +39,7 @@ public class CommandRunnerIntegrationTests { // -d counts as "debug" for the spring command, but not for the // LoggingApplicationListener runner.runAndHandleErrors("run", "samples/app.groovy", "-d"); - assertTrue(this.output.toString().contains("Negative matches:")); + assertThat(this.output.toString()).contains("Negative matches:"); } @Test @@ -48,6 +47,6 @@ public class CommandRunnerIntegrationTests { CommandRunner runner = new CommandRunner("spring"); runner.addCommand(new RunCommand()); runner.runAndHandleErrors("run", "samples/app.groovy", "--", "-d"); - assertFalse(this.output.toString().contains("Negative matches:")); + assertThat(this.output.toString()).doesNotContain("Negative matches:"); } } diff --git a/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/CommandRunnerTests.java b/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/CommandRunnerTests.java index ff82014ac4..0d2a8eefc8 100644 --- a/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/CommandRunnerTests.java +++ b/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/CommandRunnerTests.java @@ -30,10 +30,7 @@ import org.mockito.MockitoAnnotations; import org.springframework.boot.cli.command.core.HelpCommand; import org.springframework.boot.cli.command.core.HintCommand; -import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.BDDMockito.given; import static org.mockito.BDDMockito.willThrow; import static org.mockito.Mockito.verify; @@ -126,64 +123,61 @@ public class CommandRunnerTests { verify(this.regularCommand).run("--", "--debug", "bar"); // When handled by the command itself it shouldn't cause the system property to be // set - assertNull(System.getProperty("debug")); + assertThat(System.getProperty("debug")).isNull(); } @Test public void handlesSuccess() throws Exception { int status = this.commandRunner.runAndHandleErrors("command"); - assertThat(status, equalTo(0)); - assertThat(this.calls, equalTo((Set) EnumSet.noneOf(Call.class))); + assertThat(status).isEqualTo(0); + assertThat(this.calls).isEmpty(); } @Test public void handlesNoSuchCommand() throws Exception { int status = this.commandRunner.runAndHandleErrors("missing"); - assertThat(status, equalTo(1)); - assertThat(this.calls, equalTo((Set) EnumSet.of(Call.ERROR_MESSAGE))); + assertThat(status).isEqualTo(1); + assertThat(this.calls).containsOnly(Call.ERROR_MESSAGE); } @Test public void handlesRegularExceptionWithMessage() throws Exception { willThrow(new RuntimeException("With Message")).given(this.regularCommand).run(); int status = this.commandRunner.runAndHandleErrors("command"); - assertThat(status, equalTo(1)); - assertThat(this.calls, equalTo((Set) EnumSet.of(Call.ERROR_MESSAGE))); + assertThat(status).isEqualTo(1); + assertThat(this.calls).containsOnly(Call.ERROR_MESSAGE); } @Test public void handlesRegularExceptionWithoutMessage() throws Exception { willThrow(new NullPointerException()).given(this.regularCommand).run(); int status = this.commandRunner.runAndHandleErrors("command"); - assertThat(status, equalTo(1)); - assertThat(this.calls, equalTo( - (Set) EnumSet.of(Call.ERROR_MESSAGE, Call.PRINT_STACK_TRACE))); + assertThat(status).isEqualTo(1); + assertThat(this.calls).containsOnly(Call.ERROR_MESSAGE, Call.PRINT_STACK_TRACE); } @Test public void handlesExceptionWithDashD() throws Exception { willThrow(new RuntimeException()).given(this.regularCommand).run(); int status = this.commandRunner.runAndHandleErrors("command", "-d"); - assertEquals("true", System.getProperty("debug")); - assertThat(status, equalTo(1)); - assertThat(this.calls, equalTo( - (Set) EnumSet.of(Call.ERROR_MESSAGE, Call.PRINT_STACK_TRACE))); + assertThat(System.getProperty("debug")).isEqualTo("true"); + assertThat(status).isEqualTo(1); + assertThat(this.calls).containsOnly(Call.ERROR_MESSAGE, Call.PRINT_STACK_TRACE); } @Test public void handlesExceptionWithDashDashDebug() throws Exception { willThrow(new RuntimeException()).given(this.regularCommand).run(); int status = this.commandRunner.runAndHandleErrors("command", "--debug"); - assertEquals("true", System.getProperty("debug")); - assertThat(status, equalTo(1)); - assertThat(this.calls, equalTo( - (Set) EnumSet.of(Call.ERROR_MESSAGE, Call.PRINT_STACK_TRACE))); + assertThat(System.getProperty("debug")).isEqualTo("true"); + assertThat(status).isEqualTo(1); + assertThat(this.calls).containsOnly(Call.ERROR_MESSAGE, Call.PRINT_STACK_TRACE); } @Test public void exceptionMessages() throws Exception { - assertThat(new NoSuchCommandException("name").getMessage(), - equalTo("'name' is not a valid command. See 'help'.")); + assertThat(new NoSuchCommandException("name").getMessage()) + .isEqualTo("'name' is not a valid command. See 'help'."); } @Test diff --git a/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/OptionParsingCommandTests.java b/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/OptionParsingCommandTests.java index a751ecf16f..83771782fe 100644 --- a/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/OptionParsingCommandTests.java +++ b/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/OptionParsingCommandTests.java @@ -20,8 +20,7 @@ import org.junit.Test; import org.springframework.boot.cli.command.options.OptionHandler; -import static org.hamcrest.Matchers.containsString; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link OptionParsingCommand}. @@ -34,9 +33,17 @@ public class OptionParsingCommandTests { public void optionHelp() { OptionHandler handler = new OptionHandler(); handler.option("bar", "Bar"); - OptionParsingCommand command = new OptionParsingCommand("foo", "Foo", handler) { - }; - assertThat(command.getHelp(), containsString("--bar")); + OptionParsingCommand command = new TestOptionParsingCommand("foo", "Foo", + handler); + assertThat(command.getHelp()).contains("--bar"); + } + + private static class TestOptionParsingCommand extends OptionParsingCommand { + + TestOptionParsingCommand(String name, String description, OptionHandler handler) { + super(name, description, handler); + } + } } diff --git a/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/archive/ResourceMatcherTests.java b/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/archive/ResourceMatcherTests.java index c437769d86..fc86047cd0 100644 --- a/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/archive/ResourceMatcherTests.java +++ b/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/archive/ResourceMatcherTests.java @@ -23,19 +23,13 @@ import java.util.Arrays; import java.util.Collection; import java.util.List; -import org.hamcrest.Description; -import org.hamcrest.TypeSafeMatcher; +import org.assertj.core.api.Condition; import org.junit.Test; import org.springframework.boot.cli.command.archive.ResourceMatcher.MatchedResource; import org.springframework.test.util.ReflectionTestUtils; -import static org.hamcrest.Matchers.hasItem; -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.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link ResourceMatcher}. @@ -51,7 +45,7 @@ public class ResourceMatcherTests { Arrays.asList(".*", "alpha/**/excluded")); List matchedResources = resourceMatcher .find(Arrays.asList(new File("does-not-exist"))); - assertEquals(0, matchedResources.size()); + assertThat(matchedResources).isEmpty(); } @SuppressWarnings("unchecked") @@ -59,10 +53,12 @@ public class ResourceMatcherTests { public void defaults() throws Exception { ResourceMatcher resourceMatcher = new ResourceMatcher(Arrays.asList(""), Arrays.asList("")); - assertTrue(((Collection) ReflectionTestUtils.getField(resourceMatcher, - "includes")).contains("static/**")); - assertTrue(((Collection) ReflectionTestUtils.getField(resourceMatcher, - "excludes")).contains("**/*.jar")); + Collection includes = (Collection) ReflectionTestUtils + .getField(resourceMatcher, "includes"); + Collection excludes = (Collection) ReflectionTestUtils + .getField(resourceMatcher, "excludes"); + assertThat(includes).contains("static/**"); + assertThat(excludes).contains("**/*.jar"); } @Test @@ -71,7 +67,14 @@ public class ResourceMatcherTests { Arrays.asList("**/*.jar")); List found = resourceMatcher .find(Arrays.asList(new File("src/test/resources"))); - assertThat(found, not(hasItem(new FooJarMatcher(MatchedResource.class)))); + assertThat(found).areNot(new Condition() { + + @Override + public boolean matches(MatchedResource value) { + return value.getFile().getName().equals("foo.jar"); + } + + }); } @SuppressWarnings("unchecked") @@ -81,8 +84,8 @@ public class ResourceMatcherTests { Arrays.asList("")); Collection includes = (Collection) ReflectionTestUtils .getField(resourceMatcher, "includes"); - assertTrue(includes.contains("templates/**")); - assertFalse(includes.contains("static/**")); + assertThat(includes).contains("templates/**"); + assertThat(includes).doesNotContain("static/**"); } @SuppressWarnings("unchecked") @@ -92,11 +95,12 @@ public class ResourceMatcherTests { Arrays.asList("-static/**", "foo.jar"), Arrays.asList("-**/*.jar")); Collection includes = (Collection) ReflectionTestUtils .getField(resourceMatcher, "includes"); - assertTrue(includes.contains("foo.jar")); - assertTrue(includes.contains("templates/**")); - assertFalse(includes.contains("static/**")); - assertFalse(((Collection) ReflectionTestUtils.getField(resourceMatcher, - "excludes")).contains("**/*.jar")); + Collection excludes = (Collection) ReflectionTestUtils + .getField(resourceMatcher, "excludes"); + assertThat(includes).contains("foo.jar"); + assertThat(includes).contains("templates/**"); + assertThat(includes).doesNotContain("static/**"); + assertThat(excludes).doesNotContain("**/*.jar"); } @SuppressWarnings("unchecked") @@ -104,8 +108,9 @@ public class ResourceMatcherTests { public void excludedDeltas() throws Exception { ResourceMatcher resourceMatcher = new ResourceMatcher(Arrays.asList(""), Arrays.asList("-**/*.jar")); - assertFalse(((Collection) ReflectionTestUtils.getField(resourceMatcher, - "excludes")).contains("**/*.jar")); + Collection excludes = (Collection) ReflectionTestUtils + .getField(resourceMatcher, "excludes"); + assertThat(excludes).doesNotContain("**/*.jar"); } @Test @@ -115,10 +120,14 @@ public class ResourceMatcherTests { List found = resourceMatcher .find(Arrays.asList(new File("src/test/resources/templates"), new File("src/test/resources/foo.jar"))); - FooJarMatcher matcher = new FooJarMatcher(MatchedResource.class); - assertThat(found, hasItem(matcher)); - // A jar file is always treated as a dependency (stick it in /lib) - assertTrue(matcher.getMatched().isRoot()); + assertThat(found).areAtLeastOne(new Condition() { + + @Override + public boolean matches(MatchedResource value) { + return value.getFile().getName().equals("foo.jar") && value.isRoot(); + } + + }); } @Test @@ -135,37 +144,8 @@ public class ResourceMatcherTests { for (MatchedResource resource : matchedResources) { paths.add(resource.getName()); } - - assertEquals(6, paths.size()); - assertTrue(paths.containsAll(Arrays.asList("alpha/nested/fileA", "bravo/fileC", - "fileD", "bravo/fileE", "fileF", "three"))); - } - - private final class FooJarMatcher extends TypeSafeMatcher { - - private MatchedResource matched; - - public MatchedResource getMatched() { - return this.matched; - } - - private FooJarMatcher(Class expectedType) { - super(expectedType); - } - - @Override - public void describeTo(Description description) { - description.appendText("foo.jar"); - } - - @Override - protected boolean matchesSafely(MatchedResource item) { - boolean matches = item.getFile().getName().equals("foo.jar"); - if (matches) { - this.matched = item; - } - return matches; - } + assertThat(paths).containsOnly("alpha/nested/fileA", "bravo/fileC", "fileD", + "bravo/fileE", "fileF", "three"); } } diff --git a/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/init/InitCommandTests.java b/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/init/InitCommandTests.java index f592399060..5f392d34e5 100644 --- a/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/init/InitCommandTests.java +++ b/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/init/InitCommandTests.java @@ -37,12 +37,7 @@ import org.mockito.MockitoAnnotations; import org.springframework.boot.cli.command.status.ExitStatus; -import static org.hamcrest.Matchers.startsWith; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -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.mockito.Mockito.verify; /** @@ -96,16 +91,16 @@ public class InitCommandTests extends AbstractHttpClientMockTests { public void generateProject() throws Exception { String fileName = UUID.randomUUID().toString() + ".zip"; File file = new File(fileName); - assertFalse("file should not exist", file.exists()); + assertThat(file.exists()).as("file should not exist").isFalse(); MockHttpProjectGenerationRequest request = new MockHttpProjectGenerationRequest( "application/zip", fileName); mockSuccessfulProjectGeneration(request); try { - assertEquals(ExitStatus.OK, this.command.run()); - assertTrue("file should have been created", file.exists()); + assertThat(this.command.run()).isEqualTo(ExitStatus.OK); + assertThat(file.exists()).as("file should have been created").isTrue(); } finally { - assertTrue("failed to delete test file", file.delete()); + assertThat(file.delete()).as("failed to delete test file").isTrue(); } } @@ -114,7 +109,7 @@ public class InitCommandTests extends AbstractHttpClientMockTests { MockHttpProjectGenerationRequest request = new MockHttpProjectGenerationRequest( "application/zip", null); mockSuccessfulProjectGeneration(request); - assertEquals(ExitStatus.ERROR, this.command.run()); + assertThat(this.command.run()).isEqualTo(ExitStatus.ERROR); } @Test @@ -124,11 +119,10 @@ public class InitCommandTests extends AbstractHttpClientMockTests { MockHttpProjectGenerationRequest request = new MockHttpProjectGenerationRequest( "application/zip", "demo.zip", archive); mockSuccessfulProjectGeneration(request); - assertEquals(ExitStatus.OK, - this.command.run("--extract", folder.getAbsolutePath())); + assertThat(this.command.run("--extract", folder.getAbsolutePath())) + .isEqualTo(ExitStatus.OK); File archiveFile = new File(folder, "test.txt"); - assertTrue("Archive not extracted properly " + archiveFile.getAbsolutePath() - + " not found", archiveFile.exists()); + assertThat(archiveFile).exists(); } @Test @@ -138,16 +132,16 @@ public class InitCommandTests extends AbstractHttpClientMockTests { MockHttpProjectGenerationRequest request = new MockHttpProjectGenerationRequest( "application/zip", "demo.zip", archive); mockSuccessfulProjectGeneration(request); - assertEquals(ExitStatus.OK, this.command.run(folder.getAbsolutePath() + "/")); + assertThat(this.command.run(folder.getAbsolutePath() + "/")) + .isEqualTo(ExitStatus.OK); File archiveFile = new File(folder, "test.txt"); - assertTrue("Archive not extracted properly " + archiveFile.getAbsolutePath() - + " not found", archiveFile.exists()); + assertThat(archiveFile).exists(); } @Test public void generateProjectArchiveExtractedByDefault() throws Exception { String fileName = UUID.randomUUID().toString(); - assertFalse("No dot in filename", fileName.contains(".")); + assertThat(fileName.contains(".")).as("No dot in filename").isFalse(); byte[] archive = createFakeZipArchive("test.txt", "Fake content"); MockHttpProjectGenerationRequest request = new MockHttpProjectGenerationRequest( "application/zip", "demo.zip", archive); @@ -155,9 +149,8 @@ public class InitCommandTests extends AbstractHttpClientMockTests { File file = new File(fileName); File archiveFile = new File(file, "test.txt"); try { - assertEquals(ExitStatus.OK, this.command.run(fileName)); - assertTrue("Archive not extracted properly " + archiveFile.getAbsolutePath() - + " not found", archiveFile.exists()); + assertThat(this.command.run(fileName)).isEqualTo(ExitStatus.OK); + assertThat(archiveFile).exists(); } finally { archiveFile.delete(); @@ -175,9 +168,9 @@ public class InitCommandTests extends AbstractHttpClientMockTests { mockSuccessfulProjectGeneration(request); File file = new File(fileName); try { - assertEquals(ExitStatus.OK, this.command.run(fileName)); - assertTrue("File not saved properly", file.exists()); - assertTrue("Should not be a directory", file.isFile()); + assertThat(this.command.run(fileName)).isEqualTo(ExitStatus.OK); + assertThat(file.exists()).as("File not saved properly").isTrue(); + assertThat(file.isFile()).as("Should not be a directory").isTrue(); } finally { file.delete(); @@ -189,18 +182,18 @@ public class InitCommandTests extends AbstractHttpClientMockTests { File folder = this.temporaryFolder.newFolder(); String fileName = UUID.randomUUID().toString() + ".zip"; File file = new File(fileName); - assertFalse("file should not exist", file.exists()); + assertThat(file.exists()).as("file should not exist").isFalse(); try { byte[] archive = createFakeZipArchive("test.txt", "Fake content"); MockHttpProjectGenerationRequest request = new MockHttpProjectGenerationRequest( "application/foobar", fileName, archive); mockSuccessfulProjectGeneration(request); - assertEquals(ExitStatus.OK, - this.command.run("--extract", folder.getAbsolutePath())); - assertTrue("file should have been saved instead", file.exists()); + assertThat(this.command.run("--extract", folder.getAbsolutePath())) + .isEqualTo(ExitStatus.OK); + assertThat(file.exists()).as("file should have been saved instead").isTrue(); } finally { - assertTrue("failed to delete test file", file.delete()); + assertThat(file.delete()).as("failed to delete test file").isTrue(); } } @@ -209,18 +202,18 @@ public class InitCommandTests extends AbstractHttpClientMockTests { File folder = this.temporaryFolder.newFolder(); String fileName = UUID.randomUUID().toString() + ".zip"; File file = new File(fileName); - assertFalse("file should not exist", file.exists()); + assertThat(file.exists()).as("file should not exist").isFalse(); try { byte[] archive = createFakeZipArchive("test.txt", "Fake content"); MockHttpProjectGenerationRequest request = new MockHttpProjectGenerationRequest( null, fileName, archive); mockSuccessfulProjectGeneration(request); - assertEquals(ExitStatus.OK, - this.command.run("--extract", folder.getAbsolutePath())); - assertTrue("file should have been saved instead", file.exists()); + assertThat(this.command.run("--extract", folder.getAbsolutePath())) + .isEqualTo(ExitStatus.OK); + assertThat(file.exists()).as("file should have been saved instead").isTrue(); } finally { - assertTrue("failed to delete test file", file.delete()); + assertThat(file.delete()).as("failed to delete test file").isTrue(); } } @@ -231,8 +224,10 @@ public class InitCommandTests extends AbstractHttpClientMockTests { MockHttpProjectGenerationRequest request = new MockHttpProjectGenerationRequest( "application/zip", file.getAbsolutePath()); mockSuccessfulProjectGeneration(request); - assertEquals("Should have failed", ExitStatus.ERROR, this.command.run()); - assertEquals("File should not have changed", fileLength, file.length()); + assertThat(this.command.run()).as("Should have failed") + .isEqualTo(ExitStatus.ERROR); + assertThat(file.length()).as("File should not have changed") + .isEqualTo(fileLength); } @Test @@ -242,25 +237,26 @@ public class InitCommandTests extends AbstractHttpClientMockTests { MockHttpProjectGenerationRequest request = new MockHttpProjectGenerationRequest( "application/zip", file.getAbsolutePath()); mockSuccessfulProjectGeneration(request); - assertEquals("Should not have failed", ExitStatus.OK, - this.command.run("--force")); - assertTrue("File should have changed", fileLength != file.length()); + assertThat(this.command.run("--force")).isEqualTo(ExitStatus.OK); + assertThat(fileLength != file.length()).as("File should have changed").isTrue(); } @Test public void fileInArchiveNotOverwrittenByDefault() throws Exception { File folder = this.temporaryFolder.newFolder(); File conflict = new File(folder, "test.txt"); - assertTrue("Should have been able to create file", conflict.createNewFile()); + assertThat(conflict.createNewFile()).as("Should have been able to create file") + .isTrue(); long fileLength = conflict.length(); // also contains test.txt byte[] archive = createFakeZipArchive("test.txt", "Fake content"); MockHttpProjectGenerationRequest request = new MockHttpProjectGenerationRequest( "application/zip", "demo.zip", archive); mockSuccessfulProjectGeneration(request); - assertEquals(ExitStatus.ERROR, - this.command.run("--extract", folder.getAbsolutePath())); - assertEquals("File should not have changed", fileLength, conflict.length()); + assertThat(this.command.run("--extract", folder.getAbsolutePath())) + .isEqualTo(ExitStatus.ERROR); + assertThat(conflict.length()).as("File should not have changed") + .isEqualTo(fileLength); } @Test @@ -270,90 +266,93 @@ public class InitCommandTests extends AbstractHttpClientMockTests { "--description=Acme sample project", "--package-name=demo.foo", "-t=ant-project", "--build=grunt", "--format=web", "-p=war", "-j=1.9", "-l=groovy", "-b=1.2.0.RELEASE", "-d=web,data-jpa"); - assertEquals("org.demo", this.handler.lastRequest.getGroupId()); - assertEquals("acme", this.handler.lastRequest.getArtifactId()); - assertEquals("1.2.3-SNAPSHOT", this.handler.lastRequest.getVersion()); - assertEquals("acme-sample", this.handler.lastRequest.getName()); - assertEquals("Acme sample project", this.handler.lastRequest.getDescription()); - assertEquals("demo.foo", this.handler.lastRequest.getPackageName()); - assertEquals("ant-project", this.handler.lastRequest.getType()); - assertEquals("grunt", this.handler.lastRequest.getBuild()); - assertEquals("web", this.handler.lastRequest.getFormat()); - assertEquals("war", this.handler.lastRequest.getPackaging()); - assertEquals("1.9", this.handler.lastRequest.getJavaVersion()); - assertEquals("groovy", this.handler.lastRequest.getLanguage()); - assertEquals("1.2.0.RELEASE", this.handler.lastRequest.getBootVersion()); + assertThat(this.handler.lastRequest.getGroupId()).isEqualTo("org.demo"); + assertThat(this.handler.lastRequest.getArtifactId()).isEqualTo("acme"); + assertThat(this.handler.lastRequest.getVersion()).isEqualTo("1.2.3-SNAPSHOT"); + assertThat(this.handler.lastRequest.getName()).isEqualTo("acme-sample"); + assertThat(this.handler.lastRequest.getDescription()) + .isEqualTo("Acme sample project"); + assertThat(this.handler.lastRequest.getPackageName()).isEqualTo("demo.foo"); + assertThat(this.handler.lastRequest.getType()).isEqualTo("ant-project"); + assertThat(this.handler.lastRequest.getBuild()).isEqualTo("grunt"); + assertThat(this.handler.lastRequest.getFormat()).isEqualTo("web"); + assertThat(this.handler.lastRequest.getPackaging()).isEqualTo("war"); + assertThat(this.handler.lastRequest.getJavaVersion()).isEqualTo("1.9"); + assertThat(this.handler.lastRequest.getLanguage()).isEqualTo("groovy"); + assertThat(this.handler.lastRequest.getBootVersion()).isEqualTo("1.2.0.RELEASE"); List dependencies = this.handler.lastRequest.getDependencies(); - assertEquals(2, dependencies.size()); - assertTrue(dependencies.contains("web")); - assertTrue(dependencies.contains("data-jpa")); + assertThat(dependencies).hasSize(2); + assertThat(dependencies.contains("web")).isTrue(); + assertThat(dependencies.contains("data-jpa")).isTrue(); } @Test public void overwriteFileInArchive() throws Exception { File folder = this.temporaryFolder.newFolder(); File conflict = new File(folder, "test.txt"); - assertTrue("Should have been able to create file", conflict.createNewFile()); + assertThat(conflict.createNewFile()).as("Should have been able to create file") + .isTrue(); long fileLength = conflict.length(); // also contains test.txt byte[] archive = createFakeZipArchive("test.txt", "Fake content"); MockHttpProjectGenerationRequest request = new MockHttpProjectGenerationRequest( "application/zip", "demo.zip", archive); mockSuccessfulProjectGeneration(request); - assertEquals(ExitStatus.OK, - this.command.run("--force", "--extract", folder.getAbsolutePath())); - assertTrue("File should have changed", fileLength != conflict.length()); + assertThat(this.command.run("--force", "--extract", folder.getAbsolutePath())) + .isEqualTo(ExitStatus.OK); + assertThat(fileLength != conflict.length()).as("File should have changed") + .isTrue(); } @Test public void parseTypeOnly() throws Exception { this.handler.disableProjectGeneration(); this.command.run("-t=ant-project"); - assertEquals("maven", this.handler.lastRequest.getBuild()); - assertEquals("project", this.handler.lastRequest.getFormat()); - assertFalse(this.handler.lastRequest.isDetectType()); - assertEquals("ant-project", this.handler.lastRequest.getType()); + assertThat(this.handler.lastRequest.getBuild()).isEqualTo("maven"); + assertThat(this.handler.lastRequest.getFormat()).isEqualTo("project"); + assertThat(this.handler.lastRequest.isDetectType()).isFalse(); + assertThat(this.handler.lastRequest.getType()).isEqualTo("ant-project"); } @Test public void parseBuildOnly() throws Exception { this.handler.disableProjectGeneration(); this.command.run("--build=ant"); - assertEquals("ant", this.handler.lastRequest.getBuild()); - assertEquals("project", this.handler.lastRequest.getFormat()); - assertTrue(this.handler.lastRequest.isDetectType()); - assertNull(this.handler.lastRequest.getType()); + assertThat(this.handler.lastRequest.getBuild()).isEqualTo("ant"); + assertThat(this.handler.lastRequest.getFormat()).isEqualTo("project"); + assertThat(this.handler.lastRequest.isDetectType()).isTrue(); + assertThat(this.handler.lastRequest.getType()).isNull(); } @Test public void parseFormatOnly() throws Exception { this.handler.disableProjectGeneration(); this.command.run("--format=web"); - assertEquals("maven", this.handler.lastRequest.getBuild()); - assertEquals("web", this.handler.lastRequest.getFormat()); - assertTrue(this.handler.lastRequest.isDetectType()); - assertNull(this.handler.lastRequest.getType()); + assertThat(this.handler.lastRequest.getBuild()).isEqualTo("maven"); + assertThat(this.handler.lastRequest.getFormat()).isEqualTo("web"); + assertThat(this.handler.lastRequest.isDetectType()).isTrue(); + assertThat(this.handler.lastRequest.getType()).isNull(); } @Test public void parseLocation() throws Exception { this.handler.disableProjectGeneration(); this.command.run("foobar.zip"); - assertEquals("foobar.zip", this.handler.lastRequest.getOutput()); + assertThat(this.handler.lastRequest.getOutput()).isEqualTo("foobar.zip"); } @Test public void parseLocationWithSlash() throws Exception { this.handler.disableProjectGeneration(); this.command.run("foobar/"); - assertEquals("foobar", this.handler.lastRequest.getOutput()); - assertTrue(this.handler.lastRequest.isExtract()); + assertThat(this.handler.lastRequest.getOutput()).isEqualTo("foobar"); + assertThat(this.handler.lastRequest.isExtract()).isTrue(); } @Test public void parseMoreThanOneArg() throws Exception { this.handler.disableProjectGeneration(); - assertEquals(ExitStatus.ERROR, this.command.run("foobar", "barfoo")); + assertThat(this.command.run("foobar", "barfoo")).isEqualTo(ExitStatus.ERROR); } @Test @@ -361,7 +360,7 @@ public class InitCommandTests extends AbstractHttpClientMockTests { this.command.run("--list", "--target=http://fake-service"); verify(this.http).execute(this.requestCaptor.capture()); Header agent = this.requestCaptor.getValue().getHeaders("User-Agent")[0]; - assertThat(agent.getValue(), startsWith("SpringBootCli/")); + assertThat(agent.getValue()).startsWith("SpringBootCli/"); } private byte[] createFakeZipArchive(String fileName, String content) diff --git a/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/init/InitializrServiceMetadataTests.java b/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/init/InitializrServiceMetadataTests.java index 15c151d9eb..a9d75ec612 100644 --- a/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/init/InitializrServiceMetadataTests.java +++ b/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/init/InitializrServiceMetadataTests.java @@ -27,8 +27,7 @@ import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.Resource; import org.springframework.util.StreamUtils; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link InitializrServiceMetadata} @@ -40,43 +39,43 @@ public class InitializrServiceMetadataTests { @Test public void parseDefaults() { InitializrServiceMetadata metadata = createInstance("2.0.0"); - assertEquals("1.1.8.RELEASE", metadata.getDefaults().get("bootVersion")); - assertEquals("1.7", metadata.getDefaults().get("javaVersion")); - assertEquals("org.test", metadata.getDefaults().get("groupId")); - assertEquals("demo", metadata.getDefaults().get("name")); - assertEquals("Demo project for Spring Boot", - metadata.getDefaults().get("description")); - assertEquals("jar", metadata.getDefaults().get("packaging")); - assertEquals("java", metadata.getDefaults().get("language")); - assertEquals("demo", metadata.getDefaults().get("artifactId")); - assertEquals("demo", metadata.getDefaults().get("packageName")); - assertEquals("maven-project", metadata.getDefaults().get("type")); - assertEquals("0.0.1-SNAPSHOT", metadata.getDefaults().get("version")); - assertEquals("Wrong number of defaults", 11, metadata.getDefaults().size()); + assertThat(metadata.getDefaults().get("bootVersion")).isEqualTo("1.1.8.RELEASE"); + assertThat(metadata.getDefaults().get("javaVersion")).isEqualTo("1.7"); + assertThat(metadata.getDefaults().get("groupId")).isEqualTo("org.test"); + assertThat(metadata.getDefaults().get("name")).isEqualTo("demo"); + assertThat(metadata.getDefaults().get("description")) + .isEqualTo("Demo project for Spring Boot"); + assertThat(metadata.getDefaults().get("packaging")).isEqualTo("jar"); + assertThat(metadata.getDefaults().get("language")).isEqualTo("java"); + assertThat(metadata.getDefaults().get("artifactId")).isEqualTo("demo"); + assertThat(metadata.getDefaults().get("packageName")).isEqualTo("demo"); + assertThat(metadata.getDefaults().get("type")).isEqualTo("maven-project"); + assertThat(metadata.getDefaults().get("version")).isEqualTo("0.0.1-SNAPSHOT"); + assertThat(metadata.getDefaults()).as("Wrong number of defaults").hasSize(11); } @Test public void parseDependencies() { InitializrServiceMetadata metadata = createInstance("2.0.0"); - assertEquals(5, metadata.getDependencies().size()); + assertThat(metadata.getDependencies()).hasSize(5); // Security description - assertEquals("AOP", metadata.getDependency("aop").getName()); - assertEquals("Security", metadata.getDependency("security").getName()); - assertEquals("Security description", - metadata.getDependency("security").getDescription()); - assertEquals("JDBC", metadata.getDependency("jdbc").getName()); - assertEquals("JPA", metadata.getDependency("data-jpa").getName()); - assertEquals("MongoDB", metadata.getDependency("data-mongodb").getName()); + assertThat(metadata.getDependency("aop").getName()).isEqualTo("AOP"); + assertThat(metadata.getDependency("security").getName()).isEqualTo("Security"); + assertThat(metadata.getDependency("security").getDescription()) + .isEqualTo("Security description"); + assertThat(metadata.getDependency("jdbc").getName()).isEqualTo("JDBC"); + assertThat(metadata.getDependency("data-jpa").getName()).isEqualTo("JPA"); + assertThat(metadata.getDependency("data-mongodb").getName()).isEqualTo("MongoDB"); } @Test public void parseTypes() { InitializrServiceMetadata metadata = createInstance("2.0.0"); ProjectType projectType = metadata.getProjectTypes().get("maven-project"); - assertNotNull(projectType); - assertEquals("maven", projectType.getTags().get("build")); - assertEquals("project", projectType.getTags().get("format")); + assertThat(projectType).isNotNull(); + assertThat(projectType.getTags().get("build")).isEqualTo("maven"); + assertThat(projectType.getTags().get("format")).isEqualTo("project"); } private static InitializrServiceMetadata createInstance(String version) { diff --git a/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/init/InitializrServiceTests.java b/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/init/InitializrServiceTests.java index b239f24b5d..01435147c7 100644 --- a/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/init/InitializrServiceTests.java +++ b/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/init/InitializrServiceTests.java @@ -24,10 +24,7 @@ import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.BDDMockito.given; import static org.mockito.Matchers.isA; import static org.mockito.Mockito.mock; @@ -48,7 +45,7 @@ public class InitializrServiceTests extends AbstractHttpClientMockTests { public void loadMetadata() throws IOException { mockSuccessfulMetadataGet(false); InitializrServiceMetadata metadata = this.invoker.loadMetadata("http://foo/bar"); - assertNotNull(metadata); + assertThat(metadata).isNotNull(); } @Test @@ -149,20 +146,20 @@ public class InitializrServiceTests extends AbstractHttpClientMockTests { MockHttpProjectGenerationRequest mockRequest) throws IOException { mockSuccessfulProjectGeneration(mockRequest); ProjectGenerationResponse entity = this.invoker.generate(request); - assertArrayEquals("wrong body content", mockRequest.content, entity.getContent()); + assertThat(entity.getContent()).as("wrong body content") + .isEqualTo(mockRequest.content); return entity; } private static void assertProjectEntity(ProjectGenerationResponse entity, String mimeType, String fileName) { if (mimeType == null) { - assertNull("No content type expected", entity.getContentType()); + assertThat(entity.getContentType()).isNull(); } else { - assertEquals("wrong mime type", mimeType, - entity.getContentType().getMimeType()); + assertThat(entity.getContentType().getMimeType()).isEqualTo(mimeType); } - assertEquals("wrong filename", fileName, entity.getFileName()); + assertThat(entity.getFileName()).isEqualTo(fileName); } } diff --git a/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/init/ProjectGenerationRequestTests.java b/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/init/ProjectGenerationRequestTests.java index f16d0f5a3d..3e89f1daea 100644 --- a/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/init/ProjectGenerationRequestTests.java +++ b/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/init/ProjectGenerationRequestTests.java @@ -32,7 +32,7 @@ import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.Resource; import org.springframework.util.StreamUtils; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link ProjectGenerationRequest} @@ -52,8 +52,8 @@ public class ProjectGenerationRequestTests { @Test public void defaultSettings() { - assertEquals(createDefaultUrl("?type=test-type"), - this.request.generateUrl(createDefaultMetadata())); + assertThat(this.request.generateUrl(createDefaultMetadata())) + .isEqualTo(createDefaultUrl("?type=test-type")); } @Test @@ -61,46 +61,44 @@ public class ProjectGenerationRequestTests { String customServerUrl = "http://foo:8080/initializr"; this.request.setServiceUrl(customServerUrl); this.request.getDependencies().add("security"); - assertEquals( - new URI(customServerUrl - + "/starter.zip?dependencies=security&type=test-type"), - this.request.generateUrl(createDefaultMetadata())); + assertThat(this.request.generateUrl(createDefaultMetadata())).isEqualTo(new URI( + customServerUrl + "/starter.zip?dependencies=security&type=test-type")); } @Test public void customBootVersion() { this.request.setBootVersion("1.2.0.RELEASE"); - assertEquals(createDefaultUrl("?type=test-type&bootVersion=1.2.0.RELEASE"), - this.request.generateUrl(createDefaultMetadata())); + assertThat(this.request.generateUrl(createDefaultMetadata())) + .isEqualTo(createDefaultUrl("?type=test-type&bootVersion=1.2.0.RELEASE")); } @Test public void singleDependency() { this.request.getDependencies().add("web"); - assertEquals(createDefaultUrl("?dependencies=web&type=test-type"), - this.request.generateUrl(createDefaultMetadata())); + assertThat(this.request.generateUrl(createDefaultMetadata())) + .isEqualTo(createDefaultUrl("?dependencies=web&type=test-type")); } @Test public void multipleDependencies() { this.request.getDependencies().add("web"); this.request.getDependencies().add("data-jpa"); - assertEquals(createDefaultUrl("?dependencies=web%2Cdata-jpa&type=test-type"), - this.request.generateUrl(createDefaultMetadata())); + assertThat(this.request.generateUrl(createDefaultMetadata())).isEqualTo( + createDefaultUrl("?dependencies=web%2Cdata-jpa&type=test-type")); } @Test public void customJavaVersion() { this.request.setJavaVersion("1.8"); - assertEquals(createDefaultUrl("?type=test-type&javaVersion=1.8"), - this.request.generateUrl(createDefaultMetadata())); + assertThat(this.request.generateUrl(createDefaultMetadata())) + .isEqualTo(createDefaultUrl("?type=test-type&javaVersion=1.8")); } @Test public void customPackageName() { this.request.setPackageName("demo.foo"); - assertEquals(createDefaultUrl("?packageName=demo.foo&type=test-type"), - this.request.generateUrl(createDefaultMetadata())); + assertThat(this.request.generateUrl(createDefaultMetadata())) + .isEqualTo(createDefaultUrl("?packageName=demo.foo&type=test-type")); } @Test @@ -110,24 +108,23 @@ public class ProjectGenerationRequestTests { InitializrServiceMetadata metadata = new InitializrServiceMetadata(projectType); this.request.setType("custom"); this.request.getDependencies().add("data-rest"); - assertEquals( - new URI(ProjectGenerationRequest.DEFAULT_SERVICE_URL - + "/foo?dependencies=data-rest&type=custom"), - this.request.generateUrl(metadata)); + assertThat(this.request.generateUrl(metadata)) + .isEqualTo(new URI(ProjectGenerationRequest.DEFAULT_SERVICE_URL + + "/foo?dependencies=data-rest&type=custom")); } @Test public void customPackaging() { this.request.setPackaging("war"); - assertEquals(createDefaultUrl("?type=test-type&packaging=war"), - this.request.generateUrl(createDefaultMetadata())); + assertThat(this.request.generateUrl(createDefaultMetadata())) + .isEqualTo(createDefaultUrl("?type=test-type&packaging=war")); } @Test public void customLanguage() { this.request.setLanguage("groovy"); - assertEquals(createDefaultUrl("?type=test-type&language=groovy"), - this.request.generateUrl(createDefaultMetadata())); + assertThat(this.request.generateUrl(createDefaultMetadata())) + .isEqualTo(createDefaultUrl("?type=test-type&language=groovy")); } @Test @@ -136,40 +133,39 @@ public class ProjectGenerationRequestTests { this.request.setArtifactId("sample"); this.request.setVersion("1.0.1-SNAPSHOT"); this.request.setDescription("Spring Boot Test"); - assertEquals( - createDefaultUrl( + assertThat(this.request.generateUrl(createDefaultMetadata())) + .isEqualTo(createDefaultUrl( "?groupId=org.acme&artifactId=sample&version=1.0.1-SNAPSHOT" - + "&description=Spring+Boot+Test&type=test-type"), - this.request.generateUrl(createDefaultMetadata())); + + "&description=Spring+Boot+Test&type=test-type")); } @Test public void outputCustomizeArtifactId() { this.request.setOutput("my-project"); - assertEquals(createDefaultUrl("?artifactId=my-project&type=test-type"), - this.request.generateUrl(createDefaultMetadata())); + assertThat(this.request.generateUrl(createDefaultMetadata())) + .isEqualTo(createDefaultUrl("?artifactId=my-project&type=test-type")); } @Test public void outputArchiveCustomizeArtifactId() { this.request.setOutput("my-project.zip"); - assertEquals(createDefaultUrl("?artifactId=my-project&type=test-type"), - this.request.generateUrl(createDefaultMetadata())); + assertThat(this.request.generateUrl(createDefaultMetadata())) + .isEqualTo(createDefaultUrl("?artifactId=my-project&type=test-type")); } @Test public void outputArchiveWithDotsCustomizeArtifactId() { this.request.setOutput("my.nice.project.zip"); - assertEquals(createDefaultUrl("?artifactId=my.nice.project&type=test-type"), - this.request.generateUrl(createDefaultMetadata())); + assertThat(this.request.generateUrl(createDefaultMetadata())).isEqualTo( + createDefaultUrl("?artifactId=my.nice.project&type=test-type")); } @Test public void outputDoesNotOverrideCustomArtifactId() { this.request.setOutput("my-project"); this.request.setArtifactId("my-id"); - assertEquals(createDefaultUrl("?artifactId=my-id&type=test-type"), - this.request.generateUrl(createDefaultMetadata())); + assertThat(this.request.generateUrl(createDefaultMetadata())) + .isEqualTo(createDefaultUrl("?artifactId=my-id&type=test-type")); } @Test @@ -195,8 +191,8 @@ public class ProjectGenerationRequestTests { public void buildOneMatch() { InitializrServiceMetadata metadata = readMetadata(); setBuildAndFormat("gradle", null); - assertEquals(createDefaultUrl("?type=gradle-project"), - this.request.generateUrl(metadata)); + assertThat(this.request.generateUrl(metadata)) + .isEqualTo(createDefaultUrl("?type=gradle-project")); } @Test @@ -204,8 +200,8 @@ public class ProjectGenerationRequestTests { InitializrServiceMetadata metadata = readMetadata(); setBuildAndFormat("gradle", "project"); this.request.setType("maven-build"); - assertEquals(createUrl("/pom.xml?type=maven-build"), - this.request.generateUrl(metadata)); + assertThat(this.request.generateUrl(metadata)) + .isEqualTo(createUrl("/pom.xml?type=maven-build")); } @Test diff --git a/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/init/ServiceCapabilitiesReportGeneratorTests.java b/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/init/ServiceCapabilitiesReportGeneratorTests.java index 9759e7484b..5758065ad2 100644 --- a/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/init/ServiceCapabilitiesReportGeneratorTests.java +++ b/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/init/ServiceCapabilitiesReportGeneratorTests.java @@ -20,9 +20,7 @@ import java.io.IOException; import org.junit.Test; -import static org.hamcrest.CoreMatchers.equalTo; -import static org.hamcrest.Matchers.containsString; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link ServiceCapabilitiesReportGenerator} @@ -40,7 +38,7 @@ public class ServiceCapabilitiesReportGeneratorTests extends AbstractHttpClientM String expected = new String( readClasspathResource("metadata/service-metadata-2.1.0.txt")); String content = this.command.generate("http://localhost"); - assertThat(content, equalTo(expected)); + assertThat(content).isEqualTo(expected); } @Test @@ -57,10 +55,10 @@ public class ServiceCapabilitiesReportGeneratorTests extends AbstractHttpClientM private void doTestGenerateCapabilitiesFromJson() throws IOException { String content = this.command.generate("http://localhost"); - assertThat(content, containsString("aop - AOP")); - assertThat(content, containsString("security - Security: Security description")); - assertThat(content, containsString("type: maven-project")); - assertThat(content, containsString("packaging: jar")); + assertThat(content).contains("aop - AOP"); + assertThat(content).contains("security - Security: Security description"); + assertThat(content).contains("type: maven-project"); + assertThat(content).contains("packaging: jar"); } } diff --git a/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/install/GroovyGrabDependencyResolverTests.java b/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/install/GroovyGrabDependencyResolverTests.java index 70dd379d4c..ae2d1d5845 100644 --- a/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/install/GroovyGrabDependencyResolverTests.java +++ b/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/install/GroovyGrabDependencyResolverTests.java @@ -23,6 +23,7 @@ import java.util.HashSet; import java.util.List; import java.util.Set; +import org.assertj.core.api.Condition; import org.junit.Before; import org.junit.Test; @@ -30,11 +31,11 @@ import org.springframework.boot.cli.compiler.GroovyCompilerConfiguration; import org.springframework.boot.cli.compiler.GroovyCompilerScope; import org.springframework.boot.cli.compiler.RepositoryConfigurationFactory; import org.springframework.boot.cli.compiler.grape.RepositoryConfiguration; +import org.springframework.boot.test.assertj.Matched; +import static org.assertj.core.api.Assertions.assertThat; import static org.hamcrest.Matchers.hasItems; -import static org.hamcrest.Matchers.hasSize; import static org.hamcrest.Matchers.startsWith; -import static org.junit.Assert.assertThat; /** * Tests for {@link GroovyGrabDependencyResolver}. @@ -88,35 +89,35 @@ public class GroovyGrabDependencyResolverTests { public void resolveArtifactWithNoDependencies() throws Exception { List resolved = this.resolver .resolve(Arrays.asList("commons-logging:commons-logging:1.1.3")); - assertThat(resolved, hasSize(1)); - assertThat(getNames(resolved), hasItems("commons-logging-1.1.3.jar")); + assertThat(resolved).hasSize(1); + assertThat(getNames(resolved)).containsOnly("commons-logging-1.1.3.jar"); } @Test public void resolveArtifactWithDependencies() throws Exception { List resolved = this.resolver .resolve(Arrays.asList("org.springframework:spring-core:4.1.1.RELEASE")); - assertThat(resolved, hasSize(2)); - assertThat(getNames(resolved), - hasItems("commons-logging-1.1.3.jar", "spring-core-4.1.1.RELEASE.jar")); + assertThat(resolved).hasSize(2); + assertThat(getNames(resolved)).containsOnly("commons-logging-1.1.3.jar", + "spring-core-4.1.1.RELEASE.jar"); } - @SuppressWarnings("unchecked") @Test + @SuppressWarnings({ "unchecked", "rawtypes" }) public void resolveShorthandArtifactWithDependencies() throws Exception { List resolved = this.resolver.resolve(Arrays.asList("spring-core")); - assertThat(resolved, hasSize(2)); - assertThat(getNames(resolved), - hasItems(startsWith("commons-logging-"), startsWith("spring-core-"))); + assertThat(resolved).hasSize(2); + assertThat(getNames(resolved)).has((Condition) Matched.by( + hasItems(startsWith("commons-logging-"), startsWith("spring-core-")))); } @Test public void resolveMultipleArtifacts() throws Exception { List resolved = this.resolver.resolve(Arrays.asList("junit:junit:4.11", "commons-logging:commons-logging:1.1.3")); - assertThat(resolved, hasSize(3)); - assertThat(getNames(resolved), hasItems("junit-4.11.jar", - "commons-logging-1.1.3.jar", "hamcrest-core-1.3.jar")); + assertThat(resolved).hasSize(3); + assertThat(getNames(resolved)).containsOnly("junit-4.11.jar", + "commons-logging-1.1.3.jar", "hamcrest-core-1.3.jar"); } public Set getNames(Collection files) { diff --git a/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/install/InstallerTests.java b/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/install/InstallerTests.java index 4fb433745f..1986c94367 100644 --- a/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/install/InstallerTests.java +++ b/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/install/InstallerTests.java @@ -30,9 +30,7 @@ import org.junit.rules.TemporaryFolder; import org.springframework.util.FileSystemUtils; -import static org.hamcrest.Matchers.contains; -import static org.hamcrest.Matchers.containsInAnyOrder; -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; @@ -68,7 +66,7 @@ public class InstallerTests { File foo = createTemporaryFile("foo.jar"); given(this.resolver.resolve(Arrays.asList("foo"))).willReturn(Arrays.asList(foo)); this.installer.install(Arrays.asList("foo")); - assertThat(getNamesOfFilesInLib(), containsInAnyOrder("foo.jar", ".installed")); + assertThat(getNamesOfFilesInLib()).containsOnly("foo.jar", ".installed"); } @Test @@ -77,7 +75,7 @@ public class InstallerTests { given(this.resolver.resolve(Arrays.asList("foo"))).willReturn(Arrays.asList(foo)); this.installer.install(Arrays.asList("foo")); this.installer.uninstall(Arrays.asList("foo")); - assertThat(getNamesOfFilesInLib(), contains(".installed")); + assertThat(getNamesOfFilesInLib()).contains(".installed"); } @Test @@ -89,21 +87,17 @@ public class InstallerTests { .willReturn(Arrays.asList(bravo, alpha)); given(this.resolver.resolve(Arrays.asList("charlie"))) .willReturn(Arrays.asList(charlie, alpha)); - this.installer.install(Arrays.asList("bravo")); - assertThat(getNamesOfFilesInLib(), - containsInAnyOrder("alpha.jar", "bravo.jar", ".installed")); - + assertThat(getNamesOfFilesInLib()).containsOnly("alpha.jar", "bravo.jar", + ".installed"); this.installer.install(Arrays.asList("charlie")); - assertThat(getNamesOfFilesInLib(), containsInAnyOrder("alpha.jar", "bravo.jar", - "charlie.jar", ".installed")); - + assertThat(getNamesOfFilesInLib()).containsOnly("alpha.jar", "bravo.jar", + "charlie.jar", ".installed"); this.installer.uninstall(Arrays.asList("bravo")); - assertThat(getNamesOfFilesInLib(), - containsInAnyOrder("alpha.jar", "charlie.jar", ".installed")); - + assertThat(getNamesOfFilesInLib()).containsOnly("alpha.jar", "charlie.jar", + ".installed"); this.installer.uninstall(Arrays.asList("charlie")); - assertThat(getNamesOfFilesInLib(), containsInAnyOrder(".installed")); + assertThat(getNamesOfFilesInLib()).containsOnly(".installed"); } @Test @@ -111,19 +105,16 @@ public class InstallerTests { File alpha = createTemporaryFile("alpha.jar"); File bravo = createTemporaryFile("bravo.jar"); File charlie = createTemporaryFile("charlie.jar"); - given(this.resolver.resolve(Arrays.asList("bravo"))) .willReturn(Arrays.asList(bravo, alpha)); given(this.resolver.resolve(Arrays.asList("charlie"))) .willReturn(Arrays.asList(charlie, alpha)); - this.installer.install(Arrays.asList("bravo")); this.installer.install(Arrays.asList("charlie")); - assertThat(getNamesOfFilesInLib(), containsInAnyOrder("alpha.jar", "bravo.jar", - "charlie.jar", ".installed")); - + assertThat(getNamesOfFilesInLib()).containsOnly("alpha.jar", "bravo.jar", + "charlie.jar", ".installed"); this.installer.uninstallAll(); - assertThat(getNamesOfFilesInLib(), containsInAnyOrder(".installed")); + assertThat(getNamesOfFilesInLib()).containsOnly(".installed"); } private Set getNamesOfFilesInLib() { diff --git a/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/shell/EscapeAwareWhiteSpaceArgumentDelimiterTests.java b/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/shell/EscapeAwareWhiteSpaceArgumentDelimiterTests.java index aa2ac5ceba..863c8721c7 100644 --- a/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/shell/EscapeAwareWhiteSpaceArgumentDelimiterTests.java +++ b/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/shell/EscapeAwareWhiteSpaceArgumentDelimiterTests.java @@ -19,8 +19,7 @@ package org.springframework.boot.cli.command.shell; import jline.console.completer.ArgumentCompleter.ArgumentList; 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 EscapeAwareWhiteSpaceArgumentDelimiter}. @@ -34,68 +33,63 @@ public class EscapeAwareWhiteSpaceArgumentDelimiterTests { @Test public void simple() throws Exception { String s = "one two"; - assertThat(this.delimiter.delimit(s, 0).getArguments(), - equalTo(new String[] { "one", "two" })); - assertThat(this.delimiter.parseArguments(s), - equalTo(new String[] { "one", "two" })); - assertThat(this.delimiter.isDelimiter(s, 2), equalTo(false)); - assertThat(this.delimiter.isDelimiter(s, 3), equalTo(true)); - assertThat(this.delimiter.isDelimiter(s, 4), equalTo(false)); + assertThat(this.delimiter.delimit(s, 0).getArguments()).containsExactly("one", + "two"); + assertThat(this.delimiter.parseArguments(s)).containsExactly("one", "two"); + assertThat(this.delimiter.isDelimiter(s, 2)).isFalse(); + assertThat(this.delimiter.isDelimiter(s, 3)).isTrue(); + assertThat(this.delimiter.isDelimiter(s, 4)).isFalse(); } @Test public void escaped() throws Exception { String s = "o\\ ne two"; - assertThat(this.delimiter.delimit(s, 0).getArguments(), - equalTo(new String[] { "o\\ ne", "two" })); - assertThat(this.delimiter.parseArguments(s), - equalTo(new String[] { "o ne", "two" })); - assertThat(this.delimiter.isDelimiter(s, 2), equalTo(false)); - assertThat(this.delimiter.isDelimiter(s, 3), equalTo(false)); - assertThat(this.delimiter.isDelimiter(s, 4), equalTo(false)); - assertThat(this.delimiter.isDelimiter(s, 5), equalTo(true)); + assertThat(this.delimiter.delimit(s, 0).getArguments()).containsExactly("o\\ ne", + "two"); + assertThat(this.delimiter.parseArguments(s)).containsExactly("o ne", "two"); + assertThat(this.delimiter.isDelimiter(s, 2)).isFalse(); + assertThat(this.delimiter.isDelimiter(s, 3)).isFalse(); + assertThat(this.delimiter.isDelimiter(s, 4)).isFalse(); + assertThat(this.delimiter.isDelimiter(s, 5)).isTrue(); } @Test public void quoted() throws Exception { String s = "'o ne' 't w o'"; - assertThat(this.delimiter.delimit(s, 0).getArguments(), - equalTo(new String[] { "'o ne'", "'t w o'" })); - assertThat(this.delimiter.parseArguments(s), - equalTo(new String[] { "o ne", "t w o" })); + assertThat(this.delimiter.delimit(s, 0).getArguments()).containsExactly("'o ne'", + "'t w o'"); + assertThat(this.delimiter.parseArguments(s)).containsExactly("o ne", "t w o"); } @Test public void doubleQuoted() throws Exception { String s = "\"o ne\" \"t w o\""; - assertThat(this.delimiter.delimit(s, 0).getArguments(), - equalTo(new String[] { "\"o ne\"", "\"t w o\"" })); - assertThat(this.delimiter.parseArguments(s), - equalTo(new String[] { "o ne", "t w o" })); + assertThat(this.delimiter.delimit(s, 0).getArguments()) + .containsExactly("\"o ne\"", "\"t w o\""); + assertThat(this.delimiter.parseArguments(s)).containsExactly("o ne", "t w o"); } @Test public void nestedQuotes() throws Exception { String s = "\"o 'n''e\" 't \"w o'"; - assertThat(this.delimiter.delimit(s, 0).getArguments(), - equalTo(new String[] { "\"o 'n''e\"", "'t \"w o'" })); - assertThat(this.delimiter.parseArguments(s), - equalTo(new String[] { "o 'n''e", "t \"w o" })); + assertThat(this.delimiter.delimit(s, 0).getArguments()) + .containsExactly("\"o 'n''e\"", "'t \"w o'"); + assertThat(this.delimiter.parseArguments(s)).containsExactly("o 'n''e", + "t \"w o"); } @Test public void escapedQuotes() throws Exception { String s = "\\'a b"; ArgumentList argumentList = this.delimiter.delimit(s, 0); - assertThat(argumentList.getArguments(), equalTo(new String[] { "\\'a", "b" })); - assertThat(this.delimiter.parseArguments(s), equalTo(new String[] { "'a", "b" })); + assertThat(argumentList.getArguments()).isEqualTo(new String[] { "\\'a", "b" }); + assertThat(this.delimiter.parseArguments(s)).containsExactly("'a", "b"); } @Test public void escapes() throws Exception { String s = "\\ \\\\.\\\\\\t"; - assertThat(this.delimiter.parseArguments(s), - equalTo(new String[] { " \\.\\\t" })); - + assertThat(this.delimiter.parseArguments(s)).containsExactly(" \\.\\\t"); } + } diff --git a/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/DependencyCustomizerTests.java b/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/DependencyCustomizerTests.java index 6112504047..8fd7bca91c 100644 --- a/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/DependencyCustomizerTests.java +++ b/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/DependencyCustomizerTests.java @@ -33,8 +33,7 @@ import org.mockito.MockitoAnnotations; import org.springframework.boot.cli.compiler.dependencies.ArtifactCoordinatesResolver; import org.springframework.boot.cli.compiler.grape.DependencyResolutionContext; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.BDDMockito.given; /** @@ -78,7 +77,7 @@ public class DependencyCustomizerTests { this.dependencyCustomizer.add("spring-boot-starter-logging"); List grabAnnotations = this.classNode .getAnnotations(new ClassNode(Grab.class)); - assertEquals(1, grabAnnotations.size()); + assertThat(grabAnnotations).hasSize(1); AnnotationNode annotationNode = grabAnnotations.get(0); assertGrabAnnotation(annotationNode, "org.springframework.boot", "spring-boot-starter-logging", "1.2.3", null, null, true); @@ -89,7 +88,7 @@ public class DependencyCustomizerTests { this.dependencyCustomizer.add("spring-boot-starter-logging", false); List grabAnnotations = this.classNode .getAnnotations(new ClassNode(Grab.class)); - assertEquals(1, grabAnnotations.size()); + assertThat(grabAnnotations).hasSize(1); AnnotationNode annotationNode = grabAnnotations.get(0); assertGrabAnnotation(annotationNode, "org.springframework.boot", "spring-boot-starter-logging", "1.2.3", null, null, false); @@ -101,7 +100,7 @@ public class DependencyCustomizerTests { "my-type", false); List grabAnnotations = this.classNode .getAnnotations(new ClassNode(Grab.class)); - assertEquals(1, grabAnnotations.size()); + assertThat(grabAnnotations).hasSize(1); AnnotationNode annotationNode = grabAnnotations.get(0); assertGrabAnnotation(annotationNode, "org.springframework.boot", "spring-boot-starter-logging", "1.2.3", "my-classifier", "my-type", @@ -112,7 +111,7 @@ public class DependencyCustomizerTests { public void anyMissingClassesWithMissingClassesPerformsAdd() { this.dependencyCustomizer.ifAnyMissingClasses("does.not.Exist") .add("spring-boot-starter-logging"); - assertEquals(1, this.classNode.getAnnotations(new ClassNode(Grab.class)).size()); + assertThat(this.classNode.getAnnotations(new ClassNode(Grab.class))).hasSize(1); } @Test @@ -120,21 +119,21 @@ public class DependencyCustomizerTests { this.dependencyCustomizer .ifAnyMissingClasses(getClass().getName(), "does.not.Exist") .add("spring-boot-starter-logging"); - assertEquals(1, this.classNode.getAnnotations(new ClassNode(Grab.class)).size()); + assertThat(this.classNode.getAnnotations(new ClassNode(Grab.class))).hasSize(1); } @Test public void anyMissingClassesWithNoMissingClassesDoesNotPerformAdd() { this.dependencyCustomizer.ifAnyMissingClasses(getClass().getName()) .add("spring-boot-starter-logging"); - assertEquals(0, this.classNode.getAnnotations(new ClassNode(Grab.class)).size()); + assertThat(this.classNode.getAnnotations(new ClassNode(Grab.class))).isEmpty(); } @Test public void allMissingClassesWithNoMissingClassesDoesNotPerformAdd() { this.dependencyCustomizer.ifAllMissingClasses(getClass().getName()) .add("spring-boot-starter-logging"); - assertEquals(0, this.classNode.getAnnotations(new ClassNode(Grab.class)).size()); + assertThat(this.classNode.getAnnotations(new ClassNode(Grab.class))).isEmpty(); } @Test @@ -142,7 +141,7 @@ public class DependencyCustomizerTests { this.dependencyCustomizer .ifAllMissingClasses(getClass().getName(), "does.not.Exist") .add("spring-boot-starter-logging"); - assertEquals(0, this.classNode.getAnnotations(new ClassNode(Grab.class)).size()); + assertThat(this.classNode.getAnnotations(new ClassNode(Grab.class))).isEmpty(); } @Test @@ -150,27 +149,28 @@ public class DependencyCustomizerTests { this.dependencyCustomizer .ifAllMissingClasses("does.not.Exist", "does.not.exist.Either") .add("spring-boot-starter-logging"); - assertEquals(1, this.classNode.getAnnotations(new ClassNode(Grab.class)).size()); + assertThat(this.classNode.getAnnotations(new ClassNode(Grab.class))).hasSize(1); } private void assertGrabAnnotation(AnnotationNode annotationNode, String group, String module, String version, String classifier, String type, boolean transitive) { - assertEquals(group, getMemberValue(annotationNode, "group")); - assertEquals(module, getMemberValue(annotationNode, "module")); + assertThat(getMemberValue(annotationNode, "group")).isEqualTo(group); + assertThat(getMemberValue(annotationNode, "module")).isEqualTo(module); if (type == null) { - assertNull(annotationNode.getMember("type")); + assertThat(annotationNode.getMember("type")).isNull(); } else { - assertEquals(type, getMemberValue(annotationNode, "type")); + assertThat(getMemberValue(annotationNode, "type")).isEqualTo(type); } if (classifier == null) { - assertNull(annotationNode.getMember("classifier")); + assertThat(annotationNode.getMember("classifier")).isNull(); } else { - assertEquals(classifier, getMemberValue(annotationNode, "classifier")); + assertThat(getMemberValue(annotationNode, "classifier")) + .isEqualTo(classifier); } - assertEquals(transitive, getMemberValue(annotationNode, "transitive")); + assertThat(getMemberValue(annotationNode, "transitive")).isEqualTo(transitive); } private Object getMemberValue(AnnotationNode annotationNode, String member) { diff --git a/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/ExtendedGroovyClassLoaderTests.java b/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/ExtendedGroovyClassLoaderTests.java index 1f9aef54d9..26efe82d0b 100644 --- a/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/ExtendedGroovyClassLoaderTests.java +++ b/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/ExtendedGroovyClassLoaderTests.java @@ -21,8 +21,7 @@ import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; -import static org.hamcrest.Matchers.sameInstance; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link ExtendedGroovyClassLoader}. @@ -49,7 +48,7 @@ public class ExtendedGroovyClassLoaderTests { public void loadsGroovyFromSameClassLoader() throws Exception { Class c1 = this.contextClassLoader.loadClass("groovy.lang.Script"); Class c2 = this.defaultScopeGroovyClassLoader.loadClass("groovy.lang.Script"); - assertThat(c1.getClassLoader(), sameInstance(c2.getClassLoader())); + assertThat(c1.getClassLoader()).isSameAs(c2.getClassLoader()); } @Test diff --git a/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/GenericBomAstTransformationTests.java b/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/GenericBomAstTransformationTests.java index a41e73f67f..ae705f34fa 100644 --- a/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/GenericBomAstTransformationTests.java +++ b/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/GenericBomAstTransformationTests.java @@ -35,7 +35,7 @@ import org.junit.Test; import org.springframework.boot.groovy.DependencyManagementBom; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link ResolveDependencyCoordinatesTransformation} @@ -68,14 +68,14 @@ public final class GenericBomAstTransformationTests { public void transformationOfEmptyPackage() { this.moduleNode.setPackage(new PackageNode("foo")); this.transformation.visit(new ASTNode[] { this.moduleNode }, this.sourceUnit); - assertEquals("[test:child:1.0.0]", getValue().toString()); + assertThat(getValue().toString()).isEqualTo("[test:child:1.0.0]"); } @Test public void transformationOfClass() { this.moduleNode.addClass(ClassHelper.make("MyClass")); this.transformation.visit(new ASTNode[] { this.moduleNode }, this.sourceUnit); - assertEquals("[test:child:1.0.0]", getValue().toString()); + assertThat(getValue().toString()).isEqualTo("[test:child:1.0.0]"); } @Test @@ -88,7 +88,8 @@ public final class GenericBomAstTransformationTests { annotation.addMember("value", new ConstantExpression("test:parent:1.0.0")); cls.addAnnotation(annotation); this.transformation.visit(new ASTNode[] { this.moduleNode }, this.sourceUnit); - assertEquals("[test:parent:1.0.0, test:child:1.0.0]", getValue().toString()); + assertThat(getValue().toString()) + .isEqualTo("[test:parent:1.0.0, test:child:1.0.0]"); } private List getValue() { diff --git a/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/RepositoryConfigurationFactoryTests.java b/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/RepositoryConfigurationFactoryTests.java index f640bf75e2..f8b570dc14 100644 --- a/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/RepositoryConfigurationFactoryTests.java +++ b/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/RepositoryConfigurationFactoryTests.java @@ -25,9 +25,7 @@ import org.junit.Test; import org.springframework.boot.cli.compiler.grape.RepositoryConfiguration; import org.springframework.boot.cli.util.SystemProperties; -import static org.hamcrest.Matchers.hasItems; -import static org.hamcrest.Matchers.hasSize; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link RepositoryConfigurationFactory} @@ -107,11 +105,12 @@ public class RepositoryConfigurationFactoryTests { private void assertRepositoryConfiguration( List configurations, String... expectedNames) { - assertThat(configurations, hasSize(expectedNames.length)); + assertThat(configurations).hasSize(expectedNames.length); Set actualNames = new HashSet(); for (RepositoryConfiguration configuration : configurations) { actualNames.add(configuration.getName()); } - assertThat(actualNames, hasItems(expectedNames)); + assertThat(actualNames).containsOnly(expectedNames); } + } diff --git a/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/ResolveDependencyCoordinatesTransformationTests.java b/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/ResolveDependencyCoordinatesTransformationTests.java index 1ff96d5bd3..883698188e 100644 --- a/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/ResolveDependencyCoordinatesTransformationTests.java +++ b/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/ResolveDependencyCoordinatesTransformationTests.java @@ -45,7 +45,7 @@ import org.junit.Test; import org.springframework.boot.cli.compiler.dependencies.ArtifactCoordinatesResolver; import org.springframework.boot.cli.compiler.grape.DependencyResolutionContext; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; @@ -220,9 +220,9 @@ public final class ResolveDependencyCoordinatesTransformationTests { private void assertGrabAnnotationHasBeenTransformed() { this.transformation.visit(new ASTNode[] { this.moduleNode }, this.sourceUnit); - - assertEquals("org.springframework", getGrabAnnotationMemberAsString("group")); - assertEquals("spring-core", getGrabAnnotationMemberAsString("module")); + assertThat(getGrabAnnotationMemberAsString("group")) + .isEqualTo("org.springframework"); + assertThat(getGrabAnnotationMemberAsString("module")).isEqualTo("spring-core"); } private Object getGrabAnnotationMemberAsString(String memberName) { diff --git a/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/dependencies/CompositeDependencyManagementTests.java b/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/dependencies/CompositeDependencyManagementTests.java index 6b14c89e19..f1f7ece863 100644 --- a/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/dependencies/CompositeDependencyManagementTests.java +++ b/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/dependencies/CompositeDependencyManagementTests.java @@ -23,10 +23,7 @@ import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; -import static org.hamcrest.Matchers.contains; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.nullValue; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.BDDMockito.given; /** @@ -47,10 +44,8 @@ public class CompositeDependencyManagementTests { public void unknownSpringBootVersion() { given(this.dependencyManagement1.getSpringBootVersion()).willReturn(null); given(this.dependencyManagement2.getSpringBootVersion()).willReturn(null); - assertThat( - new CompositeDependencyManagement(this.dependencyManagement1, - this.dependencyManagement2).getSpringBootVersion(), - is(nullValue())); + assertThat(new CompositeDependencyManagement(this.dependencyManagement1, + this.dependencyManagement2).getSpringBootVersion()).isNull(); } @Test @@ -58,7 +53,7 @@ public class CompositeDependencyManagementTests { given(this.dependencyManagement1.getSpringBootVersion()).willReturn("1.2.3"); given(this.dependencyManagement2.getSpringBootVersion()).willReturn("1.2.4"); assertThat(new CompositeDependencyManagement(this.dependencyManagement1, - this.dependencyManagement2).getSpringBootVersion(), is("1.2.3")); + this.dependencyManagement2).getSpringBootVersion()).isEqualTo("1.2.3"); } @Test @@ -66,7 +61,7 @@ public class CompositeDependencyManagementTests { given(this.dependencyManagement1.find("artifact")).willReturn(null); given(this.dependencyManagement2.find("artifact")).willReturn(null); assertThat(new CompositeDependencyManagement(this.dependencyManagement1, - this.dependencyManagement2).find("artifact"), is(nullValue())); + this.dependencyManagement2).find("artifact")).isNull(); } @Test @@ -75,10 +70,9 @@ public class CompositeDependencyManagementTests { .willReturn(new Dependency("test", "artifact", "1.2.3")); given(this.dependencyManagement2.find("artifact")) .willReturn(new Dependency("test", "artifact", "1.2.4")); - assertThat( - new CompositeDependencyManagement(this.dependencyManagement1, - this.dependencyManagement2).find("artifact"), - is(new Dependency("test", "artifact", "1.2.3"))); + assertThat(new CompositeDependencyManagement(this.dependencyManagement1, + this.dependencyManagement2).find("artifact")) + .isEqualTo(new Dependency("test", "artifact", "1.2.3")); } @Test @@ -87,11 +81,10 @@ public class CompositeDependencyManagementTests { .willReturn(Arrays.asList(new Dependency("test", "artifact", "1.2.3"))); given(this.dependencyManagement2.getDependencies()) .willReturn(Arrays.asList(new Dependency("test", "artifact", "1.2.4"))); - assertThat( - new CompositeDependencyManagement(this.dependencyManagement1, - this.dependencyManagement2).getDependencies(), - contains(new Dependency("test", "artifact", "1.2.3"), - new Dependency("test", "artifact", "1.2.4"))); + assertThat(new CompositeDependencyManagement(this.dependencyManagement1, + this.dependencyManagement2).getDependencies()).containsOnly( + new Dependency("test", "artifact", "1.2.3"), + new Dependency("test", "artifact", "1.2.4")); } } diff --git a/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/dependencies/DependencyManagementArtifactCoordinatesResolverTests.java b/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/dependencies/DependencyManagementArtifactCoordinatesResolverTests.java index 689969b2ad..54fe86a5b5 100644 --- a/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/dependencies/DependencyManagementArtifactCoordinatesResolverTests.java +++ b/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/dependencies/DependencyManagementArtifactCoordinatesResolverTests.java @@ -19,9 +19,7 @@ package org.springframework.boot.cli.compiler.dependencies; import org.junit.Before; import org.junit.Test; -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; import static org.mockito.BDDMockito.given; import static org.mockito.Matchers.anyString; import static org.mockito.Mockito.mock; @@ -52,19 +50,19 @@ public class DependencyManagementArtifactCoordinatesResolverTests { @Test public void getGroupIdForBootArtifact() throws Exception { - assertThat(this.resolver.getGroupId("spring-boot-something"), - equalTo("org.springframework.boot")); + assertThat(this.resolver.getGroupId("spring-boot-something")) + .isEqualTo("org.springframework.boot"); verify(this.dependencyManagement, never()).find(anyString()); } @Test public void getGroupIdFound() throws Exception { - assertThat(this.resolver.getGroupId("a1"), equalTo("g1")); + assertThat(this.resolver.getGroupId("a1")).isEqualTo("g1"); } @Test public void getGroupIdNotFound() throws Exception { - assertThat(this.resolver.getGroupId("a2"), nullValue()); + assertThat(this.resolver.getGroupId("a2")).isNull(); } } diff --git a/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/dependencies/SpringBootDependenciesDependencyManagementTests.java b/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/dependencies/SpringBootDependenciesDependencyManagementTests.java index ccd5a906f2..455b2289c5 100644 --- a/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/dependencies/SpringBootDependenciesDependencyManagementTests.java +++ b/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/dependencies/SpringBootDependenciesDependencyManagementTests.java @@ -18,12 +18,8 @@ package org.springframework.boot.cli.compiler.dependencies; import org.junit.Test; +import static org.assertj.core.api.Assertions.assertThat; import static org.hamcrest.Matchers.empty; -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.junit.Assert.assertThat; /** * Tests for {@link SpringBootDependenciesDependencyManagement} @@ -36,20 +32,20 @@ public class SpringBootDependenciesDependencyManagementTests { @Test public void springBootVersion() { - assertThat(this.dependencyManagement.getSpringBootVersion(), is(notNullValue())); + assertThat(this.dependencyManagement.getSpringBootVersion()).isNotNull(); } @Test public void find() { Dependency dependency = this.dependencyManagement.find("spring-boot"); - assertThat(dependency, is(notNullValue())); - assertThat(dependency.getGroupId(), is(equalTo("org.springframework.boot"))); - assertThat(dependency.getArtifactId(), is(equalTo("spring-boot"))); + assertThat(dependency).isNotNull(); + assertThat(dependency.getGroupId()).isEqualTo("org.springframework.boot"); + assertThat(dependency.getArtifactId()).isEqualTo("spring-boot"); } @Test public void getDependencies() { - assertThat(this.dependencyManagement.getDependencies(), is(not(empty()))); + assertThat(this.dependencyManagement.getDependencies()).isNotEqualTo(empty()); } } diff --git a/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/grape/AetherGrapeEngineTests.java b/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/grape/AetherGrapeEngineTests.java index 5400d2b70d..0362fe3a00 100644 --- a/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/grape/AetherGrapeEngineTests.java +++ b/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/grape/AetherGrapeEngineTests.java @@ -34,9 +34,7 @@ import org.junit.Test; import org.springframework.test.util.ReflectionTestUtils; -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; /** * Tests for {@link AetherGrapeEngine}. @@ -63,11 +61,9 @@ public class AetherGrapeEngineTests { @Test public void dependencyResolution() { Map args = new HashMap(); - createGrapeEngine(this.springMilestones).grab(args, createDependency("org.springframework", "spring-jdbc", "3.2.4.RELEASE")); - - assertEquals(5, this.groovyClassLoader.getURLs().length); + assertThat(this.groovyClassLoader.getURLs()).hasSize(5); } @Test @@ -81,8 +77,10 @@ public class AetherGrapeEngineTests { DefaultRepositorySystemSession session = (DefaultRepositorySystemSession) ReflectionTestUtils .getField(grapeEngine, "session"); - assertTrue(session.getProxySelector() instanceof CompositeProxySelector); + assertThat(session.getProxySelector() instanceof CompositeProxySelector) + .isTrue(); } + }); } @@ -97,8 +95,8 @@ public class AetherGrapeEngineTests { List repositories = (List) ReflectionTestUtils .getField(grapeEngine, "repositories"); - assertEquals(1, repositories.size()); - assertEquals("central-mirror", repositories.get(0).getId()); + assertThat(repositories).hasSize(1); + assertThat(repositories.get(0).getId()).isEqualTo("central-mirror"); } }); } @@ -114,9 +112,9 @@ public class AetherGrapeEngineTests { List repositories = (List) ReflectionTestUtils .getField(grapeEngine, "repositories"); - assertEquals(1, repositories.size()); + assertThat(repositories).hasSize(1); Authentication authentication = repositories.get(0).getAuthentication(); - assertNotNull(authentication); + assertThat(authentication).isNotNull(); } }); } @@ -131,7 +129,7 @@ public class AetherGrapeEngineTests { createDependency("org.springframework", "spring-jdbc", "3.2.4.RELEASE"), createDependency("org.springframework", "spring-beans", "3.2.4.RELEASE")); - assertEquals(3, this.groovyClassLoader.getURLs().length); + assertThat(this.groovyClassLoader.getURLs().length).isEqualTo(3); } @Test @@ -141,7 +139,7 @@ public class AetherGrapeEngineTests { createGrapeEngine().grab(args, createDependency("org.springframework", "spring-jdbc", "3.2.4.RELEASE", false)); - assertEquals(1, this.groovyClassLoader.getURLs().length); + assertThat(this.groovyClassLoader.getURLs().length).isEqualTo(1); } @Test @@ -153,8 +151,8 @@ public class AetherGrapeEngineTests { createGrapeEngine(this.springMilestones).grab(args, createDependency("org.springframework", "spring-jdbc", "3.2.4.RELEASE")); - assertEquals(0, this.groovyClassLoader.getURLs().length); - assertEquals(5, customClassLoader.getURLs().length); + assertThat(this.groovyClassLoader.getURLs().length).isEqualTo(0); + assertThat(customClassLoader.getURLs().length).isEqualTo(5); } @Test @@ -164,7 +162,7 @@ public class AetherGrapeEngineTests { grapeEngine .addResolver(createResolver("restlet.org", "http://maven.restlet.org")); grapeEngine.grab(args, createDependency("org.restlet", "org.restlet", "1.1.6")); - assertEquals(1, this.groovyClassLoader.getURLs().length); + assertThat(this.groovyClassLoader.getURLs().length).isEqualTo(1); } @Test(expected = IllegalArgumentException.class) @@ -184,8 +182,8 @@ public class AetherGrapeEngineTests { dependency.put("type", "pom"); createGrapeEngine().grab(args, dependency); URL[] urls = this.groovyClassLoader.getURLs(); - assertEquals(1, urls.length); - assertTrue(urls[0].toExternalForm().endsWith(".pom")); + assertThat(urls.length).isEqualTo(1); + assertThat(urls[0].toExternalForm().endsWith(".pom")).isTrue(); } @Test @@ -196,8 +194,8 @@ public class AetherGrapeEngineTests { dependency.put("ext", "pom"); createGrapeEngine().grab(args, dependency); URL[] urls = this.groovyClassLoader.getURLs(); - assertEquals(1, urls.length); - assertTrue(urls[0].toExternalForm().endsWith(".pom")); + assertThat(urls.length).isEqualTo(1); + assertThat(urls[0].toExternalForm().endsWith(".pom")).isTrue(); } @Test @@ -210,8 +208,8 @@ public class AetherGrapeEngineTests { createGrapeEngine().grab(args, dependency); URL[] urls = this.groovyClassLoader.getURLs(); - assertEquals(1, urls.length); - assertTrue(urls[0].toExternalForm().endsWith("-sources.jar")); + assertThat(urls.length).isEqualTo(1); + assertThat(urls[0].toExternalForm().endsWith("-sources.jar")).isTrue(); } private Map createDependency(String group, String module, diff --git a/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/grape/DetailedProgressReporterTests.java b/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/grape/DetailedProgressReporterTests.java index 2229a6223f..aa1a223c35 100644 --- a/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/grape/DetailedProgressReporterTests.java +++ b/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/grape/DetailedProgressReporterTests.java @@ -26,11 +26,7 @@ import org.eclipse.aether.transfer.TransferResource; import org.junit.Before; import org.junit.Test; -import static org.hamcrest.Matchers.containsString; -import static org.hamcrest.Matchers.endsWith; -import static org.hamcrest.Matchers.startsWith; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link DetailedProgressReporter}. @@ -62,9 +58,8 @@ public final class DetailedProgressReporterTests { TransferEvent startedEvent = new TransferEvent.Builder(this.session, this.resource).build(); this.session.getTransferListener().transferStarted(startedEvent); - - assertEquals(String.format("Downloading: %s%s%n", REPOSITORY, ARTIFACT), - new String(this.baos.toByteArray())); + assertThat(new String(this.baos.toByteArray())) + .isEqualTo(String.format("Downloading: %s%s%n", REPOSITORY, ARTIFACT)); } @Test @@ -75,9 +70,10 @@ public final class DetailedProgressReporterTests { this.resource).addTransferredBytes(4096).build(); this.session.getTransferListener().transferSucceeded(completedEvent); String message = new String(this.baos.toByteArray()).replace("\\", "/"); - assertThat(message, startsWith("Downloaded: " + REPOSITORY + ARTIFACT)); - assertThat(message, containsString("4KB at")); - assertThat(message, containsString("KB/sec")); - assertThat(message, endsWith("\n")); + assertThat(message).startsWith("Downloaded: " + REPOSITORY + ARTIFACT); + assertThat(message).contains("4KB at"); + assertThat(message).contains("KB/sec"); + assertThat(message).endsWith("\n"); } + } diff --git a/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/grape/GrapeRootRepositorySystemSessionAutoConfigurationTests.java b/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/grape/GrapeRootRepositorySystemSessionAutoConfigurationTests.java index d551265f6e..2e34bfd327 100644 --- a/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/grape/GrapeRootRepositorySystemSessionAutoConfigurationTests.java +++ b/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/grape/GrapeRootRepositorySystemSessionAutoConfigurationTests.java @@ -31,11 +31,7 @@ import org.mockito.invocation.InvocationOnMock; import org.mockito.runners.MockitoJUnitRunner; import org.mockito.stubbing.Answer; -import static org.hamcrest.Matchers.endsWith; -import static org.hamcrest.Matchers.is; -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; import static org.mockito.BDDMockito.given; import static org.mockito.Matchers.any; import static org.mockito.Matchers.eq; @@ -72,15 +68,13 @@ public class GrapeRootRepositorySystemSessionAutoConfigurationTests { GrapeRootRepositorySystemSessionAutoConfigurationTests.this.session, localRepository); } - }); + }); new GrapeRootRepositorySystemSessionAutoConfiguration().apply(this.session, this.repositorySystem); - verify(this.repositorySystem, times(0)) .newLocalRepositoryManager(eq(this.session), any(LocalRepository.class)); - - assertThat(this.session.getLocalRepository(), is(nullValue())); + assertThat(this.session.getLocalRepository()).isNull(); } @Test @@ -101,9 +95,9 @@ public class GrapeRootRepositorySystemSessionAutoConfigurationTests { verify(this.repositorySystem, times(1)) .newLocalRepositoryManager(eq(this.session), any(LocalRepository.class)); - assertThat(this.session.getLocalRepository(), is(notNullValue())); - assertThat(this.session.getLocalRepository().getBasedir().getAbsolutePath(), - endsWith(File.separatorChar + "foo" + File.separatorChar + "repository")); + assertThat(this.session.getLocalRepository()).isNotNull(); + assertThat(this.session.getLocalRepository().getBasedir().getAbsolutePath()) + .endsWith(File.separatorChar + "foo" + File.separatorChar + "repository"); } private class LocalRepositoryManagerAnswer implements Answer { diff --git a/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/grape/SettingsXmlRepositorySystemSessionAutoConfigurationTests.java b/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/grape/SettingsXmlRepositorySystemSessionAutoConfigurationTests.java index a371392ea3..91bced894f 100644 --- a/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/grape/SettingsXmlRepositorySystemSessionAutoConfigurationTests.java +++ b/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/grape/SettingsXmlRepositorySystemSessionAutoConfigurationTests.java @@ -40,10 +40,7 @@ import org.mockito.stubbing.Answer; import org.springframework.boot.cli.util.SystemProperties; -import static org.hamcrest.Matchers.endsWith; -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; import static org.mockito.BDDMockito.given; import static org.mockito.Matchers.any; import static org.mockito.Matchers.eq; @@ -99,14 +96,13 @@ public class SettingsXmlRepositorySystemSessionAutoConfigurationTests { }, "user.home:src/test/resources/maven-settings/property-interpolation", "foo:bar"); - assertThat(session.getLocalRepository().getBasedir().getAbsolutePath(), - endsWith(File.separatorChar + "bar" + File.separatorChar + "repository")); + assertThat(session.getLocalRepository().getBasedir().getAbsolutePath()) + .endsWith(File.separatorChar + "bar" + File.separatorChar + "repository"); } private void assertSessionCustomization(String userHome) { final DefaultRepositorySystemSession session = MavenRepositorySystemUtils .newSession(); - SystemProperties.doWithSystemProperties(new Runnable() { @Override public void run() { @@ -117,7 +113,6 @@ public class SettingsXmlRepositorySystemSessionAutoConfigurationTests { RemoteRepository repository = new RemoteRepository.Builder("my-server", "default", "http://maven.example.com").build(); - assertMirrorSelectorConfiguration(session, repository); assertProxySelectorConfiguration(session, repository); assertAuthenticationSelectorConfiguration(session, repository); @@ -129,34 +124,33 @@ public class SettingsXmlRepositorySystemSessionAutoConfigurationTests { repository = new RemoteRepository.Builder(repository).setProxy(proxy).build(); AuthenticationContext authenticationContext = AuthenticationContext .forProxy(session, repository); - assertEquals("proxy.example.com", proxy.getHost()); - assertEquals("proxyuser", - authenticationContext.get(AuthenticationContext.USERNAME)); - assertEquals("somepassword", - authenticationContext.get(AuthenticationContext.PASSWORD)); + assertThat(proxy.getHost()).isEqualTo("proxy.example.com"); + assertThat(authenticationContext.get(AuthenticationContext.USERNAME)) + .isEqualTo("proxyuser"); + assertThat(authenticationContext.get(AuthenticationContext.PASSWORD)) + .isEqualTo("somepassword"); } private void assertMirrorSelectorConfiguration(DefaultRepositorySystemSession session, RemoteRepository repository) { RemoteRepository mirror = session.getMirrorSelector().getMirror(repository); - assertNotNull("No mirror configured for repository " + repository.getId(), - mirror); - assertEquals("maven.example.com", mirror.getHost()); + assertThat(mirror).as("Mirror configured for repository " + repository.getId()) + .isNotNull(); + assertThat(mirror.getHost()).isEqualTo("maven.example.com"); } private void assertAuthenticationSelectorConfiguration( DefaultRepositorySystemSession session, RemoteRepository repository) { Authentication authentication = session.getAuthenticationSelector() .getAuthentication(repository); - repository = new RemoteRepository.Builder(repository) .setAuthentication(authentication).build(); - AuthenticationContext authenticationContext = AuthenticationContext .forRepository(session, repository); - - assertEquals("tester", authenticationContext.get(AuthenticationContext.USERNAME)); - assertEquals("secret", authenticationContext.get(AuthenticationContext.PASSWORD)); + assertThat(authenticationContext.get(AuthenticationContext.USERNAME)) + .isEqualTo("tester"); + assertThat(authenticationContext.get(AuthenticationContext.PASSWORD)) + .isEqualTo("secret"); } } diff --git a/spring-boot-cli/src/test/java/org/springframework/boot/cli/util/ResourceUtilsTests.java b/spring-boot-cli/src/test/java/org/springframework/boot/cli/util/ResourceUtilsTests.java index b5fb9608f5..f7c79ba20a 100644 --- a/spring-boot-cli/src/test/java/org/springframework/boot/cli/util/ResourceUtilsTests.java +++ b/spring-boot-cli/src/test/java/org/springframework/boot/cli/util/ResourceUtilsTests.java @@ -25,8 +25,7 @@ import org.junit.Test; import org.springframework.util.ClassUtils; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link ResourceUtils}. @@ -39,8 +38,8 @@ public class ResourceUtilsTests { public void explicitClasspathResource() { List urls = ResourceUtils.getUrls("classpath:init.groovy", ClassUtils.getDefaultClassLoader()); - assertEquals(1, urls.size()); - assertTrue(urls.get(0).startsWith("file:")); + assertThat(urls).hasSize(1); + assertThat(urls.get(0).startsWith("file:")).isTrue(); } @Test @@ -49,68 +48,68 @@ public class ResourceUtilsTests { new URL("file:./src/test/resources/"), new File("src/test/resources/").getAbsoluteFile().toURI().toURL() }); List urls = ResourceUtils.getUrls("classpath:init.groovy", loader); - assertEquals(1, urls.size()); - assertTrue(urls.get(0).startsWith("file:")); + assertThat(urls).hasSize(1); + assertThat(urls.get(0).startsWith("file:")).isTrue(); } @Test public void explicitClasspathResourceWithSlash() { List urls = ResourceUtils.getUrls("classpath:/init.groovy", ClassUtils.getDefaultClassLoader()); - assertEquals(1, urls.size()); - assertTrue(urls.get(0).startsWith("file:")); + assertThat(urls).hasSize(1); + assertThat(urls.get(0).startsWith("file:")).isTrue(); } @Test public void implicitClasspathResource() { List urls = ResourceUtils.getUrls("init.groovy", ClassUtils.getDefaultClassLoader()); - assertEquals(1, urls.size()); - assertTrue(urls.get(0).startsWith("file:")); + assertThat(urls).hasSize(1); + assertThat(urls.get(0).startsWith("file:")).isTrue(); } @Test public void implicitClasspathResourceWithSlash() { List urls = ResourceUtils.getUrls("/init.groovy", ClassUtils.getDefaultClassLoader()); - assertEquals(1, urls.size()); - assertTrue(urls.get(0).startsWith("file:")); + assertThat(urls).hasSize(1); + assertThat(urls.get(0).startsWith("file:")).isTrue(); } @Test public void nonexistentClasspathResource() { List urls = ResourceUtils.getUrls("classpath:nonexistent.groovy", null); - assertEquals(0, urls.size()); + assertThat(urls).isEmpty(); } @Test public void explicitFile() { List urls = ResourceUtils.getUrls("file:src/test/resources/init.groovy", ClassUtils.getDefaultClassLoader()); - assertEquals(1, urls.size()); - assertTrue(urls.get(0).startsWith("file:")); + assertThat(urls).hasSize(1); + assertThat(urls.get(0).startsWith("file:")).isTrue(); } @Test public void implicitFile() { List urls = ResourceUtils.getUrls("src/test/resources/init.groovy", ClassUtils.getDefaultClassLoader()); - assertEquals(1, urls.size()); - assertTrue(urls.get(0).startsWith("file:")); + assertThat(urls).hasSize(1); + assertThat(urls.get(0).startsWith("file:")).isTrue(); } @Test public void nonexistentFile() { List urls = ResourceUtils.getUrls("file:nonexistent.groovy", null); - assertEquals(0, urls.size()); + assertThat(urls).isEmpty(); } @Test public void recursiveFiles() { List urls = ResourceUtils.getUrls("src/test/resources/dir-sample", ClassUtils.getDefaultClassLoader()); - assertEquals(1, urls.size()); - assertTrue(urls.get(0).startsWith("file:")); + assertThat(urls).hasSize(1); + assertThat(urls.get(0).startsWith("file:")).isTrue(); } @Test @@ -118,8 +117,8 @@ public class ResourceUtilsTests { List urls = ResourceUtils.getUrls( "file:src/test/resources/dir-sample/**/*.groovy", ClassUtils.getDefaultClassLoader()); - assertEquals(1, urls.size()); - assertTrue(urls.get(0).startsWith("file:")); + assertThat(urls).hasSize(1); + assertThat(urls.get(0).startsWith("file:")).isTrue(); } @Test @@ -127,8 +126,8 @@ public class ResourceUtilsTests { List urls = ResourceUtils.getUrls( "src/test/resources/dir-sample/**/*.groovy", ClassUtils.getDefaultClassLoader()); - assertEquals(1, urls.size()); - assertTrue(urls.get(0).startsWith("file:")); + assertThat(urls).hasSize(1); + assertThat(urls.get(0).startsWith("file:")).isTrue(); } @Test @@ -136,16 +135,16 @@ public class ResourceUtilsTests { List urls = ResourceUtils.getUrls( "file:src/test/resources/dir-sample/code/*", ClassUtils.getDefaultClassLoader()); - assertEquals(1, urls.size()); - assertTrue(urls.get(0).startsWith("file:")); + assertThat(urls).hasSize(1); + assertThat(urls.get(0).startsWith("file:")).isTrue(); } @Test public void directoryOfFiles() { List urls = ResourceUtils.getUrls("src/test/resources/dir-sample/code/*", ClassUtils.getDefaultClassLoader()); - assertEquals(1, urls.size()); - assertTrue(urls.get(0).startsWith("file:")); + assertThat(urls).hasSize(1); + assertThat(urls.get(0).startsWith("file:")).isTrue(); } } From 1cc1fc643118618caa47aeb03d849497ccda9f6e Mon Sep 17 00:00:00 2001 From: Phillip Webb Date: Sat, 6 Feb 2016 14:53:10 -0800 Subject: [PATCH 07/10] Use AssertJ in spring-boot-samples See gh-5083 --- .../sample/activemq/SampleActiveMqTests.java | 4 +- .../SampleActuatorApplicationTests.java | 6 +- .../SampleActuatorNoWebApplicationTests.java | 4 +- .../SampleActuatorUiApplicationPortTests.java | 10 +-- .../ui/SampleActuatorUiApplicationTests.java | 24 ++--- ...pertiesSampleActuatorApplicationTests.java | 18 ++-- ...AndPathSampleActuatorApplicationTests.java | 19 ++-- ...agementSampleActuatorApplicationTests.java | 16 ++-- ...nsecureSampleActuatorApplicationTests.java | 10 +-- ...gementAddressActuatorApplicationTests.java | 10 +-- ...entPathSampleActuatorApplicationTests.java | 16 ++-- ...AndPathSampleActuatorApplicationTests.java | 28 +++--- ...entPortSampleActuatorApplicationTests.java | 18 ++-- ...agementSampleActuatorApplicationTests.java | 8 +- .../actuator/NonSensitiveHealthTests.java | 8 +- .../SampleActuatorApplicationTests.java | 87 ++++++++---------- ...nsecureSampleActuatorApplicationTests.java | 12 ++- ...letPathSampleActuatorApplicationTests.java | 22 ++--- ...hutdownSampleActuatorApplicationTests.java | 12 ++- .../sample/ant/SampleAntApplicationIT.java | 10 +-- .../sample/aop/SampleAopApplicationTests.java | 6 +- .../SampleAtmosphereApplicationTests.java | 10 +-- .../batch/SampleBatchApplicationTests.java | 10 +-- .../cache/SampleCacheApplicationTests.java | 11 +-- .../SampleCassandraApplicationTests.java | 5 +- .../SampleElasticsearchApplicationTests.java | 5 +- .../SampleDataGemFireApplicationTests.java | 89 ++++++++----------- .../jpa/SampleDataJpaApplicationTests.java | 8 +- .../CityRepositoryIntegrationTests.java | 6 +- .../HotelRepositoryIntegrationTests.java | 15 ++-- .../mongo/SampleMongoApplicationTests.java | 5 +- .../redis/SampleRedisApplicationTests.java | 5 +- .../CityRepositoryIntegrationTests.java | 14 ++- .../data/solr/SampleSolrApplicationTests.java | 4 +- .../flyway/SampleFlywayApplicationTests.java | 6 +- .../SampleHateoasApplicationTests.java | 19 ++-- ...ermediaJpaApplicationIntegrationTests.java | 6 +- .../SampleHypermediaUiApplicationTests.java | 10 +-- ...pleHypermediaApplicationHomePageTests.java | 8 +- .../SampleIntegrationApplicationTests.java | 4 +- .../jersey/SampleJerseyApplicationTests.java | 10 +-- .../SampleJersey1ApplicationTests.java | 7 +- .../ssl/SampleJettySslApplicationTests.java | 6 +- .../jetty/SampleJettyApplicationTests.java | 12 +-- .../ssl/SampleJetty8SslApplicationTests.java | 6 +- .../jetty8/SampleJetty8ApplicationTests.java | 12 +-- .../SampleJetty93ApplicationTests.java | 12 +-- .../jooq/SampleJooqApplicationTests.java | 13 ++- .../JpaNoteRepositoryIntegrationTests.java | 4 +- .../JpaTagRepositoryIntegrationTests.java | 4 +- .../SampleAtomikosApplicationTests.java | 30 +++---- .../SampleBitronixApplicationTests.java | 41 ++++----- .../SampleLiquibaseApplicationTests.java | 21 +++-- ...mpleDropwizardMetricsApplicationTests.java | 4 +- .../SampleProfileApplicationTests.java | 10 +-- ...plePropertyValidationApplicationTests.java | 10 +-- .../SampleSecureOAuth2ApplicationTests.java | 13 ++- .../secure/SampleSecureApplicationTests.java | 10 +-- .../SampleServletApplicationTests.java | 8 +- .../SampleSessionRedisApplicationTests.java | 9 +- .../simple/SampleSimpleApplicationTests.java | 6 +- ...pringTestSampleSimpleApplicationTests.java | 9 +- .../spring-boot-sample-testng/pom.xml | 4 + .../testng/SampleTestNGApplicationTests.java | 6 +- .../jsp/SampleWebJspApplicationTests.java | 8 +- ...leTomcatTwoConnectorsApplicationTests.java | 10 +-- .../SampleTomcatSslApplicationTests.java | 8 +- ...igurationSampleTomcatApplicationTests.java | 8 +- .../tomcat/SampleTomcatApplicationTests.java | 12 +-- .../jsp/SampleWebJspApplicationTests.java | 8 +- .../SampleTraditionalApplicationTests.java | 13 ++- .../SampleUndertowSslApplicationTests.java | 6 +- .../SampleUndertowApplicationTests.java | 12 +-- .../SampleVelocityApplicationTests.java | 4 +- .../SampleWebFreeMarkerApplicationTests.java | 18 ++-- .../SampleGroovyTemplateApplicationTests.java | 19 ++-- .../jsp/SampleWebJspApplicationTests.java | 8 +- .../SampleMethodSecurityApplicationTests.java | 27 +++--- .../SampleWebMustacheApplicationTests.java | 14 ++- ...SampleWebSecureCustomApplicationTests.java | 38 ++++---- .../github/SampleGithubApplicationTests.java | 17 ++-- ...SampleWebSecureCustomApplicationTests.java | 36 ++++---- .../secure/SampleSecureApplicationTests.java | 36 ++++---- .../SampleWebStaticApplicationTests.java | 19 ++-- .../ui/SampleWebUiApplicationTests.java | 21 ++--- .../SampleWebVelocityApplicationTests.java | 14 ++- .../SampleWebSocketsApplicationTests.java | 13 +-- ...omContainerWebSocketsApplicationTests.java | 13 +-- .../jetty/snake/SnakeTimerTests.java | 5 +- .../SampleWebSocketsApplicationTests.java | 13 +-- ...omContainerWebSocketsApplicationTests.java | 13 +-- .../tomcat/snake/SnakeTimerTests.java | 5 +- .../SampleWebSocketsApplicationTests.java | 13 +-- ...omContainerWebSocketsApplicationTests.java | 13 +-- .../undertow/snake/SnakeTimerTests.java | 5 +- .../sample/ws/SampleWsApplicationTests.java | 5 +- .../xml/SampleSpringXmlApplicationTests.java | 4 +- 97 files changed, 580 insertions(+), 733 deletions(-) diff --git a/spring-boot-samples/spring-boot-sample-activemq/src/test/java/sample/activemq/SampleActiveMqTests.java b/spring-boot-samples/spring-boot-sample-activemq/src/test/java/sample/activemq/SampleActiveMqTests.java index b96cfe6115..a89ac1aaaa 100644 --- a/spring-boot-samples/spring-boot-sample-activemq/src/test/java/sample/activemq/SampleActiveMqTests.java +++ b/spring-boot-samples/spring-boot-sample-activemq/src/test/java/sample/activemq/SampleActiveMqTests.java @@ -27,7 +27,7 @@ import org.springframework.boot.test.OutputCapture; import org.springframework.boot.test.SpringApplicationConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * Integration tests for demo application. @@ -48,7 +48,7 @@ public class SampleActiveMqTests { public void sendSimpleMessage() throws InterruptedException, JMSException { this.producer.send("Test message"); Thread.sleep(1000L); - assertTrue(this.outputCapture.toString().contains("Test message")); + assertThat(this.outputCapture.toString().contains("Test message")).isTrue(); } } diff --git a/spring-boot-samples/spring-boot-sample-actuator-log4j2/src/test/java/sample/actuator/log4j2/SampleActuatorApplicationTests.java b/spring-boot-samples/spring-boot-sample-actuator-log4j2/src/test/java/sample/actuator/log4j2/SampleActuatorApplicationTests.java index d7c71bdeb6..a6e4381951 100644 --- a/spring-boot-samples/spring-boot-sample-actuator-log4j2/src/test/java/sample/actuator/log4j2/SampleActuatorApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-actuator-log4j2/src/test/java/sample/actuator/log4j2/SampleActuatorApplicationTests.java @@ -30,7 +30,7 @@ import org.springframework.http.ResponseEntity; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * Basic integration tests for service demo application. @@ -51,10 +51,10 @@ public class SampleActuatorApplicationTests { @SuppressWarnings("rawtypes") ResponseEntity entity = new TestRestTemplate() .getForEntity("http://localhost:" + port, Map.class); - assertEquals(HttpStatus.OK, entity.getStatusCode()); + assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); @SuppressWarnings("unchecked") Map body = entity.getBody(); - assertEquals("Hello Daniel", body.get("message")); + assertThat(body.get("message")).isEqualTo("Hello Daniel"); } } diff --git a/spring-boot-samples/spring-boot-sample-actuator-noweb/src/test/java/sample/actuator/noweb/SampleActuatorNoWebApplicationTests.java b/spring-boot-samples/spring-boot-sample-actuator-noweb/src/test/java/sample/actuator/noweb/SampleActuatorNoWebApplicationTests.java index 9b47c1ace0..4bffcc648f 100644 --- a/spring-boot-samples/spring-boot-sample-actuator-noweb/src/test/java/sample/actuator/noweb/SampleActuatorNoWebApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-actuator-noweb/src/test/java/sample/actuator/noweb/SampleActuatorNoWebApplicationTests.java @@ -25,7 +25,7 @@ import org.springframework.boot.test.SpringApplicationConfiguration; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import static org.junit.Assert.assertNotNull; +import static org.assertj.core.api.Assertions.assertThat; /** * Basic integration tests for service demo application. @@ -42,7 +42,7 @@ public class SampleActuatorNoWebApplicationTests { @Test public void endpointsExist() throws Exception { - assertNotNull(this.endpoint); + assertThat(this.endpoint).isNotNull(); } } diff --git a/spring-boot-samples/spring-boot-sample-actuator-ui/src/test/java/sample/actuator/ui/SampleActuatorUiApplicationPortTests.java b/spring-boot-samples/spring-boot-sample-actuator-ui/src/test/java/sample/actuator/ui/SampleActuatorUiApplicationPortTests.java index b930a18d1c..0f2460b846 100644 --- a/spring-boot-samples/spring-boot-sample-actuator-ui/src/test/java/sample/actuator/ui/SampleActuatorUiApplicationPortTests.java +++ b/spring-boot-samples/spring-boot-sample-actuator-ui/src/test/java/sample/actuator/ui/SampleActuatorUiApplicationPortTests.java @@ -30,7 +30,7 @@ import org.springframework.http.ResponseEntity; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * Integration tests for separate management and main service ports. @@ -53,7 +53,7 @@ public class SampleActuatorUiApplicationPortTests { public void testHome() throws Exception { ResponseEntity entity = new TestRestTemplate() .getForEntity("http://localhost:" + this.port, String.class); - assertEquals(HttpStatus.OK, entity.getStatusCode()); + assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); } @Test @@ -61,15 +61,15 @@ public class SampleActuatorUiApplicationPortTests { @SuppressWarnings("rawtypes") ResponseEntity entity = new TestRestTemplate().getForEntity( "http://localhost:" + this.managementPort + "/metrics", Map.class); - assertEquals(HttpStatus.UNAUTHORIZED, entity.getStatusCode()); + assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED); } @Test public void testHealth() throws Exception { ResponseEntity entity = new TestRestTemplate().getForEntity( "http://localhost:" + this.managementPort + "/health", String.class); - assertEquals(HttpStatus.OK, entity.getStatusCode()); - assertEquals("{\"status\":\"UP\"}", entity.getBody()); + assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); + assertThat(entity.getBody()).isEqualTo("{\"status\":\"UP\"}"); } } diff --git a/spring-boot-samples/spring-boot-sample-actuator-ui/src/test/java/sample/actuator/ui/SampleActuatorUiApplicationTests.java b/spring-boot-samples/spring-boot-sample-actuator-ui/src/test/java/sample/actuator/ui/SampleActuatorUiApplicationTests.java index bdb76e65c2..9ee10c24f8 100644 --- a/spring-boot-samples/spring-boot-sample-actuator-ui/src/test/java/sample/actuator/ui/SampleActuatorUiApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-actuator-ui/src/test/java/sample/actuator/ui/SampleActuatorUiApplicationTests.java @@ -35,8 +35,7 @@ import org.springframework.http.ResponseEntity; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * Basic integration tests for demo application. @@ -59,17 +58,16 @@ public class SampleActuatorUiApplicationTests { ResponseEntity entity = new TestRestTemplate().exchange( "http://localhost:" + this.port, HttpMethod.GET, new HttpEntity(headers), String.class); - assertEquals(HttpStatus.OK, entity.getStatusCode()); - assertTrue("Wrong body (title doesn't match):\n" + entity.getBody(), - entity.getBody().contains("Hello")); + assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); + assertThat(entity.getBody()).contains("<title>Hello"); } @Test public void testCss() throws Exception { ResponseEntity<String> entity = new TestRestTemplate().getForEntity( "http://localhost:" + this.port + "/css/bootstrap.min.css", String.class); - assertEquals(HttpStatus.OK, entity.getStatusCode()); - assertTrue("Wrong body:\n" + entity.getBody(), entity.getBody().contains("body")); + assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); + assertThat(entity.getBody()).contains("body"); } @Test @@ -77,7 +75,7 @@ public class SampleActuatorUiApplicationTests { @SuppressWarnings("rawtypes") ResponseEntity<Map> entity = new TestRestTemplate() .getForEntity("http://localhost:" + this.port + "/metrics", Map.class); - assertEquals(HttpStatus.UNAUTHORIZED, entity.getStatusCode()); + assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED); } @Test @@ -87,13 +85,9 @@ public class SampleActuatorUiApplicationTests { ResponseEntity<String> entity = new TestRestTemplate().exchange( "http://localhost:" + this.port + "/error", HttpMethod.GET, new HttpEntity<Void>(headers), String.class); - assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, entity.getStatusCode()); - assertTrue("Wrong body:\n" + entity.getBody(), - entity.getBody().contains("<html>")); - assertTrue("Wrong body:\n" + entity.getBody(), - entity.getBody().contains("<body>")); - assertTrue("Wrong body:\n" + entity.getBody(), entity.getBody() - .contains("Please contact the operator with the above information")); + assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR); + assertThat(entity.getBody()).contains("<html>").contains("<body>") + .contains("Please contact the operator with the above information"); } } diff --git a/spring-boot-samples/spring-boot-sample-actuator/src/test/java/sample/actuator/EndpointsPropertiesSampleActuatorApplicationTests.java b/spring-boot-samples/spring-boot-sample-actuator/src/test/java/sample/actuator/EndpointsPropertiesSampleActuatorApplicationTests.java index d6a6c56c45..95e95c787e 100644 --- a/spring-boot-samples/spring-boot-sample-actuator/src/test/java/sample/actuator/EndpointsPropertiesSampleActuatorApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-actuator/src/test/java/sample/actuator/EndpointsPropertiesSampleActuatorApplicationTests.java @@ -33,8 +33,7 @@ import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * Integration tests for endpoints configuration. @@ -59,11 +58,11 @@ public class EndpointsPropertiesSampleActuatorApplicationTests { @SuppressWarnings("rawtypes") ResponseEntity<Map> entity = new TestRestTemplate("user", getPassword()) .getForEntity("http://localhost:" + this.port + "/oops", Map.class); - assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, entity.getStatusCode()); + assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR); @SuppressWarnings("unchecked") Map<String, Object> body = entity.getBody(); - assertEquals("None", body.get("error")); - assertEquals(999, body.get("status")); + assertThat(body.get("error")).isEqualTo("None"); + assertThat(body.get("status")).isEqualTo(999); } @Test @@ -71,12 +70,9 @@ public class EndpointsPropertiesSampleActuatorApplicationTests { ResponseEntity<String> entity = new TestRestTemplate("user", getPassword()) .getForEntity("http://localhost:" + this.port + "/admin/health", String.class); - assertEquals(HttpStatus.OK, entity.getStatusCode()); - assertTrue("Wrong body: " + entity.getBody(), - entity.getBody().contains("\"status\":\"UP\"")); - System.err.println(entity.getBody()); - assertTrue("Wrong body: " + entity.getBody(), - entity.getBody().contains("\"hello\":\"world\"")); + assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); + assertThat(entity.getBody()).contains("\"status\":\"UP\""); + assertThat(entity.getBody()).contains("\"hello\":\"world\""); } private String getPassword() { diff --git a/spring-boot-samples/spring-boot-sample-actuator/src/test/java/sample/actuator/InsecureManagementPortAndPathSampleActuatorApplicationTests.java b/spring-boot-samples/spring-boot-sample-actuator/src/test/java/sample/actuator/InsecureManagementPortAndPathSampleActuatorApplicationTests.java index 97d9574ad9..a8741fff73 100644 --- a/spring-boot-samples/spring-boot-sample-actuator/src/test/java/sample/actuator/InsecureManagementPortAndPathSampleActuatorApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-actuator/src/test/java/sample/actuator/InsecureManagementPortAndPathSampleActuatorApplicationTests.java @@ -32,8 +32,7 @@ import org.springframework.http.ResponseEntity; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * Integration tests for separate management and main service ports. @@ -61,10 +60,10 @@ public class InsecureManagementPortAndPathSampleActuatorApplicationTests { @SuppressWarnings("rawtypes") ResponseEntity<Map> entity = new TestRestTemplate("user", getPassword()) .getForEntity("http://localhost:" + this.port, Map.class); - assertEquals(HttpStatus.OK, entity.getStatusCode()); + assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); @SuppressWarnings("unchecked") Map<String, Object> body = entity.getBody(); - assertEquals("Hello Phil", body.get("message")); + assertThat(body.get("message")).isEqualTo("Hello Phil"); } @Test @@ -73,7 +72,7 @@ public class InsecureManagementPortAndPathSampleActuatorApplicationTests { @SuppressWarnings("rawtypes") ResponseEntity<Map> entity = new TestRestTemplate().getForEntity( "http://localhost:" + this.managementPort + "/admin/metrics", Map.class); - assertEquals(HttpStatus.OK, entity.getStatusCode()); + assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); } @Test @@ -81,9 +80,8 @@ public class InsecureManagementPortAndPathSampleActuatorApplicationTests { ResponseEntity<String> entity = new TestRestTemplate().getForEntity( "http://localhost:" + this.managementPort + "/admin/health", String.class); - assertEquals(HttpStatus.OK, entity.getStatusCode()); - assertTrue("Wrong body: " + entity.getBody(), - entity.getBody().contains("\"status\":\"UP\"")); + assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); + assertThat(entity.getBody()).contains("\"status\":\"UP\""); } @Test @@ -91,9 +89,8 @@ public class InsecureManagementPortAndPathSampleActuatorApplicationTests { ResponseEntity<String> entity = new TestRestTemplate().getForEntity( "http://localhost:" + this.managementPort + "/admin/missing", String.class); - assertEquals(HttpStatus.NOT_FOUND, entity.getStatusCode()); - assertTrue("Wrong body: " + entity.getBody(), - entity.getBody().contains("\"status\":404")); + assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND); + assertThat(entity.getBody()).contains("\"status\":404"); } private String getPassword() { diff --git a/spring-boot-samples/spring-boot-sample-actuator/src/test/java/sample/actuator/InsecureManagementSampleActuatorApplicationTests.java b/spring-boot-samples/spring-boot-sample-actuator/src/test/java/sample/actuator/InsecureManagementSampleActuatorApplicationTests.java index 57bca76db6..89d86992ef 100644 --- a/spring-boot-samples/spring-boot-sample-actuator/src/test/java/sample/actuator/InsecureManagementSampleActuatorApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-actuator/src/test/java/sample/actuator/InsecureManagementSampleActuatorApplicationTests.java @@ -31,9 +31,7 @@ import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -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; /** * Integration tests for insecured service endpoints (even with Spring Security on @@ -56,12 +54,11 @@ public class InsecureManagementSampleActuatorApplicationTests { @SuppressWarnings("rawtypes") ResponseEntity<Map> entity = new TestRestTemplate() .getForEntity("http://localhost:" + this.port, Map.class); - assertEquals(HttpStatus.UNAUTHORIZED, entity.getStatusCode()); + assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED); @SuppressWarnings("unchecked") Map<String, Object> body = entity.getBody(); - assertEquals("Wrong body: " + body, "Unauthorized", body.get("error")); - assertFalse("Wrong headers: " + entity.getHeaders(), - entity.getHeaders().containsKey("Set-Cookie")); + assertThat(body.get("error")).isEqualTo("Unauthorized"); + assertThat(entity.getHeaders()).doesNotContainKey("Set-Cookie"); } @Test @@ -75,11 +72,10 @@ public class InsecureManagementSampleActuatorApplicationTests { @SuppressWarnings("rawtypes") ResponseEntity<Map> entity = new TestRestTemplate() .getForEntity("http://localhost:" + this.port + "/metrics", Map.class); - assertEquals(HttpStatus.OK, entity.getStatusCode()); + assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); @SuppressWarnings("unchecked") Map<String, Object> body = entity.getBody(); - assertTrue("Wrong body: " + body, - body.containsKey("counter.status.401.unmapped")); + assertThat(body).containsKey("counter.status.401.unmapped"); } } diff --git a/spring-boot-samples/spring-boot-sample-actuator/src/test/java/sample/actuator/InsecureSampleActuatorApplicationTests.java b/spring-boot-samples/spring-boot-sample-actuator/src/test/java/sample/actuator/InsecureSampleActuatorApplicationTests.java index 914e3ec20d..e3d4d6107b 100644 --- a/spring-boot-samples/spring-boot-sample-actuator/src/test/java/sample/actuator/InsecureSampleActuatorApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-actuator/src/test/java/sample/actuator/InsecureSampleActuatorApplicationTests.java @@ -30,8 +30,7 @@ import org.springframework.http.ResponseEntity; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; +import static org.assertj.core.api.Assertions.assertThat; /** * Integration tests for insecured service endpoints (even with Spring Security on @@ -53,12 +52,11 @@ public class InsecureSampleActuatorApplicationTests { @SuppressWarnings("rawtypes") ResponseEntity<Map> entity = new TestRestTemplate() .getForEntity("http://localhost:" + this.port, Map.class); - assertEquals(HttpStatus.OK, entity.getStatusCode()); + assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); @SuppressWarnings("unchecked") Map<String, Object> body = entity.getBody(); - assertEquals("Hello Phil", body.get("message")); - assertFalse("Wrong headers: " + entity.getHeaders(), - entity.getHeaders().containsKey("Set-Cookie")); + assertThat(body.get("message")).isEqualTo("Hello Phil"); + assertThat(entity.getHeaders()).doesNotContainKey("Set-Cookie"); } } diff --git a/spring-boot-samples/spring-boot-sample-actuator/src/test/java/sample/actuator/ManagementAddressActuatorApplicationTests.java b/spring-boot-samples/spring-boot-sample-actuator/src/test/java/sample/actuator/ManagementAddressActuatorApplicationTests.java index df075314d3..fa8f2cd394 100644 --- a/spring-boot-samples/spring-boot-sample-actuator/src/test/java/sample/actuator/ManagementAddressActuatorApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-actuator/src/test/java/sample/actuator/ManagementAddressActuatorApplicationTests.java @@ -30,8 +30,7 @@ import org.springframework.http.ResponseEntity; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * Integration tests for separate management and main service ports. @@ -56,7 +55,7 @@ public class ManagementAddressActuatorApplicationTests { @SuppressWarnings("rawtypes") ResponseEntity<Map> entity = new TestRestTemplate() .getForEntity("http://localhost:" + this.port, Map.class); - assertEquals(HttpStatus.UNAUTHORIZED, entity.getStatusCode()); + assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED); } @Test @@ -64,9 +63,8 @@ public class ManagementAddressActuatorApplicationTests { ResponseEntity<String> entity = new TestRestTemplate().getForEntity( "http://localhost:" + this.managementPort + "/admin/health", String.class); - assertEquals(HttpStatus.OK, entity.getStatusCode()); - assertTrue("Wrong body: " + entity.getBody(), - entity.getBody().contains("\"status\":\"UP\"")); + assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); + assertThat(entity.getBody()).contains("\"status\":\"UP\""); } } diff --git a/spring-boot-samples/spring-boot-sample-actuator/src/test/java/sample/actuator/ManagementPathSampleActuatorApplicationTests.java b/spring-boot-samples/spring-boot-sample-actuator/src/test/java/sample/actuator/ManagementPathSampleActuatorApplicationTests.java index 75711361fe..3d823ad69e 100644 --- a/spring-boot-samples/spring-boot-sample-actuator/src/test/java/sample/actuator/ManagementPathSampleActuatorApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-actuator/src/test/java/sample/actuator/ManagementPathSampleActuatorApplicationTests.java @@ -30,9 +30,7 @@ import org.springframework.http.ResponseEntity; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -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; /** * Integration tests for endpoints configuration. @@ -52,9 +50,8 @@ public class ManagementPathSampleActuatorApplicationTests { public void testHealth() throws Exception { ResponseEntity<String> entity = new TestRestTemplate().getForEntity( "http://localhost:" + this.port + "/admin/health", String.class); - assertEquals(HttpStatus.OK, entity.getStatusCode()); - assertTrue("Wrong body: " + entity.getBody(), - entity.getBody().contains("\"status\":\"UP\"")); + assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); + assertThat(entity.getBody()).contains("\"status\":\"UP\""); } @Test @@ -62,12 +59,11 @@ public class ManagementPathSampleActuatorApplicationTests { @SuppressWarnings("rawtypes") ResponseEntity<Map> entity = new TestRestTemplate() .getForEntity("http://localhost:" + this.port, Map.class); - assertEquals(HttpStatus.UNAUTHORIZED, entity.getStatusCode()); + assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED); @SuppressWarnings("unchecked") Map<String, Object> body = entity.getBody(); - assertEquals("Wrong body: " + body, "Unauthorized", body.get("error")); - assertFalse("Wrong headers: " + entity.getHeaders(), - entity.getHeaders().containsKey("Set-Cookie")); + assertThat(body.get("error")).isEqualTo("Unauthorized"); + assertThat(entity.getHeaders()).doesNotContainKey("Set-Cookie"); } } diff --git a/spring-boot-samples/spring-boot-sample-actuator/src/test/java/sample/actuator/ManagementPortAndPathSampleActuatorApplicationTests.java b/spring-boot-samples/spring-boot-sample-actuator/src/test/java/sample/actuator/ManagementPortAndPathSampleActuatorApplicationTests.java index 1446de329a..bc4441aaa3 100644 --- a/spring-boot-samples/spring-boot-sample-actuator/src/test/java/sample/actuator/ManagementPortAndPathSampleActuatorApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-actuator/src/test/java/sample/actuator/ManagementPortAndPathSampleActuatorApplicationTests.java @@ -32,8 +32,7 @@ import org.springframework.http.ResponseEntity; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * Integration tests for separate management and main service ports. @@ -61,10 +60,10 @@ public class ManagementPortAndPathSampleActuatorApplicationTests { @SuppressWarnings("rawtypes") ResponseEntity<Map> entity = new TestRestTemplate("user", getPassword()) .getForEntity("http://localhost:" + this.port, Map.class); - assertEquals(HttpStatus.OK, entity.getStatusCode()); + assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); @SuppressWarnings("unchecked") Map<String, Object> body = entity.getBody(); - assertEquals("Hello Phil", body.get("message")); + assertThat(body.get("message")).isEqualTo("Hello Phil"); } @Test @@ -73,7 +72,7 @@ public class ManagementPortAndPathSampleActuatorApplicationTests { @SuppressWarnings("rawtypes") ResponseEntity<Map> entity = new TestRestTemplate().getForEntity( "http://localhost:" + this.managementPort + "/admin/metrics", Map.class); - assertEquals(HttpStatus.UNAUTHORIZED, entity.getStatusCode()); + assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED); } @Test @@ -81,9 +80,8 @@ public class ManagementPortAndPathSampleActuatorApplicationTests { ResponseEntity<String> entity = new TestRestTemplate().getForEntity( "http://localhost:" + this.managementPort + "/admin/health", String.class); - assertEquals(HttpStatus.OK, entity.getStatusCode()); - assertTrue("Wrong body: " + entity.getBody(), - entity.getBody().contains("\"status\":\"UP\"")); + assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); + assertThat(entity.getBody()).contains("\"status\":\"UP\""); } @Test @@ -92,9 +90,8 @@ public class ManagementPortAndPathSampleActuatorApplicationTests { .getForEntity( "http://localhost:" + this.managementPort + "/admin/missing", String.class); - assertEquals(HttpStatus.NOT_FOUND, entity.getStatusCode()); - assertTrue("Wrong body: " + entity.getBody(), - entity.getBody().contains("\"status\":404")); + assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND); + assertThat(entity.getBody()).contains("\"status\":404"); } @Test @@ -102,10 +99,10 @@ public class ManagementPortAndPathSampleActuatorApplicationTests { @SuppressWarnings("rawtypes") ResponseEntity<Map> entity = new TestRestTemplate() .getForEntity("http://localhost:" + this.port + "/error", Map.class); - assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, entity.getStatusCode()); + assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR); @SuppressWarnings("unchecked") Map<String, Object> body = entity.getBody(); - assertEquals(999, body.get("status")); + assertThat(body.get("status")).isEqualTo(999); } @Test @@ -113,11 +110,10 @@ public class ManagementPortAndPathSampleActuatorApplicationTests { @SuppressWarnings("rawtypes") ResponseEntity<Map> entity = new TestRestTemplate().getForEntity( "http://localhost:" + this.managementPort + "/error", Map.class); - // TODO: should be 500? - assertEquals(HttpStatus.OK, entity.getStatusCode()); + assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); @SuppressWarnings("unchecked") Map<String, Object> body = entity.getBody(); - assertEquals(999, body.get("status")); + assertThat(body.get("status")).isEqualTo(999); } private String getPassword() { diff --git a/spring-boot-samples/spring-boot-sample-actuator/src/test/java/sample/actuator/ManagementPortSampleActuatorApplicationTests.java b/spring-boot-samples/spring-boot-sample-actuator/src/test/java/sample/actuator/ManagementPortSampleActuatorApplicationTests.java index fc9c21ab9e..24dd9042b9 100644 --- a/spring-boot-samples/spring-boot-sample-actuator/src/test/java/sample/actuator/ManagementPortSampleActuatorApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-actuator/src/test/java/sample/actuator/ManagementPortSampleActuatorApplicationTests.java @@ -32,8 +32,7 @@ import org.springframework.http.ResponseEntity; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * Integration tests for separate management and main service ports. @@ -60,10 +59,10 @@ public class ManagementPortSampleActuatorApplicationTests { @SuppressWarnings("rawtypes") ResponseEntity<Map> entity = new TestRestTemplate("user", getPassword()) .getForEntity("http://localhost:" + this.port, Map.class); - assertEquals(HttpStatus.OK, entity.getStatusCode()); + assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); @SuppressWarnings("unchecked") Map<String, Object> body = entity.getBody(); - assertEquals("Hello Phil", body.get("message")); + assertThat(body.get("message")).isEqualTo("Hello Phil"); } @Test @@ -72,16 +71,15 @@ public class ManagementPortSampleActuatorApplicationTests { @SuppressWarnings("rawtypes") ResponseEntity<Map> entity = new TestRestTemplate().getForEntity( "http://localhost:" + this.managementPort + "/metrics", Map.class); - assertEquals(HttpStatus.UNAUTHORIZED, entity.getStatusCode()); + assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED); } @Test public void testHealth() throws Exception { ResponseEntity<String> entity = new TestRestTemplate().getForEntity( "http://localhost:" + this.managementPort + "/health", String.class); - assertEquals(HttpStatus.OK, entity.getStatusCode()); - assertTrue("Wrong body: " + entity.getBody(), - entity.getBody().contains("\"status\":\"UP\"")); + assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); + assertThat(entity.getBody()).contains("\"status\":\"UP\""); } @Test @@ -89,10 +87,10 @@ public class ManagementPortSampleActuatorApplicationTests { @SuppressWarnings("rawtypes") ResponseEntity<Map> entity = new TestRestTemplate().getForEntity( "http://localhost:" + this.managementPort + "/error", Map.class); - assertEquals(HttpStatus.OK, entity.getStatusCode()); + assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); @SuppressWarnings("unchecked") Map<String, Object> body = entity.getBody(); - assertEquals(999, body.get("status")); + assertThat(body.get("status")).isEqualTo(999); } private String getPassword() { diff --git a/spring-boot-samples/spring-boot-sample-actuator/src/test/java/sample/actuator/NoManagementSampleActuatorApplicationTests.java b/spring-boot-samples/spring-boot-sample-actuator/src/test/java/sample/actuator/NoManagementSampleActuatorApplicationTests.java index ff0d2aca92..e0523de21c 100644 --- a/spring-boot-samples/spring-boot-sample-actuator/src/test/java/sample/actuator/NoManagementSampleActuatorApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-actuator/src/test/java/sample/actuator/NoManagementSampleActuatorApplicationTests.java @@ -32,7 +32,7 @@ import org.springframework.http.ResponseEntity; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * Integration tests for switching off management endpoints. @@ -56,10 +56,10 @@ public class NoManagementSampleActuatorApplicationTests { @SuppressWarnings("rawtypes") ResponseEntity<Map> entity = new TestRestTemplate("user", getPassword()) .getForEntity("http://localhost:" + this.port, Map.class); - assertEquals(HttpStatus.OK, entity.getStatusCode()); + assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); @SuppressWarnings("unchecked") Map<String, Object> body = entity.getBody(); - assertEquals("Hello Phil", body.get("message")); + assertThat(body.get("message")).isEqualTo("Hello Phil"); } @Test @@ -68,7 +68,7 @@ public class NoManagementSampleActuatorApplicationTests { @SuppressWarnings("rawtypes") ResponseEntity<Map> entity = new TestRestTemplate("user", getPassword()) .getForEntity("http://localhost:" + this.port + "/metrics", Map.class); - assertEquals(HttpStatus.NOT_FOUND, entity.getStatusCode()); + assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND); } private String getPassword() { diff --git a/spring-boot-samples/spring-boot-sample-actuator/src/test/java/sample/actuator/NonSensitiveHealthTests.java b/spring-boot-samples/spring-boot-sample-actuator/src/test/java/sample/actuator/NonSensitiveHealthTests.java index a55be0c4a8..1debd23883 100644 --- a/spring-boot-samples/spring-boot-sample-actuator/src/test/java/sample/actuator/NonSensitiveHealthTests.java +++ b/spring-boot-samples/spring-boot-sample-actuator/src/test/java/sample/actuator/NonSensitiveHealthTests.java @@ -28,8 +28,7 @@ import org.springframework.http.ResponseEntity; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for /health with {@code endpoints.health.sensitive=false}. @@ -49,9 +48,8 @@ public class NonSensitiveHealthTests { public void testSecureHealth() throws Exception { ResponseEntity<String> entity = new TestRestTemplate() .getForEntity("http://localhost:" + this.port + "/health", String.class); - assertEquals(HttpStatus.OK, entity.getStatusCode()); - assertFalse("Wrong body: " + entity.getBody(), - entity.getBody().contains("\"hello\":1")); + assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); + assertThat(entity.getBody()).doesNotContain("\"hello\":1"); } } diff --git a/spring-boot-samples/spring-boot-sample-actuator/src/test/java/sample/actuator/SampleActuatorApplicationTests.java b/spring-boot-samples/spring-boot-sample-actuator/src/test/java/sample/actuator/SampleActuatorApplicationTests.java index f2d7797e07..cbfc1be396 100644 --- a/spring-boot-samples/spring-boot-sample-actuator/src/test/java/sample/actuator/SampleActuatorApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-actuator/src/test/java/sample/actuator/SampleActuatorApplicationTests.java @@ -38,10 +38,7 @@ import org.springframework.http.ResponseEntity; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * Basic integration tests for service demo application. @@ -65,12 +62,11 @@ public class SampleActuatorApplicationTests { @SuppressWarnings("rawtypes") ResponseEntity<Map> entity = new TestRestTemplate() .getForEntity("http://localhost:" + this.port, Map.class); - assertEquals(HttpStatus.UNAUTHORIZED, entity.getStatusCode()); + assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED); @SuppressWarnings("unchecked") Map<String, Object> body = entity.getBody(); - assertEquals("Wrong body: " + body, "Unauthorized", body.get("error")); - assertFalse("Wrong headers: " + entity.getHeaders(), - entity.getHeaders().containsKey("Set-Cookie")); + assertThat(body.get("error")).isEqualTo("Unauthorized"); + assertThat(entity.getHeaders()).doesNotContainKey("Set-Cookie"); } @Test @@ -78,16 +74,16 @@ public class SampleActuatorApplicationTests { @SuppressWarnings("rawtypes") ResponseEntity<Map> entity = new TestRestTemplate() .getForEntity("http://localhost:" + this.port + "/metrics", Map.class); - assertEquals(HttpStatus.UNAUTHORIZED, entity.getStatusCode()); + assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED); entity = new TestRestTemplate() .getForEntity("http://localhost:" + this.port + "/metrics/", Map.class); - assertEquals(HttpStatus.UNAUTHORIZED, entity.getStatusCode()); + assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED); entity = new TestRestTemplate().getForEntity( "http://localhost:" + this.port + "/metrics/foo", Map.class); - assertEquals(HttpStatus.UNAUTHORIZED, entity.getStatusCode()); + assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED); entity = new TestRestTemplate().getForEntity( "http://localhost:" + this.port + "/metrics.json", Map.class); - assertEquals(HttpStatus.UNAUTHORIZED, entity.getStatusCode()); + assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED); } @Test @@ -95,10 +91,10 @@ public class SampleActuatorApplicationTests { @SuppressWarnings("rawtypes") ResponseEntity<Map> entity = new TestRestTemplate("user", getPassword()) .getForEntity("http://localhost:" + this.port, Map.class); - assertEquals(HttpStatus.OK, entity.getStatusCode()); + assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); @SuppressWarnings("unchecked") Map<String, Object> body = entity.getBody(); - assertEquals("Hello Phil", body.get("message")); + assertThat(body.get("message")).isEqualTo("Hello Phil"); } @Test @@ -107,10 +103,10 @@ public class SampleActuatorApplicationTests { @SuppressWarnings("rawtypes") ResponseEntity<Map> entity = new TestRestTemplate("user", getPassword()) .getForEntity("http://localhost:" + this.port + "/metrics", Map.class); - assertEquals(HttpStatus.OK, entity.getStatusCode()); + assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); @SuppressWarnings("unchecked") Map<String, Object> body = entity.getBody(); - assertTrue("Wrong body: " + body, body.containsKey("counter.status.200.root")); + assertThat(body).containsKey("counter.status.200.root"); } @Test @@ -118,49 +114,45 @@ public class SampleActuatorApplicationTests { @SuppressWarnings("rawtypes") ResponseEntity<Map> entity = new TestRestTemplate("user", getPassword()) .getForEntity("http://localhost:" + this.port + "/env", Map.class); - assertEquals(HttpStatus.OK, entity.getStatusCode()); + assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); @SuppressWarnings("unchecked") Map<String, Object> body = entity.getBody(); - assertTrue("Wrong body: " + body, body.containsKey("systemProperties")); + assertThat(body).containsKey("systemProperties"); } @Test public void testHealth() throws Exception { ResponseEntity<String> entity = new TestRestTemplate() .getForEntity("http://localhost:" + this.port + "/health", String.class); - assertEquals(HttpStatus.OK, entity.getStatusCode()); - assertTrue("Wrong body: " + entity.getBody(), - entity.getBody().contains("\"status\":\"UP\"")); - assertFalse("Wrong body: " + entity.getBody(), - entity.getBody().contains("\"hello\":\"1\"")); + assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); + assertThat(entity.getBody()).contains("\"status\":\"UP\""); + assertThat(entity.getBody()).doesNotContain("\"hello\":\"1\""); } @Test public void testSecureHealth() throws Exception { ResponseEntity<String> entity = new TestRestTemplate("user", getPassword()) .getForEntity("http://localhost:" + this.port + "/health", String.class); - assertEquals(HttpStatus.OK, entity.getStatusCode()); - assertTrue("Wrong body: " + entity.getBody(), - entity.getBody().contains("\"hello\":1")); + assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); + assertThat(entity.getBody()).contains("\"hello\":1"); } @Test public void testInfo() throws Exception { ResponseEntity<String> entity = new TestRestTemplate() .getForEntity("http://localhost:" + this.port + "/info", String.class); - assertEquals(HttpStatus.OK, entity.getStatusCode()); - assertTrue("Wrong body: " + entity.getBody(), entity.getBody() - .contains("\"artifact\":\"spring-boot-sample-actuator\"")); + assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); + assertThat(entity.getBody()) + .contains("\"artifact\":\"spring-boot-sample-actuator\""); } @Test public void testErrorPage() throws Exception { ResponseEntity<String> entity = new TestRestTemplate("user", getPassword()) .getForEntity("http://localhost:" + this.port + "/foo", String.class); - assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, entity.getStatusCode()); + assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR); String body = entity.getBody(); - assertNotNull(body); - assertTrue("Wrong body: " + body, body.contains("\"error\":")); + assertThat(body).contains("\"error\":"); } @Test @@ -171,11 +163,10 @@ public class SampleActuatorApplicationTests { ResponseEntity<String> entity = new TestRestTemplate("user", getPassword()) .exchange("http://localhost:" + this.port + "/foo", HttpMethod.GET, request, String.class); - assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, entity.getStatusCode()); + assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR); String body = entity.getBody(); - assertNotNull("Body was null", body); - assertTrue("Wrong body: " + body, - body.contains("This application has no explicit mapping for /error")); + assertThat(body).as("Body was null").isNotNull(); + assertThat(body).contains("This application has no explicit mapping for /error"); } @Test @@ -185,14 +176,14 @@ public class SampleActuatorApplicationTests { @SuppressWarnings("rawtypes") ResponseEntity<List> entity = new TestRestTemplate("user", getPassword()) .getForEntity("http://localhost:" + this.port + "/trace", List.class); - assertEquals(HttpStatus.OK, entity.getStatusCode()); + assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); @SuppressWarnings("unchecked") List<Map<String, Object>> list = entity.getBody(); Map<String, Object> trace = list.get(list.size() - 1); @SuppressWarnings("unchecked") Map<String, Object> map = (Map<String, Object>) ((Map<String, Object>) ((Map<String, Object>) trace .get("info")).get("headers")).get("response"); - assertEquals("200", map.get("status")); + assertThat(map.get("status")).isEqualTo("200"); } @Test @@ -200,24 +191,23 @@ public class SampleActuatorApplicationTests { @SuppressWarnings("rawtypes") ResponseEntity<Map> entity = new TestRestTemplate() .getForEntity("http://localhost:" + this.port + "/error", Map.class); - assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, entity.getStatusCode()); + assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR); @SuppressWarnings("unchecked") Map<String, Object> body = entity.getBody(); - assertEquals("None", body.get("error")); - assertEquals(999, body.get("status")); + assertThat(body.get("error")).isEqualTo("None"); + assertThat(body.get("status")).isEqualTo(999); } @Test + @SuppressWarnings("unchecked") public void testBeans() throws Exception { @SuppressWarnings("rawtypes") ResponseEntity<List> entity = new TestRestTemplate("user", getPassword()) .getForEntity("http://localhost:" + this.port + "/beans", List.class); - assertEquals(HttpStatus.OK, entity.getStatusCode()); - assertEquals(1, entity.getBody().size()); - @SuppressWarnings("unchecked") + assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); + assertThat(entity.getBody()).hasSize(1); Map<String, Object> body = (Map<String, Object>) entity.getBody().get(0); - assertTrue("Wrong body: " + body, - ((String) body.get("context")).startsWith("application")); + assertThat(((String) body.get("context"))).startsWith("application"); } @Test @@ -226,11 +216,10 @@ public class SampleActuatorApplicationTests { ResponseEntity<Map> entity = new TestRestTemplate("user", getPassword()) .getForEntity("http://localhost:" + this.port + "/configprops", Map.class); - assertEquals(HttpStatus.OK, entity.getStatusCode()); + assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); @SuppressWarnings("unchecked") Map<String, Object> body = entity.getBody(); - assertTrue("Wrong body: " + body, - body.containsKey("spring.datasource.CONFIGURATION_PROPERTIES")); + assertThat(body).containsKey("spring.datasource.CONFIGURATION_PROPERTIES"); } private String getPassword() { diff --git a/spring-boot-samples/spring-boot-sample-actuator/src/test/java/sample/actuator/ServletPathInsecureSampleActuatorApplicationTests.java b/spring-boot-samples/spring-boot-sample-actuator/src/test/java/sample/actuator/ServletPathInsecureSampleActuatorApplicationTests.java index c5b9b30a8e..5f344e8bbc 100644 --- a/spring-boot-samples/spring-boot-sample-actuator/src/test/java/sample/actuator/ServletPathInsecureSampleActuatorApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-actuator/src/test/java/sample/actuator/ServletPathInsecureSampleActuatorApplicationTests.java @@ -30,8 +30,7 @@ import org.springframework.http.ResponseEntity; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; +import static org.assertj.core.api.Assertions.assertThat; /** * Integration tests for insecured service endpoints (even with Spring Security on @@ -54,12 +53,11 @@ public class ServletPathInsecureSampleActuatorApplicationTests { @SuppressWarnings("rawtypes") ResponseEntity<Map> entity = new TestRestTemplate() .getForEntity("http://localhost:" + this.port + "/spring/", Map.class); - assertEquals(HttpStatus.OK, entity.getStatusCode()); + assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); @SuppressWarnings("unchecked") Map<String, Object> body = entity.getBody(); - assertEquals("Hello Phil", body.get("message")); - assertFalse("Wrong headers: " + entity.getHeaders(), - entity.getHeaders().containsKey("Set-Cookie")); + assertThat(body.get("message")).isEqualTo("Hello Phil"); + assertThat(entity.getHeaders()).doesNotContainKey("Set-Cookie"); } @Test @@ -67,7 +65,7 @@ public class ServletPathInsecureSampleActuatorApplicationTests { @SuppressWarnings("rawtypes") ResponseEntity<Map> entity = new TestRestTemplate().getForEntity( "http://localhost:" + this.port + "/spring/metrics", Map.class); - assertEquals(HttpStatus.UNAUTHORIZED, entity.getStatusCode()); + assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED); } } diff --git a/spring-boot-samples/spring-boot-sample-actuator/src/test/java/sample/actuator/ServletPathSampleActuatorApplicationTests.java b/spring-boot-samples/spring-boot-sample-actuator/src/test/java/sample/actuator/ServletPathSampleActuatorApplicationTests.java index a1e760910d..deb970a12c 100644 --- a/spring-boot-samples/spring-boot-sample-actuator/src/test/java/sample/actuator/ServletPathSampleActuatorApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-actuator/src/test/java/sample/actuator/ServletPathSampleActuatorApplicationTests.java @@ -30,9 +30,7 @@ import org.springframework.http.ResponseEntity; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -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; /** * Integration tests for endpoints configuration. @@ -54,20 +52,19 @@ public class ServletPathSampleActuatorApplicationTests { ResponseEntity<Map> entity = new TestRestTemplate("user", "password") .getForEntity("http://localhost:" + this.port + "/spring/error", Map.class); - assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, entity.getStatusCode()); + assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR); @SuppressWarnings("unchecked") Map<String, Object> body = entity.getBody(); - assertEquals("None", body.get("error")); - assertEquals(999, body.get("status")); + assertThat(body.get("error")).isEqualTo("None"); + assertThat(body.get("status")).isEqualTo(999); } @Test public void testHealth() throws Exception { ResponseEntity<String> entity = new TestRestTemplate().getForEntity( "http://localhost:" + this.port + "/spring/health", String.class); - assertEquals(HttpStatus.OK, entity.getStatusCode()); - assertTrue("Wrong body: " + entity.getBody(), - entity.getBody().contains("\"status\":\"UP\"")); + assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); + assertThat(entity.getBody()).contains("\"status\":\"UP\""); } @Test @@ -75,12 +72,11 @@ public class ServletPathSampleActuatorApplicationTests { @SuppressWarnings("rawtypes") ResponseEntity<Map> entity = new TestRestTemplate() .getForEntity("http://localhost:" + this.port + "/spring/", Map.class); - assertEquals(HttpStatus.UNAUTHORIZED, entity.getStatusCode()); + assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED); @SuppressWarnings("unchecked") Map<String, Object> body = entity.getBody(); - assertEquals("Wrong body: " + body, "Unauthorized", body.get("error")); - assertFalse("Wrong headers: " + entity.getHeaders(), - entity.getHeaders().containsKey("Set-Cookie")); + assertThat(body.get("error")).isEqualTo("Unauthorized"); + assertThat(entity.getHeaders()).doesNotContainKey("Set-Cookie"); } } diff --git a/spring-boot-samples/spring-boot-sample-actuator/src/test/java/sample/actuator/ShutdownSampleActuatorApplicationTests.java b/spring-boot-samples/spring-boot-sample-actuator/src/test/java/sample/actuator/ShutdownSampleActuatorApplicationTests.java index a822d130ea..09c567f884 100644 --- a/spring-boot-samples/spring-boot-sample-actuator/src/test/java/sample/actuator/ShutdownSampleActuatorApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-actuator/src/test/java/sample/actuator/ShutdownSampleActuatorApplicationTests.java @@ -32,8 +32,7 @@ import org.springframework.http.ResponseEntity; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * Integration tests for separate management and main service ports. @@ -57,10 +56,10 @@ public class ShutdownSampleActuatorApplicationTests { @SuppressWarnings("rawtypes") ResponseEntity<Map> entity = new TestRestTemplate("user", getPassword()) .getForEntity("http://localhost:" + this.port, Map.class); - assertEquals(HttpStatus.OK, entity.getStatusCode()); + assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); @SuppressWarnings("unchecked") Map<String, Object> body = entity.getBody(); - assertEquals("Hello Phil", body.get("message")); + assertThat(body.get("message")).isEqualTo("Hello Phil"); } @Test @@ -69,11 +68,10 @@ public class ShutdownSampleActuatorApplicationTests { ResponseEntity<Map> entity = new TestRestTemplate("user", getPassword()) .postForEntity("http://localhost:" + this.port + "/shutdown", null, Map.class); - assertEquals(HttpStatus.OK, entity.getStatusCode()); + assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); @SuppressWarnings("unchecked") Map<String, Object> body = entity.getBody(); - assertTrue("Wrong body: " + body, - ((String) body.get("message")).contains("Shutting down")); + assertThat(((String) body.get("message"))).contains("Shutting down"); } private String getPassword() { diff --git a/spring-boot-samples/spring-boot-sample-ant/src/test/java/sample/ant/SampleAntApplicationIT.java b/spring-boot-samples/spring-boot-sample-ant/src/test/java/sample/ant/SampleAntApplicationIT.java index 7050787e79..617e12273b 100644 --- a/spring-boot-samples/spring-boot-sample-ant/src/test/java/sample/ant/SampleAntApplicationIT.java +++ b/spring-boot-samples/spring-boot-sample-ant/src/test/java/sample/ant/SampleAntApplicationIT.java @@ -16,9 +16,7 @@ package sample.ant; -import static org.hamcrest.Matchers.containsString; -import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import java.io.File; import java.io.FileFilter; @@ -48,12 +46,12 @@ public class SampleAntApplicationIT { } }); - assertThat("Number of jars", jarFiles.length, equalTo(1)); + assertThat(jarFiles).hasSize(1); Process process = new JavaExecutable().processBuilder("-jar", jarFiles[0].getName()).directory(target).start(); process.waitFor(5, TimeUnit.MINUTES); - assertThat(process.exitValue(), equalTo(0)); + assertThat(process.exitValue()).isEqualTo(0); String output = FileCopyUtils.copyToString(new InputStreamReader(process.getInputStream())); - assertThat(output, containsString("Spring Boot Ant Example")); + assertThat(output).contains("Spring Boot Ant Example"); } } diff --git a/spring-boot-samples/spring-boot-sample-aop/src/test/java/sample/aop/SampleAopApplicationTests.java b/spring-boot-samples/spring-boot-sample-aop/src/test/java/sample/aop/SampleAopApplicationTests.java index 326ac90b39..18e03b2f5f 100644 --- a/spring-boot-samples/spring-boot-sample-aop/src/test/java/sample/aop/SampleAopApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-aop/src/test/java/sample/aop/SampleAopApplicationTests.java @@ -23,7 +23,7 @@ import org.junit.Test; import org.springframework.boot.test.OutputCapture; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link SampleAopApplication}. @@ -57,14 +57,14 @@ public class SampleAopApplicationTests { public void testDefaultSettings() throws Exception { SampleAopApplication.main(new String[0]); String output = this.outputCapture.toString(); - assertTrue("Wrong output: " + output, output.contains("Hello Phil")); + assertThat(output).contains("Hello Phil"); } @Test public void testCommandLineOverrides() throws Exception { SampleAopApplication.main(new String[] { "--name=Gordon" }); String output = this.outputCapture.toString(); - assertTrue("Wrong output: " + output, output.contains("Hello Gordon")); + assertThat(output).contains("Hello Gordon"); } } diff --git a/spring-boot-samples/spring-boot-sample-atmosphere/src/test/java/sample/atmosphere/SampleAtmosphereApplicationTests.java b/spring-boot-samples/spring-boot-sample-atmosphere/src/test/java/sample/atmosphere/SampleAtmosphereApplicationTests.java index beb0c0d186..d58676e7ad 100644 --- a/spring-boot-samples/spring-boot-sample-atmosphere/src/test/java/sample/atmosphere/SampleAtmosphereApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-atmosphere/src/test/java/sample/atmosphere/SampleAtmosphereApplicationTests.java @@ -42,9 +42,7 @@ import org.springframework.web.socket.client.WebSocketConnectionManager; import org.springframework.web.socket.client.standard.StandardWebSocketClient; import org.springframework.web.socket.handler.TextWebSocketHandler; -import static org.hamcrest.Matchers.containsString; -import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(SampleAtmosphereApplication.class) @@ -68,9 +66,9 @@ public class SampleAtmosphereApplicationTests { AtomicReference<String> messagePayloadReference = context .getBean(ClientConfiguration.class).messagePayload; context.close(); - assertThat(count, equalTo(0L)); - assertThat(messagePayloadReference.get(), - containsString("{\"message\":\"test\",\"author\":\"test\",\"time\":")); + assertThat(count).isEqualTo(0L); + assertThat(messagePayloadReference.get()) + .contains("{\"message\":\"test\",\"author\":\"test\",\"time\":"); } @Configuration diff --git a/spring-boot-samples/spring-boot-sample-batch/src/test/java/sample/batch/SampleBatchApplicationTests.java b/spring-boot-samples/spring-boot-sample-batch/src/test/java/sample/batch/SampleBatchApplicationTests.java index 52f983b941..141ad2334f 100644 --- a/spring-boot-samples/spring-boot-sample-batch/src/test/java/sample/batch/SampleBatchApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-batch/src/test/java/sample/batch/SampleBatchApplicationTests.java @@ -22,8 +22,7 @@ import org.junit.Test; import org.springframework.boot.SpringApplication; import org.springframework.boot.test.OutputCapture; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; public class SampleBatchApplicationTests { @@ -32,11 +31,10 @@ public class SampleBatchApplicationTests { @Test public void testDefaultSettings() throws Exception { - assertEquals(0, SpringApplication - .exit(SpringApplication.run(SampleBatchApplication.class))); + assertThat(SpringApplication + .exit(SpringApplication.run(SampleBatchApplication.class))).isEqualTo(0); String output = this.outputCapture.toString(); - assertTrue("Wrong output: " + output, - output.contains("completed with the following parameters")); + assertThat(output).contains("completed with the following parameters"); } } diff --git a/spring-boot-samples/spring-boot-sample-cache/src/test/java/sample/cache/SampleCacheApplicationTests.java b/spring-boot-samples/spring-boot-sample-cache/src/test/java/sample/cache/SampleCacheApplicationTests.java index df5c5c6e1c..2d3a17f317 100644 --- a/spring-boot-samples/spring-boot-sample-cache/src/test/java/sample/cache/SampleCacheApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-cache/src/test/java/sample/cache/SampleCacheApplicationTests.java @@ -25,10 +25,7 @@ import org.springframework.cache.Cache; import org.springframework.cache.CacheManager; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import static org.hamcrest.CoreMatchers.nullValue; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.core.IsNull.notNullValue; +import static org.assertj.core.api.Assertions.assertThat; @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(SampleCacheApplication.class) @@ -43,11 +40,11 @@ public class SampleCacheApplicationTests { @Test public void validateCache() { Cache countries = this.cacheManager.getCache("countries"); - assertThat(countries, is(notNullValue())); + assertThat(countries).isNotNull(); countries.clear(); // Simple test assuming the cache is empty - assertThat(countries.get("BE"), is(nullValue())); + assertThat(countries.get("BE")).isNull(); Country be = this.countryRepository.findByCode("BE"); - assertThat((Country) countries.get("BE").get(), is(be)); + assertThat((Country) countries.get("BE").get()).isEqualTo(be); } } diff --git a/spring-boot-samples/spring-boot-sample-data-cassandra/src/test/java/sample/data/cassandra/SampleCassandraApplicationTests.java b/spring-boot-samples/spring-boot-sample-data-cassandra/src/test/java/sample/data/cassandra/SampleCassandraApplicationTests.java index 10c0a83b12..f50659242a 100644 --- a/spring-boot-samples/spring-boot-sample-data-cassandra/src/test/java/sample/data/cassandra/SampleCassandraApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-data-cassandra/src/test/java/sample/data/cassandra/SampleCassandraApplicationTests.java @@ -30,7 +30,7 @@ import org.springframework.test.context.TestExecutionListeners; import org.springframework.test.context.TestExecutionListeners.MergeMode; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link SampleCassandraApplication}. @@ -51,8 +51,7 @@ public class SampleCassandraApplicationTests { @Test public void testDefaultSettings() throws Exception { String output = SampleCassandraApplicationTests.outputCapture.toString(); - assertTrue("Wrong output: " + output, - output.contains("firstName='Alice', lastName='Smith'")); + assertThat(output).contains("firstName='Alice', lastName='Smith'"); } } diff --git a/spring-boot-samples/spring-boot-sample-data-elasticsearch/src/test/java/sample/data/elasticsearch/SampleElasticsearchApplicationTests.java b/spring-boot-samples/spring-boot-sample-data-elasticsearch/src/test/java/sample/data/elasticsearch/SampleElasticsearchApplicationTests.java index 87d9db45e5..2cfceb60a9 100644 --- a/spring-boot-samples/spring-boot-sample-data-elasticsearch/src/test/java/sample/data/elasticsearch/SampleElasticsearchApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-data-elasticsearch/src/test/java/sample/data/elasticsearch/SampleElasticsearchApplicationTests.java @@ -25,7 +25,7 @@ import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.boot.test.OutputCapture; import org.springframework.core.NestedCheckedException; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link SampleElasticsearchApplication}. @@ -53,8 +53,7 @@ public class SampleElasticsearchApplicationTests { } } String output = this.outputCapture.toString(); - assertTrue("Wrong output: " + output, - output.contains("firstName='Alice', lastName='Smith'")); + assertThat(output).contains("firstName='Alice', lastName='Smith'"); } private boolean serverNotRunning(IllegalStateException ex) { diff --git a/spring-boot-samples/spring-boot-sample-data-gemfire/src/test/java/sample/data/gemfire/SampleDataGemFireApplicationTests.java b/spring-boot-samples/spring-boot-sample-data-gemfire/src/test/java/sample/data/gemfire/SampleDataGemFireApplicationTests.java index 0fce4acdd1..13f90ac861 100644 --- a/spring-boot-samples/spring-boot-sample-data-gemfire/src/test/java/sample/data/gemfire/SampleDataGemFireApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-data-gemfire/src/test/java/sample/data/gemfire/SampleDataGemFireApplicationTests.java @@ -16,8 +16,6 @@ package sample.data.gemfire; -import java.util.ArrayList; -import java.util.List; import java.util.concurrent.atomic.AtomicLong; import org.junit.Before; @@ -31,9 +29,7 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.SpringApplicationConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -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; /** * The SampleDataGemFireApplicationTests class is a test suite with test cases testing the @@ -50,70 +46,38 @@ public class SampleDataGemFireApplicationTests { private final AtomicLong ID_GENERATOR = new AtomicLong(0l); - protected List<Gemstone> asList(final Iterable<Gemstone> gemstones) { - List<Gemstone> gemstoneList = new ArrayList<Gemstone>(); - - if (gemstones != null) { - for (Gemstone gemstone : gemstones) { - gemstoneList.add(gemstone); - } - } - - return gemstoneList; - } - - protected Gemstone createGemstone(final String name) { - return createGemstone(this.ID_GENERATOR.incrementAndGet(), name); - } - - protected Gemstone createGemstone(final Long id, final String name) { - return new Gemstone(id, name); - } - - protected List<Gemstone> getGemstones(final String... names) { - List<Gemstone> gemstones = new ArrayList<Gemstone>(names.length); - - for (String name : names) { - gemstones.add(createGemstone(null, name)); - } - - return gemstones; - } - @Before public void setup() { - assertNotNull("A reference to the GemstoneService was not properly configured!", - this.gemstoneService); + assertThat(this.gemstoneService).isNotNull(); } @Test public void testGemstonesApp() { - assertEquals(0, this.gemstoneService.count()); - assertTrue(asList(this.gemstoneService.list()).isEmpty()); + assertThat(this.gemstoneService.count()).isEqualTo(0); + assertThat(this.gemstoneService.list()).isEmpty(); this.gemstoneService.save(createGemstone("Diamond")); this.gemstoneService.save(createGemstone("Ruby")); - assertEquals(2, this.gemstoneService.count()); - assertTrue(asList(this.gemstoneService.list()) - .containsAll(getGemstones("Diamond", "Ruby"))); + assertThat(this.gemstoneService.count()).isEqualTo(2); + assertThat(this.gemstoneService.list()).contains(getGemstones("Diamond", "Ruby")); try { this.gemstoneService.save(createGemstone("Coal")); } - catch (IllegalGemstoneException expected) { + catch (IllegalGemstoneException ex) { + // Expected } - assertEquals(2, this.gemstoneService.count()); - assertTrue(asList(this.gemstoneService.list()) - .containsAll(getGemstones("Diamond", "Ruby"))); + assertThat(this.gemstoneService.count()).isEqualTo(2); + assertThat(this.gemstoneService.list()).contains(getGemstones("Diamond", "Ruby")); this.gemstoneService.save(createGemstone("Pearl")); this.gemstoneService.save(createGemstone("Sapphire")); - assertEquals(4, this.gemstoneService.count()); - assertTrue(asList(this.gemstoneService.list()) - .containsAll(getGemstones("Diamond", "Ruby", "Pearl", "Sapphire"))); + assertThat(this.gemstoneService.count()).isEqualTo(4); + assertThat(this.gemstoneService.list()) + .contains(getGemstones("Diamond", "Ruby", "Pearl", "Sapphire")); try { this.gemstoneService.save(createGemstone("Quartz")); @@ -121,11 +85,28 @@ public class SampleDataGemFireApplicationTests { catch (IllegalGemstoneException expected) { } - assertEquals(4, this.gemstoneService.count()); - assertTrue(asList(this.gemstoneService.list()) - .containsAll(getGemstones("Diamond", "Ruby", "Pearl", "Sapphire"))); - assertEquals(createGemstone("Diamond"), this.gemstoneService.get("Diamond")); - assertEquals(createGemstone("Pearl"), this.gemstoneService.get("Pearl")); + assertThat(this.gemstoneService.count()).isEqualTo(4); + assertThat(this.gemstoneService.list()) + .contains(getGemstones("Diamond", "Ruby", "Pearl", "Sapphire")); + assertThat(this.gemstoneService.get("Diamond")) + .isEqualTo(createGemstone("Diamond")); + assertThat(this.gemstoneService.get("Pearl")).isEqualTo(createGemstone("Pearl")); + } + + private Gemstone[] getGemstones(String... names) { + Gemstone[] gemstones = new Gemstone[names.length]; + for (int i = 0; i < names.length; i++) { + gemstones[i] = createGemstone(null, names[i]); + } + return gemstones; + } + + private Gemstone createGemstone(String name) { + return createGemstone(this.ID_GENERATOR.incrementAndGet(), name); + } + + private Gemstone createGemstone(Long id, String name) { + return new Gemstone(id, name); } } diff --git a/spring-boot-samples/spring-boot-sample-data-jpa/src/test/java/sample/data/jpa/SampleDataJpaApplicationTests.java b/spring-boot-samples/spring-boot-sample-data-jpa/src/test/java/sample/data/jpa/SampleDataJpaApplicationTests.java index ef1e073f3a..371ca52577 100644 --- a/spring-boot-samples/spring-boot-sample-data-jpa/src/test/java/sample/data/jpa/SampleDataJpaApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-data-jpa/src/test/java/sample/data/jpa/SampleDataJpaApplicationTests.java @@ -34,7 +34,7 @@ import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; -import static org.junit.Assert.assertEquals; +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; @@ -74,9 +74,9 @@ public class SampleDataJpaApplicationTests { @Test public void testJmx() throws Exception { - assertEquals(1, ManagementFactory.getPlatformMBeanServer() - .queryMBeans(new ObjectName("jpa.sample:type=ConnectionPool,*"), null) - .size()); + assertThat(ManagementFactory.getPlatformMBeanServer() + .queryMBeans(new ObjectName("jpa.sample:type=ConnectionPool,*"), null)) + .hasSize(1); } } diff --git a/spring-boot-samples/spring-boot-sample-data-jpa/src/test/java/sample/data/jpa/service/CityRepositoryIntegrationTests.java b/spring-boot-samples/spring-boot-sample-data-jpa/src/test/java/sample/data/jpa/service/CityRepositoryIntegrationTests.java index 2e591a964d..58d1afd914 100644 --- a/spring-boot-samples/spring-boot-sample-data-jpa/src/test/java/sample/data/jpa/service/CityRepositoryIntegrationTests.java +++ b/spring-boot-samples/spring-boot-sample-data-jpa/src/test/java/sample/data/jpa/service/CityRepositoryIntegrationTests.java @@ -26,9 +26,7 @@ import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import static org.hamcrest.Matchers.greaterThan; -import static org.hamcrest.Matchers.is; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; /** * Integration tests for {@link CityRepository}. @@ -46,6 +44,6 @@ public class CityRepositoryIntegrationTests { public void findsFirstPageOfCities() { Page<City> cities = this.repository.findAll(new PageRequest(0, 10)); - assertThat(cities.getTotalElements(), is(greaterThan(20L))); + assertThat(cities.getTotalElements()).isGreaterThan(20L); } } diff --git a/spring-boot-samples/spring-boot-sample-data-jpa/src/test/java/sample/data/jpa/service/HotelRepositoryIntegrationTests.java b/spring-boot-samples/spring-boot-sample-data-jpa/src/test/java/sample/data/jpa/service/HotelRepositoryIntegrationTests.java index 4a540b7c22..9b8c2d9cf5 100644 --- a/spring-boot-samples/spring-boot-sample-data-jpa/src/test/java/sample/data/jpa/service/HotelRepositoryIntegrationTests.java +++ b/spring-boot-samples/spring-boot-sample-data-jpa/src/test/java/sample/data/jpa/service/HotelRepositoryIntegrationTests.java @@ -33,10 +33,7 @@ import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Sort.Direction; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import static org.hamcrest.Matchers.greaterThan; -import static org.hamcrest.Matchers.hasSize; -import static org.hamcrest.Matchers.is; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; /** * Integration tests for {@link HotelRepository}. @@ -57,17 +54,17 @@ public class HotelRepositoryIntegrationTests { City city = this.cityRepository .findAll(new PageRequest(0, 1, Direction.ASC, "name")).getContent() .get(0); - assertThat(city.getName(), is("Atlanta")); + assertThat(city.getName()).isEqualTo("Atlanta"); Page<HotelSummary> hotels = this.repository.findByCity(city, new PageRequest(0, 10, Direction.ASC, "name")); Hotel hotel = this.repository.findByCityAndName(city, hotels.getContent().get(0).getName()); - assertThat(hotel.getName(), is("Doubletree")); + assertThat(hotel.getName()).isEqualTo("Doubletree"); List<RatingCount> counts = this.repository.findRatingCounts(hotel); - assertThat(counts, hasSize(1)); - assertThat(counts.get(0).getRating(), is(Rating.AVERAGE)); - assertThat(counts.get(0).getCount(), is(greaterThan(1L))); + assertThat(counts).hasSize(1); + assertThat(counts.get(0).getRating()).isEqualTo(Rating.AVERAGE); + assertThat(counts.get(0).getCount()).isGreaterThan(1L); } } diff --git a/spring-boot-samples/spring-boot-sample-data-mongodb/src/test/java/sample/data/mongo/SampleMongoApplicationTests.java b/spring-boot-samples/spring-boot-sample-data-mongodb/src/test/java/sample/data/mongo/SampleMongoApplicationTests.java index 53eb843be2..befd77b18d 100644 --- a/spring-boot-samples/spring-boot-sample-data-mongodb/src/test/java/sample/data/mongo/SampleMongoApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-data-mongodb/src/test/java/sample/data/mongo/SampleMongoApplicationTests.java @@ -25,7 +25,7 @@ import org.springframework.boot.test.OutputCapture; import org.springframework.boot.test.SpringApplicationConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link SampleMongoApplication}. @@ -44,8 +44,7 @@ public class SampleMongoApplicationTests { @Test public void testDefaultSettings() throws Exception { String output = SampleMongoApplicationTests.outputCapture.toString(); - assertTrue("Wrong output: " + output, - output.contains("firstName='Alice', lastName='Smith'")); + assertThat(output).contains("firstName='Alice', lastName='Smith'"); } } diff --git a/spring-boot-samples/spring-boot-sample-data-redis/src/test/java/sample/data/redis/SampleRedisApplicationTests.java b/spring-boot-samples/spring-boot-sample-data-redis/src/test/java/sample/data/redis/SampleRedisApplicationTests.java index d3329a7c25..91b7832a4f 100644 --- a/spring-boot-samples/spring-boot-sample-data-redis/src/test/java/sample/data/redis/SampleRedisApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-data-redis/src/test/java/sample/data/redis/SampleRedisApplicationTests.java @@ -22,7 +22,7 @@ import org.junit.Test; import org.springframework.boot.test.OutputCapture; import org.springframework.data.redis.RedisConnectionFailureException; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link SampleRedisApplication}. @@ -45,8 +45,7 @@ public class SampleRedisApplicationTests { } } String output = this.outputCapture.toString(); - assertTrue("Wrong output: " + output, - output.contains("Found key spring.boot.redis.test")); + assertThat(output).contains("Found key spring.boot.redis.test"); } private boolean redisServerRunning(Throwable ex) { diff --git a/spring-boot-samples/spring-boot-sample-data-rest/src/test/java/sample/data/rest/service/CityRepositoryIntegrationTests.java b/spring-boot-samples/spring-boot-sample-data-rest/src/test/java/sample/data/rest/service/CityRepositoryIntegrationTests.java index 9a2c1392b6..a3549ba0ff 100644 --- a/spring-boot-samples/spring-boot-sample-data-rest/src/test/java/sample/data/rest/service/CityRepositoryIntegrationTests.java +++ b/spring-boot-samples/spring-boot-sample-data-rest/src/test/java/sample/data/rest/service/CityRepositoryIntegrationTests.java @@ -27,11 +27,7 @@ import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.greaterThan; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.notNullValue; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; /** * Integration tests for {@link CityRepository}. @@ -50,15 +46,15 @@ public class CityRepositoryIntegrationTests { public void findsFirstPageOfCities() { Page<City> cities = this.repository.findAll(new PageRequest(0, 10)); - assertThat(cities.getTotalElements(), is(greaterThan(20L))); + assertThat(cities.getTotalElements()).isGreaterThan(20L); } @Test public void findByNameAndCountry() { City city = this.repository.findByNameAndCountryAllIgnoringCase("Melbourne", "Australia"); - assertThat(city, notNullValue()); - assertThat(city.getName(), is(equalTo("Melbourne"))); + assertThat(city).isNotNull(); + assertThat(city.getName()).isEqualTo("Melbourne"); } @Test @@ -66,6 +62,6 @@ public class CityRepositoryIntegrationTests { Page<City> cities = this.repository .findByNameContainingAndCountryContainingAllIgnoringCase("", "UK", new PageRequest(0, 10)); - assertThat(cities.getTotalElements(), is(equalTo(3L))); + assertThat(cities.getTotalElements()).isEqualTo(3L); } } diff --git a/spring-boot-samples/spring-boot-sample-data-solr/src/test/java/sample/data/solr/SampleSolrApplicationTests.java b/spring-boot-samples/spring-boot-sample-data-solr/src/test/java/sample/data/solr/SampleSolrApplicationTests.java index 9a527cb329..a63e9e816b 100644 --- a/spring-boot-samples/spring-boot-sample-data-solr/src/test/java/sample/data/solr/SampleSolrApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-data-solr/src/test/java/sample/data/solr/SampleSolrApplicationTests.java @@ -22,7 +22,7 @@ import org.junit.Test; import org.springframework.boot.test.OutputCapture; import org.springframework.core.NestedCheckedException; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; public class SampleSolrApplicationTests { @@ -41,7 +41,7 @@ public class SampleSolrApplicationTests { } } String output = this.outputCapture.toString(); - assertTrue("Wrong output: " + output, output.contains("name=Sony Playstation")); + assertThat(output).contains("name=Sony Playstation"); } private boolean serverNotRunning(IllegalStateException ex) { diff --git a/spring-boot-samples/spring-boot-sample-flyway/src/test/java/sample/flyway/SampleFlywayApplicationTests.java b/spring-boot-samples/spring-boot-sample-flyway/src/test/java/sample/flyway/SampleFlywayApplicationTests.java index 1382f213a0..f3e325a324 100644 --- a/spring-boot-samples/spring-boot-sample-flyway/src/test/java/sample/flyway/SampleFlywayApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-flyway/src/test/java/sample/flyway/SampleFlywayApplicationTests.java @@ -24,7 +24,7 @@ import org.springframework.boot.test.SpringApplicationConfiguration; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(SampleFlywayApplication.class) @@ -35,8 +35,8 @@ public class SampleFlywayApplicationTests { @Test public void testDefaultSettings() throws Exception { - assertEquals(new Integer(1), this.template - .queryForObject("SELECT COUNT(*) from PERSON", Integer.class)); + assertThat(this.template.queryForObject("SELECT COUNT(*) from PERSON", + Integer.class)).isEqualTo(1); } } diff --git a/spring-boot-samples/spring-boot-sample-hateoas/src/test/java/sample/hateoas/SampleHateoasApplicationTests.java b/spring-boot-samples/spring-boot-sample-hateoas/src/test/java/sample/hateoas/SampleHateoasApplicationTests.java index 511024cfa4..d7fc1fd82e 100644 --- a/spring-boot-samples/spring-boot-sample-hateoas/src/test/java/sample/hateoas/SampleHateoasApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-hateoas/src/test/java/sample/hateoas/SampleHateoasApplicationTests.java @@ -33,10 +33,7 @@ import org.springframework.http.RequestEntity; import org.springframework.http.ResponseEntity; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import static org.hamcrest.Matchers.containsString; -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; @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(SampleHateoasApplication.class) @@ -50,10 +47,10 @@ public class SampleHateoasApplicationTests { public void hasHalLinks() throws Exception { ResponseEntity<String> entity = new TestRestTemplate().getForEntity( "http://localhost:" + this.port + "/customers/1", String.class); - assertThat(entity.getStatusCode(), equalTo(HttpStatus.OK)); - assertThat(entity.getBody(), startsWith( - "{\"id\":1,\"firstName\":\"Oliver\"" + ",\"lastName\":\"Gierke\"")); - assertThat(entity.getBody(), containsString("_links\":{\"self\":{\"href\"")); + assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); + assertThat(entity.getBody()).startsWith( + "{\"id\":1,\"firstName\":\"Oliver\"" + ",\"lastName\":\"Gierke\""); + assertThat(entity.getBody()).contains("_links\":{\"self\":{\"href\""); } @Test @@ -64,9 +61,9 @@ public class SampleHateoasApplicationTests { URI.create("http://localhost:" + this.port + "/customers/1")); ResponseEntity<String> response = new TestRestTemplate().exchange(request, String.class); - assertThat(response.getStatusCode(), equalTo(HttpStatus.OK)); - assertThat(response.getHeaders().getContentType(), - equalTo(MediaType.parseMediaType("application/json;charset=UTF-8"))); + assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK); + assertThat(response.getHeaders().getContentType()) + .isEqualTo(MediaType.parseMediaType("application/json;charset=UTF-8")); } } diff --git a/spring-boot-samples/spring-boot-sample-hypermedia-jpa/src/test/java/sample/hypermedia/jpa/SampleHypermediaJpaApplicationIntegrationTests.java b/spring-boot-samples/spring-boot-sample-hypermedia-jpa/src/test/java/sample/hypermedia/jpa/SampleHypermediaJpaApplicationIntegrationTests.java index 67896386b7..f279a28fb2 100644 --- a/spring-boot-samples/spring-boot-sample-hypermedia-jpa/src/test/java/sample/hypermedia/jpa/SampleHypermediaJpaApplicationIntegrationTests.java +++ b/spring-boot-samples/spring-boot-sample-hypermedia-jpa/src/test/java/sample/hypermedia/jpa/SampleHypermediaJpaApplicationIntegrationTests.java @@ -31,7 +31,7 @@ import org.springframework.test.web.servlet.MvcResult; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; -import static org.junit.Assert.assertEquals; +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.jsonPath; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @@ -83,8 +83,8 @@ public class SampleHypermediaJpaApplicationIntegrationTests { public void browser() throws Exception { MvcResult response = this.mockMvc.perform(get("/").accept(MediaType.TEXT_HTML)) .andExpect(status().isFound()).andReturn(); - assertEquals("/browser/index.html#", - response.getResponse().getHeaders("location").get(0)); + assertThat(response.getResponse().getHeaders("location").get(0)) + .isEqualTo("/browser/index.html#"); } } diff --git a/spring-boot-samples/spring-boot-sample-hypermedia-ui/src/test/java/sample/hypermedia/ui/SampleHypermediaUiApplicationTests.java b/spring-boot-samples/spring-boot-sample-hypermedia-ui/src/test/java/sample/hypermedia/ui/SampleHypermediaUiApplicationTests.java index 342fde1a53..da90ecbd8c 100644 --- a/spring-boot-samples/spring-boot-sample-hypermedia-ui/src/test/java/sample/hypermedia/ui/SampleHypermediaUiApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-hypermedia-ui/src/test/java/sample/hypermedia/ui/SampleHypermediaUiApplicationTests.java @@ -33,7 +33,7 @@ import org.springframework.http.RequestEntity; import org.springframework.http.ResponseEntity; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(SampleHypermediaUiApplication.class) @@ -47,14 +47,14 @@ public class SampleHypermediaUiApplicationTests { public void home() { String response = new TestRestTemplate() .getForObject("http://localhost:" + this.port, String.class); - assertTrue("Wrong body: " + response, response.contains("Hello World")); + assertThat(response).contains("Hello World"); } @Test public void links() { String response = new TestRestTemplate().getForObject( "http://localhost:" + this.port + "/actuator", String.class); - assertTrue("Wrong body: " + response, response.contains("\"_links\":")); + assertThat(response).contains("\"_links\":"); } @Test @@ -65,7 +65,7 @@ public class SampleHypermediaUiApplicationTests { new RequestEntity<Void>(headers, HttpMethod.GET, new URI("http://localhost:" + this.port + "/actuator")), String.class); - assertTrue("Wrong body: " + response, response.getBody().contains("\"_links\":")); + assertThat(response.getBody()).contains("\"_links\":"); } @Test @@ -75,7 +75,7 @@ public class SampleHypermediaUiApplicationTests { ResponseEntity<String> response = new TestRestTemplate() .exchange(new RequestEntity<Void>(headers, HttpMethod.GET, new URI("http://localhost:" + this.port)), String.class); - assertTrue("Wrong body: " + response, response.getBody().contains("Hello World")); + assertThat(response.getBody()).contains("Hello World"); } } diff --git a/spring-boot-samples/spring-boot-sample-hypermedia/src/test/java/sample/hypermedia/SampleHypermediaApplicationHomePageTests.java b/spring-boot-samples/spring-boot-sample-hypermedia/src/test/java/sample/hypermedia/SampleHypermediaApplicationHomePageTests.java index d5a4f936ac..0bd29ab243 100644 --- a/spring-boot-samples/spring-boot-sample-hypermedia/src/test/java/sample/hypermedia/SampleHypermediaApplicationHomePageTests.java +++ b/spring-boot-samples/spring-boot-sample-hypermedia/src/test/java/sample/hypermedia/SampleHypermediaApplicationHomePageTests.java @@ -33,7 +33,7 @@ import org.springframework.http.RequestEntity; import org.springframework.http.ResponseEntity; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(SampleHypermediaApplication.class) @@ -47,7 +47,7 @@ public class SampleHypermediaApplicationHomePageTests { public void home() { String response = new TestRestTemplate() .getForObject("http://localhost:" + this.port, String.class); - assertTrue("Wrong body: " + response, response.contains("404")); + assertThat(response).contains("404"); } @Test @@ -58,7 +58,7 @@ public class SampleHypermediaApplicationHomePageTests { new RequestEntity<Void>(headers, HttpMethod.GET, new URI("http://localhost:" + this.port + "/actuator")), String.class); - assertTrue("Wrong body: " + response, response.getBody().contains("\"_links\":")); + assertThat(response.getBody()).contains("\"_links\":"); } @Test @@ -69,7 +69,7 @@ public class SampleHypermediaApplicationHomePageTests { new RequestEntity<Void>(headers, HttpMethod.GET, new URI("http://localhost:" + this.port + "/actuator/")), String.class); - assertTrue("Wrong body: " + response, response.getBody().contains("HAL Browser")); + assertThat(response.getBody()).contains("HAL Browser"); } } diff --git a/spring-boot-samples/spring-boot-sample-integration/src/test/java/sample/integration/consumer/SampleIntegrationApplicationTests.java b/spring-boot-samples/spring-boot-sample-integration/src/test/java/sample/integration/consumer/SampleIntegrationApplicationTests.java index a81df0a3fa..2ba25ca58f 100644 --- a/spring-boot-samples/spring-boot-sample-integration/src/test/java/sample/integration/consumer/SampleIntegrationApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-integration/src/test/java/sample/integration/consumer/SampleIntegrationApplicationTests.java @@ -38,7 +38,7 @@ import org.springframework.core.io.support.ResourcePatternUtils; import org.springframework.util.FileSystemUtils; import org.springframework.util.StreamUtils; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * Basic integration tests for service demo application. @@ -71,7 +71,7 @@ public class SampleIntegrationApplicationTests { public void testVanillaExchange() throws Exception { SpringApplication.run(ProducerApplication.class, "World"); String output = getOutput(); - assertTrue("Wrong output: " + output, output.contains("Hello World")); + assertThat(output).contains("Hello World"); } private String getOutput() throws Exception { diff --git a/spring-boot-samples/spring-boot-sample-jersey/src/test/java/sample/jersey/SampleJerseyApplicationTests.java b/spring-boot-samples/spring-boot-sample-jersey/src/test/java/sample/jersey/SampleJerseyApplicationTests.java index 16d47f6208..e6c3e47235 100644 --- a/spring-boot-samples/spring-boot-sample-jersey/src/test/java/sample/jersey/SampleJerseyApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-jersey/src/test/java/sample/jersey/SampleJerseyApplicationTests.java @@ -28,7 +28,7 @@ import org.springframework.http.ResponseEntity; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.web.client.RestTemplate; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(SampleJerseyApplication.class) @@ -44,22 +44,22 @@ public class SampleJerseyApplicationTests { public void contextLoads() { ResponseEntity<String> entity = this.restTemplate .getForEntity("http://localhost:" + this.port + "/hello", String.class); - assertEquals(HttpStatus.OK, entity.getStatusCode()); + assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); } @Test public void reverse() { ResponseEntity<String> entity = this.restTemplate.getForEntity( "http://localhost:" + this.port + "/reverse?input=olleh", String.class); - assertEquals(HttpStatus.OK, entity.getStatusCode()); - assertEquals("hello", entity.getBody()); + assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); + assertThat(entity.getBody()).isEqualTo("hello"); } @Test public void validation() { ResponseEntity<String> entity = this.restTemplate .getForEntity("http://localhost:" + this.port + "/reverse", String.class); - assertEquals(HttpStatus.BAD_REQUEST, entity.getStatusCode()); + assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.BAD_REQUEST); } } diff --git a/spring-boot-samples/spring-boot-sample-jersey1/src/test/java/sample/jersey1/SampleJersey1ApplicationTests.java b/spring-boot-samples/spring-boot-sample-jersey1/src/test/java/sample/jersey1/SampleJersey1ApplicationTests.java index 4f7a5e8815..4e1825f083 100644 --- a/spring-boot-samples/spring-boot-sample-jersey1/src/test/java/sample/jersey1/SampleJersey1ApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-jersey1/src/test/java/sample/jersey1/SampleJersey1ApplicationTests.java @@ -25,7 +25,7 @@ import org.springframework.boot.test.TestRestTemplate; import org.springframework.boot.test.WebIntegrationTest; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(SampleJersey1Application.class) @@ -37,8 +37,9 @@ public class SampleJersey1ApplicationTests { @Test public void contextLoads() { - assertEquals("Hello World", new TestRestTemplate() - .getForObject("http://localhost:" + this.port + "/", String.class)); + assertThat(new TestRestTemplate() + .getForObject("http://localhost:" + this.port + "/", String.class)) + .isEqualTo("Hello World"); } } diff --git a/spring-boot-samples/spring-boot-sample-jetty-ssl/src/test/java/sample/jetty/ssl/SampleJettySslApplicationTests.java b/spring-boot-samples/spring-boot-sample-jetty-ssl/src/test/java/sample/jetty/ssl/SampleJettySslApplicationTests.java index 2c522463f9..d3910b8b31 100644 --- a/spring-boot-samples/spring-boot-sample-jetty-ssl/src/test/java/sample/jetty/ssl/SampleJettySslApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-jetty-ssl/src/test/java/sample/jetty/ssl/SampleJettySslApplicationTests.java @@ -34,7 +34,7 @@ import org.springframework.http.client.HttpComponentsClientHttpRequestFactory; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * Basic integration tests for demo application. @@ -64,8 +64,8 @@ public class SampleJettySslApplicationTests { .setHttpClient(httpClient); ResponseEntity<String> entity = testRestTemplate .getForEntity("https://localhost:" + this.port, String.class); - assertEquals(HttpStatus.OK, entity.getStatusCode()); - assertEquals("Hello World", entity.getBody()); + assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); + assertThat(entity.getBody()).isEqualTo("Hello World"); } } diff --git a/spring-boot-samples/spring-boot-sample-jetty/src/test/java/sample/jetty/SampleJettyApplicationTests.java b/spring-boot-samples/spring-boot-sample-jetty/src/test/java/sample/jetty/SampleJettyApplicationTests.java index 75dcb45166..7401038e57 100644 --- a/spring-boot-samples/spring-boot-sample-jetty/src/test/java/sample/jetty/SampleJettyApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-jetty/src/test/java/sample/jetty/SampleJettyApplicationTests.java @@ -37,7 +37,7 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.util.StreamUtils; import org.springframework.web.client.RestTemplate; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * Basic integration tests for demo application. @@ -58,8 +58,8 @@ public class SampleJettyApplicationTests { public void testHome() throws Exception { ResponseEntity<String> entity = new TestRestTemplate() .getForEntity("http://localhost:" + this.port, String.class); - assertEquals(HttpStatus.OK, entity.getStatusCode()); - assertEquals("Hello World", entity.getBody()); + assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); + assertThat(entity.getBody()).isEqualTo("Hello World"); } @Test @@ -74,13 +74,13 @@ public class SampleJettyApplicationTests { "http://localhost:" + this.port, HttpMethod.GET, requestEntity, byte[].class); - assertEquals(HttpStatus.OK, entity.getStatusCode()); + assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); GZIPInputStream inflater = new GZIPInputStream( new ByteArrayInputStream(entity.getBody())); try { - assertEquals("Hello World", - StreamUtils.copyToString(inflater, Charset.forName("UTF-8"))); + assertThat(StreamUtils.copyToString(inflater, Charset.forName("UTF-8"))) + .isEqualTo("Hello World"); } finally { inflater.close(); diff --git a/spring-boot-samples/spring-boot-sample-jetty8-ssl/src/test/java/sample/jetty8/ssl/SampleJetty8SslApplicationTests.java b/spring-boot-samples/spring-boot-sample-jetty8-ssl/src/test/java/sample/jetty8/ssl/SampleJetty8SslApplicationTests.java index 7d0cfa474d..c70b9898e7 100644 --- a/spring-boot-samples/spring-boot-sample-jetty8-ssl/src/test/java/sample/jetty8/ssl/SampleJetty8SslApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-jetty8-ssl/src/test/java/sample/jetty8/ssl/SampleJetty8SslApplicationTests.java @@ -34,7 +34,7 @@ import org.springframework.http.client.HttpComponentsClientHttpRequestFactory; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * Basic integration tests for demo application. @@ -64,8 +64,8 @@ public class SampleJetty8SslApplicationTests { .setHttpClient(httpClient); ResponseEntity<String> entity = testRestTemplate .getForEntity("https://localhost:" + this.port, String.class); - assertEquals(HttpStatus.OK, entity.getStatusCode()); - assertEquals("Hello World", entity.getBody()); + assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); + assertThat(entity.getBody()).isEqualTo("Hello World"); } } diff --git a/spring-boot-samples/spring-boot-sample-jetty8/src/test/java/sample/jetty8/SampleJetty8ApplicationTests.java b/spring-boot-samples/spring-boot-sample-jetty8/src/test/java/sample/jetty8/SampleJetty8ApplicationTests.java index 60f77b7b04..3b9b676565 100644 --- a/spring-boot-samples/spring-boot-sample-jetty8/src/test/java/sample/jetty8/SampleJetty8ApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-jetty8/src/test/java/sample/jetty8/SampleJetty8ApplicationTests.java @@ -37,7 +37,7 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.util.StreamUtils; import org.springframework.web.client.RestTemplate; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * Basic integration tests for demo application. @@ -58,8 +58,8 @@ public class SampleJetty8ApplicationTests { public void testHome() throws Exception { ResponseEntity<String> entity = new TestRestTemplate() .getForEntity("http://localhost:" + this.port, String.class); - assertEquals(HttpStatus.OK, entity.getStatusCode()); - assertEquals("Hello World", entity.getBody()); + assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); + assertThat(entity.getBody()).isEqualTo("Hello World"); } @Test @@ -71,12 +71,12 @@ public class SampleJetty8ApplicationTests { ResponseEntity<byte[]> entity = restTemplate.exchange( "http://localhost:" + this.port, HttpMethod.GET, requestEntity, byte[].class); - assertEquals(HttpStatus.OK, entity.getStatusCode()); + assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); GZIPInputStream inflater = new GZIPInputStream( new ByteArrayInputStream(entity.getBody())); try { - assertEquals("Hello World", - StreamUtils.copyToString(inflater, Charset.forName("UTF-8"))); + assertThat(StreamUtils.copyToString(inflater, Charset.forName("UTF-8"))) + .isEqualTo("Hello World"); } finally { inflater.close(); diff --git a/spring-boot-samples/spring-boot-sample-jetty93/src/test/java/sample/jetty93/SampleJetty93ApplicationTests.java b/spring-boot-samples/spring-boot-sample-jetty93/src/test/java/sample/jetty93/SampleJetty93ApplicationTests.java index 0112a97616..8e135eb6a4 100644 --- a/spring-boot-samples/spring-boot-sample-jetty93/src/test/java/sample/jetty93/SampleJetty93ApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-jetty93/src/test/java/sample/jetty93/SampleJetty93ApplicationTests.java @@ -37,7 +37,7 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.util.StreamUtils; import org.springframework.web.client.RestTemplate; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * Basic integration tests for demo application. @@ -58,8 +58,8 @@ public class SampleJetty93ApplicationTests { public void testHome() throws Exception { ResponseEntity<String> entity = new TestRestTemplate() .getForEntity("http://localhost:" + this.port, String.class); - assertEquals(HttpStatus.OK, entity.getStatusCode()); - assertEquals("Hello World", entity.getBody()); + assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); + assertThat(entity.getBody()).isEqualTo("Hello World"); } @Test @@ -71,12 +71,12 @@ public class SampleJetty93ApplicationTests { ResponseEntity<byte[]> entity = restTemplate.exchange( "http://localhost:" + this.port, HttpMethod.GET, requestEntity, byte[].class); - assertEquals(HttpStatus.OK, entity.getStatusCode()); + assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); GZIPInputStream inflater = new GZIPInputStream( new ByteArrayInputStream(entity.getBody())); try { - assertEquals("Hello World", - StreamUtils.copyToString(inflater, Charset.forName("UTF-8"))); + assertThat(StreamUtils.copyToString(inflater, Charset.forName("UTF-8"))) + .isEqualTo("Hello World"); } finally { inflater.close(); diff --git a/spring-boot-samples/spring-boot-sample-jooq/src/test/java/sample/jooq/SampleJooqApplicationTests.java b/spring-boot-samples/spring-boot-sample-jooq/src/test/java/sample/jooq/SampleJooqApplicationTests.java index d6c222fe24..178192fadd 100644 --- a/spring-boot-samples/spring-boot-sample-jooq/src/test/java/sample/jooq/SampleJooqApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-jooq/src/test/java/sample/jooq/SampleJooqApplicationTests.java @@ -21,8 +21,7 @@ import org.junit.Test; import org.springframework.boot.test.OutputCapture; -import static org.hamcrest.Matchers.containsString; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; /** * Integration tests for {@link SampleJooqApplication}. @@ -37,11 +36,11 @@ public class SampleJooqApplicationTests { @Test public void outputResults() throws Exception { SampleJooqApplication.main(NO_ARGS); - assertThat(this.out.toString(), containsString("jOOQ Fetch 1 Greg Turnquest")); - assertThat(this.out.toString(), containsString("jOOQ Fetch 2 Craig Walls")); - assertThat(this.out.toString(), - containsString("jOOQ SQL " + "[Learning Spring Boot : Greg Turnquest, " - + "Spring Boot in Action : Craig Walls]")); + assertThat(this.out.toString()).contains("jOOQ Fetch 1 Greg Turnquest"); + assertThat(this.out.toString()).contains("jOOQ Fetch 2 Craig Walls"); + assertThat(this.out.toString()) + .contains("jOOQ SQL " + "[Learning Spring Boot : Greg Turnquest, " + + "Spring Boot in Action : Craig Walls]"); } } diff --git a/spring-boot-samples/spring-boot-sample-jpa/src/test/java/sample/jpa/repository/JpaNoteRepositoryIntegrationTests.java b/spring-boot-samples/spring-boot-sample-jpa/src/test/java/sample/jpa/repository/JpaNoteRepositoryIntegrationTests.java index 28044e811c..b4c2dd8432 100644 --- a/spring-boot-samples/spring-boot-sample-jpa/src/test/java/sample/jpa/repository/JpaNoteRepositoryIntegrationTests.java +++ b/spring-boot-samples/spring-boot-sample-jpa/src/test/java/sample/jpa/repository/JpaNoteRepositoryIntegrationTests.java @@ -26,7 +26,7 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.SpringApplicationConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * Integration tests for {@link JpaNoteRepository}. @@ -43,7 +43,7 @@ public class JpaNoteRepositoryIntegrationTests { @Test public void findsAllNotes() { List<Note> notes = this.repository.findAll(); - assertEquals(4, notes.size()); + assertThat(notes).hasSize(4); } } diff --git a/spring-boot-samples/spring-boot-sample-jpa/src/test/java/sample/jpa/repository/JpaTagRepositoryIntegrationTests.java b/spring-boot-samples/spring-boot-sample-jpa/src/test/java/sample/jpa/repository/JpaTagRepositoryIntegrationTests.java index 404fd7bc66..83d59c96cc 100644 --- a/spring-boot-samples/spring-boot-sample-jpa/src/test/java/sample/jpa/repository/JpaTagRepositoryIntegrationTests.java +++ b/spring-boot-samples/spring-boot-sample-jpa/src/test/java/sample/jpa/repository/JpaTagRepositoryIntegrationTests.java @@ -26,7 +26,7 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.SpringApplicationConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * Integration tests for {@link JpaTagRepository}. @@ -43,7 +43,7 @@ public class JpaTagRepositoryIntegrationTests { @Test public void findsAllTags() { List<Tag> tags = this.repository.findAll(); - assertEquals(3, tags.size()); + assertThat(tags).hasSize(3); } } diff --git a/spring-boot-samples/spring-boot-sample-jta-atomikos/src/test/java/sample/atomikos/SampleAtomikosApplicationTests.java b/spring-boot-samples/spring-boot-sample-jta-atomikos/src/test/java/sample/atomikos/SampleAtomikosApplicationTests.java index 38d688d1c8..519e6c413a 100644 --- a/spring-boot-samples/spring-boot-sample-jta-atomikos/src/test/java/sample/atomikos/SampleAtomikosApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-jta-atomikos/src/test/java/sample/atomikos/SampleAtomikosApplicationTests.java @@ -16,14 +16,13 @@ package sample.atomikos; -import org.hamcrest.Matcher; -import org.hamcrest.core.SubstringMatcher; +import org.assertj.core.api.Condition; import org.junit.Rule; import org.junit.Test; import org.springframework.boot.test.OutputCapture; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; /** * Basic integration tests for demo application. @@ -39,25 +38,22 @@ public class SampleAtomikosApplicationTests { public void testTransactionRollback() throws Exception { SampleAtomikosApplication.main(new String[] {}); String output = this.outputCapture.toString(); - assertThat(output, containsString(1, "---->")); - assertThat(output, containsString(1, "----> josh")); - assertThat(output, containsString(2, "Count is 1")); - assertThat(output, containsString(1, "Simulated error")); + assertThat(output).has(substring(1, "---->")); + assertThat(output).has(substring(1, "----> josh")); + assertThat(output).has(substring(2, "Count is 1")); + assertThat(output).has(substring(1, "Simulated error")); } - private Matcher<? super String> containsString(final int times, String s) { - return new SubstringMatcher(s) { + private Condition<String> substring(final int times, final String substring) { + return new Condition<String>( + "containing '" + substring + "' " + times + " times") { @Override - protected String relationship() { - return "containing " + times + " times"; - } - - @Override - protected boolean evalSubstringOf(String s) { + public boolean matches(String value) { int i = 0; - while (s.contains(this.substring)) { - s = s.substring(s.indexOf(this.substring) + this.substring.length()); + while (value.contains(substring)) { + int beginIndex = value.indexOf(substring) + substring.length(); + value = value.substring(beginIndex); i++; } return i == times; diff --git a/spring-boot-samples/spring-boot-sample-jta-bitronix/src/test/java/sample/bitronix/SampleBitronixApplicationTests.java b/spring-boot-samples/spring-boot-sample-jta-bitronix/src/test/java/sample/bitronix/SampleBitronixApplicationTests.java index 140df19905..b56bd98c62 100644 --- a/spring-boot-samples/spring-boot-sample-jta-bitronix/src/test/java/sample/bitronix/SampleBitronixApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-jta-bitronix/src/test/java/sample/bitronix/SampleBitronixApplicationTests.java @@ -17,8 +17,7 @@ package sample.bitronix; import bitronix.tm.resource.jms.PoolingConnectionFactory; -import org.hamcrest.Matcher; -import org.hamcrest.core.SubstringMatcher; +import org.assertj.core.api.Condition; import org.junit.Rule; import org.junit.Test; @@ -26,10 +25,7 @@ import org.springframework.boot.SpringApplication; import org.springframework.boot.test.OutputCapture; import org.springframework.context.ApplicationContext; -import static org.hamcrest.Matchers.instanceOf; -import static org.hamcrest.Matchers.not; -import static org.hamcrest.Matchers.sameInstance; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; /** * Basic integration tests for demo application. @@ -45,10 +41,10 @@ public class SampleBitronixApplicationTests { public void testTransactionRollback() throws Exception { SampleBitronixApplication.main(new String[] {}); String output = this.outputCapture.toString(); - assertThat(output, containsString(1, "---->")); - assertThat(output, containsString(1, "----> josh")); - assertThat(output, containsString(2, "Count is 1")); - assertThat(output, containsString(1, "Simulated error")); + assertThat(output).has(substring(1, "---->")); + assertThat(output).has(substring(1, "----> josh")); + assertThat(output).has(substring(2, "Count is 1")); + assertThat(output).has(substring(1, "Simulated error")); } @Test @@ -58,25 +54,22 @@ public class SampleBitronixApplicationTests { Object jmsConnectionFactory = context.getBean("jmsConnectionFactory"); Object xaJmsConnectionFactory = context.getBean("xaJmsConnectionFactory"); Object nonXaJmsConnectionFactory = context.getBean("nonXaJmsConnectionFactory"); - assertThat(jmsConnectionFactory, sameInstance(xaJmsConnectionFactory)); - assertThat(jmsConnectionFactory, instanceOf(PoolingConnectionFactory.class)); - assertThat(nonXaJmsConnectionFactory, - not(instanceOf(PoolingConnectionFactory.class))); + assertThat(jmsConnectionFactory).isSameAs(xaJmsConnectionFactory); + assertThat(jmsConnectionFactory).isInstanceOf(PoolingConnectionFactory.class); + assertThat(nonXaJmsConnectionFactory) + .isNotInstanceOf(PoolingConnectionFactory.class); } - private Matcher<? super String> containsString(final int times, String s) { - return new SubstringMatcher(s) { + private Condition<String> substring(final int times, final String substring) { + return new Condition<String>( + "containing '" + substring + "' " + times + " times") { @Override - protected String relationship() { - return "containing " + times + " times"; - } - - @Override - protected boolean evalSubstringOf(String s) { + public boolean matches(String value) { int i = 0; - while (s.contains(this.substring)) { - s = s.substring(s.indexOf(this.substring) + this.substring.length()); + while (value.contains(substring)) { + int beginIndex = value.indexOf(substring) + substring.length(); + value = value.substring(beginIndex); i++; } return i == times; diff --git a/spring-boot-samples/spring-boot-sample-liquibase/src/test/java/sample/liquibase/SampleLiquibaseApplicationTests.java b/spring-boot-samples/spring-boot-sample-liquibase/src/test/java/sample/liquibase/SampleLiquibaseApplicationTests.java index e33231cf73..331eb65dd6 100644 --- a/spring-boot-samples/spring-boot-sample-liquibase/src/test/java/sample/liquibase/SampleLiquibaseApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-liquibase/src/test/java/sample/liquibase/SampleLiquibaseApplicationTests.java @@ -24,7 +24,7 @@ import org.junit.Test; import org.springframework.boot.test.OutputCapture; import org.springframework.core.NestedCheckedException; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; public class SampleLiquibaseApplicationTests { @@ -42,23 +42,22 @@ public class SampleLiquibaseApplicationTests { } } String output = this.outputCapture.toString(); - assertTrue("Wrong output: " + output, - output.contains("Successfully acquired change log lock") - && output.contains("Creating database history " - + "table with name: PUBLIC.DATABASECHANGELOG") - && output.contains("Table person created") - && output.contains("ChangeSet classpath:/db/" + assertThat(output).contains("Successfully acquired change log lock") + .contains("Creating database history " + + "table with name: PUBLIC.DATABASECHANGELOG") + .contains("Table person created") + .contains("ChangeSet classpath:/db/" + "changelog/db.changelog-master.yaml::1::" + "marceloverdijk ran successfully") - && output.contains("New row inserted into person") - && output.contains("ChangeSet classpath:/db/changelog/" + .contains("New row inserted into person") + .contains("ChangeSet classpath:/db/changelog/" + "db.changelog-master.yaml::2::" + "marceloverdijk ran successfully") - && output.contains("Successfully released change log lock")); + .contains("Successfully released change log lock"); } + @SuppressWarnings("serial") private boolean serverNotRunning(IllegalStateException ex) { - @SuppressWarnings("serial") NestedCheckedException nested = new NestedCheckedException("failed", ex) { }; if (nested.contains(ConnectException.class)) { diff --git a/spring-boot-samples/spring-boot-sample-metrics-dropwizard/src/test/java/sample/metrics/dropwizard/SampleDropwizardMetricsApplicationTests.java b/spring-boot-samples/spring-boot-sample-metrics-dropwizard/src/test/java/sample/metrics/dropwizard/SampleDropwizardMetricsApplicationTests.java index 8ec62f11e4..9ec6b54af5 100644 --- a/spring-boot-samples/spring-boot-sample-metrics-dropwizard/src/test/java/sample/metrics/dropwizard/SampleDropwizardMetricsApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-metrics-dropwizard/src/test/java/sample/metrics/dropwizard/SampleDropwizardMetricsApplicationTests.java @@ -27,7 +27,7 @@ import org.springframework.boot.test.WebIntegrationTest; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * Basic integration tests for {@link SampleDropwizardMetricsApplication}. @@ -49,7 +49,7 @@ public class SampleDropwizardMetricsApplicationTests { @Test public void timerCreated() { this.gauges.submit("timer.test", 1234); - assertEquals(1, this.registry.getTimers().get("timer.test").getCount()); + assertThat(this.registry.getTimers().get("timer.test").getCount()).isEqualTo(1); } } diff --git a/spring-boot-samples/spring-boot-sample-profile/src/test/java/sample/profile/SampleProfileApplicationTests.java b/spring-boot-samples/spring-boot-sample-profile/src/test/java/sample/profile/SampleProfileApplicationTests.java index a252afa4c6..0548159001 100644 --- a/spring-boot-samples/spring-boot-sample-profile/src/test/java/sample/profile/SampleProfileApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-profile/src/test/java/sample/profile/SampleProfileApplicationTests.java @@ -23,7 +23,7 @@ import org.junit.Test; import org.springframework.boot.test.OutputCapture; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; public class SampleProfileApplicationTests { @@ -51,7 +51,7 @@ public class SampleProfileApplicationTests { public void testDefaultProfile() throws Exception { SampleProfileApplication.main(new String[0]); String output = this.outputCapture.toString(); - assertTrue("Wrong output: " + output, output.contains("Hello Phil")); + assertThat(output).contains("Hello Phil"); } @Test @@ -59,7 +59,7 @@ public class SampleProfileApplicationTests { System.setProperty("spring.profiles.active", "goodbye"); SampleProfileApplication.main(new String[0]); String output = this.outputCapture.toString(); - assertTrue("Wrong output: " + output, output.contains("Goodbye Everyone")); + assertThat(output).contains("Goodbye Everyone"); } @Test @@ -73,7 +73,7 @@ public class SampleProfileApplicationTests { System.setProperty("spring.profiles.active", "generic"); SampleProfileApplication.main(new String[0]); String output = this.outputCapture.toString(); - assertTrue("Wrong output: " + output, output.contains("Bonjour Phil")); + assertThat(output).contains("Bonjour Phil"); } @Test @@ -81,7 +81,7 @@ public class SampleProfileApplicationTests { SampleProfileApplication .main(new String[] { "--spring.profiles.active=goodbye" }); String output = this.outputCapture.toString(); - assertTrue("Wrong output: " + output, output.contains("Goodbye Everyone")); + assertThat(output).contains("Goodbye Everyone"); } } diff --git a/spring-boot-samples/spring-boot-sample-property-validation/src/test/java/sample/propertyvalidation/SamplePropertyValidationApplicationTests.java b/spring-boot-samples/spring-boot-sample-property-validation/src/test/java/sample/propertyvalidation/SamplePropertyValidationApplicationTests.java index 0f8defc904..885463e3ce 100644 --- a/spring-boot-samples/spring-boot-sample-property-validation/src/test/java/sample/propertyvalidation/SamplePropertyValidationApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-property-validation/src/test/java/sample/propertyvalidation/SamplePropertyValidationApplicationTests.java @@ -26,7 +26,7 @@ import org.springframework.boot.autoconfigure.web.ServerProperties; import org.springframework.boot.test.EnvironmentTestUtils; import org.springframework.context.annotation.AnnotationConfigApplicationContext; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link SamplePropertyValidationApplication}. @@ -53,8 +53,8 @@ public class SamplePropertyValidationApplicationTests { "sample.port:9090"); this.context.refresh(); SampleProperties properties = this.context.getBean(SampleProperties.class); - assertEquals("192.168.0.1", properties.getHost()); - assertEquals(Integer.valueOf(9090), properties.getPort()); + assertThat(properties.getHost()).isEqualTo("192.168.0.1"); + assertThat(properties.getPort()).isEqualTo(Integer.valueOf(9090)); } @Test @@ -84,8 +84,8 @@ public class SamplePropertyValidationApplicationTests { "sample.port:9090"); this.context.refresh(); SampleProperties properties = this.context.getBean(SampleProperties.class); - assertEquals("192.168.0.1", properties.getHost()); - assertEquals(Integer.valueOf(9090), properties.getPort()); + assertThat(properties.getHost()).isEqualTo("192.168.0.1"); + assertThat(properties.getPort()).isEqualTo(Integer.valueOf(9090)); } } diff --git a/spring-boot-samples/spring-boot-sample-secure-oauth2/src/test/java/sample/secure/oauth2/SampleSecureOAuth2ApplicationTests.java b/spring-boot-samples/spring-boot-sample-secure-oauth2/src/test/java/sample/secure/oauth2/SampleSecureOAuth2ApplicationTests.java index 49c2f3d297..92a5c352f3 100644 --- a/spring-boot-samples/spring-boot-sample-secure-oauth2/src/test/java/sample/secure/oauth2/SampleSecureOAuth2ApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-secure-oauth2/src/test/java/sample/secure/oauth2/SampleSecureOAuth2ApplicationTests.java @@ -20,8 +20,7 @@ import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.MvcResult; import org.springframework.web.context.WebApplicationContext; -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.MatcherAssert.assertThat; +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.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; @@ -100,11 +99,11 @@ public class SampleSecureOAuth2ApplicationTests { Flight flight = this.objectMapper.readValue( flightsAction.getResponse().getContentAsString(), Flight.class); - assertThat(flight.getOrigin(), is("Nashville")); - assertThat(flight.getDestination(), is("Dallas")); - assertThat(flight.getAirline(), is("Spring Ways")); - assertThat(flight.getFlightNumber(), is("OAUTH2")); - assertThat(flight.getTraveler(), is("Greg Turnquist")); + assertThat(flight.getOrigin()).isEqualTo("Nashville"); + assertThat(flight.getDestination()).isEqualTo("Dallas"); + assertThat(flight.getAirline()).isEqualTo("Spring Ways"); + assertThat(flight.getFlightNumber()).isEqualTo("OAUTH2"); + assertThat(flight.getTraveler()).isEqualTo("Greg Turnquist"); } } diff --git a/spring-boot-samples/spring-boot-sample-secure/src/test/java/sample/secure/SampleSecureApplicationTests.java b/spring-boot-samples/spring-boot-sample-secure/src/test/java/sample/secure/SampleSecureApplicationTests.java index 689da7112f..6eed7b6d12 100644 --- a/spring-boot-samples/spring-boot-sample-secure/src/test/java/sample/secure/SampleSecureApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-secure/src/test/java/sample/secure/SampleSecureApplicationTests.java @@ -35,7 +35,7 @@ import org.springframework.security.core.AuthenticationException; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * Basic integration tests for demo application. @@ -70,25 +70,25 @@ public class SampleSecureApplicationTests { @Test(expected = AuthenticationException.class) public void secure() throws Exception { - assertEquals(this.service.secure(), "Hello Security"); + assertThat("Hello Security").isEqualTo(this.service.secure()); } @Test public void authenticated() throws Exception { SecurityContextHolder.getContext().setAuthentication(this.authentication); - assertEquals(this.service.secure(), "Hello Security"); + assertThat("Hello Security").isEqualTo(this.service.secure()); } @Test public void preauth() throws Exception { SecurityContextHolder.getContext().setAuthentication(this.authentication); - assertEquals(this.service.authorized(), "Hello World"); + assertThat("Hello World").isEqualTo(this.service.authorized()); } @Test(expected = AccessDeniedException.class) public void denied() throws Exception { SecurityContextHolder.getContext().setAuthentication(this.authentication); - assertEquals(this.service.denied(), "Goodbye World"); + assertThat("Goodbye World").isEqualTo(this.service.denied()); } @PropertySource("classpath:test.properties") diff --git a/spring-boot-samples/spring-boot-sample-servlet/src/test/java/sample/servlet/SampleServletApplicationTests.java b/spring-boot-samples/spring-boot-sample-servlet/src/test/java/sample/servlet/SampleServletApplicationTests.java index 2b727d7b95..b206aac81c 100644 --- a/spring-boot-samples/spring-boot-sample-servlet/src/test/java/sample/servlet/SampleServletApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-servlet/src/test/java/sample/servlet/SampleServletApplicationTests.java @@ -30,7 +30,7 @@ import org.springframework.http.ResponseEntity; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * Basic integration tests for demo application. @@ -53,15 +53,15 @@ public class SampleServletApplicationTests { public void testHomeIsSecure() throws Exception { ResponseEntity<String> entity = new TestRestTemplate() .getForEntity("http://localhost:" + this.port, String.class); - assertEquals(HttpStatus.UNAUTHORIZED, entity.getStatusCode()); + assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED); } @Test public void testHome() throws Exception { ResponseEntity<String> entity = new TestRestTemplate("user", getPassword()) .getForEntity("http://localhost:" + this.port, String.class); - assertEquals(HttpStatus.OK, entity.getStatusCode()); - assertEquals("Hello World", entity.getBody()); + assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); + assertThat(entity.getBody()).isEqualTo("Hello World"); } private String getPassword() { diff --git a/spring-boot-samples/spring-boot-sample-session-redis/src/test/java/sample/session/redis/SampleSessionRedisApplicationTests.java b/spring-boot-samples/spring-boot-sample-session-redis/src/test/java/sample/session/redis/SampleSessionRedisApplicationTests.java index 3b20c126fa..3a58faeb71 100644 --- a/spring-boot-samples/spring-boot-sample-session-redis/src/test/java/sample/session/redis/SampleSessionRedisApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-session-redis/src/test/java/sample/session/redis/SampleSessionRedisApplicationTests.java @@ -30,10 +30,7 @@ import org.springframework.http.RequestEntity; import org.springframework.http.ResponseEntity; import org.springframework.web.client.RestTemplate; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.not; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link SampleSessionRedisApplication}. @@ -73,12 +70,12 @@ public class SampleSessionRedisApplicationTests { HttpMethod.GET, uri); String uuid2 = restTemplate.exchange(request, String.class).getBody(); - assertThat(uuid1, is(equalTo(uuid2))); + assertThat(uuid1).isEqualTo(uuid2); Thread.sleep(5000); String uuid3 = restTemplate.exchange(request, String.class).getBody(); - assertThat(uuid2, is(not(equalTo(uuid3)))); + assertThat(uuid2).isNotEqualTo(uuid3); } private boolean redisServerRunning(Throwable ex) { diff --git a/spring-boot-samples/spring-boot-sample-simple/src/test/java/sample/simple/SampleSimpleApplicationTests.java b/spring-boot-samples/spring-boot-sample-simple/src/test/java/sample/simple/SampleSimpleApplicationTests.java index e885d91be1..33e47903b2 100644 --- a/spring-boot-samples/spring-boot-sample-simple/src/test/java/sample/simple/SampleSimpleApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-simple/src/test/java/sample/simple/SampleSimpleApplicationTests.java @@ -23,7 +23,7 @@ import org.junit.Test; import org.springframework.boot.test.OutputCapture; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link SampleSimpleApplication}. @@ -57,14 +57,14 @@ public class SampleSimpleApplicationTests { public void testDefaultSettings() throws Exception { SampleSimpleApplication.main(new String[0]); String output = this.outputCapture.toString(); - assertTrue("Wrong output: " + output, output.contains("Hello Phil")); + assertThat(output).contains("Hello Phil"); } @Test public void testCommandLineOverrides() throws Exception { SampleSimpleApplication.main(new String[] { "--name=Gordon" }); String output = this.outputCapture.toString(); - assertTrue("Wrong output: " + output, output.contains("Hello Gordon")); + assertThat(output).contains("Hello Gordon"); } } diff --git a/spring-boot-samples/spring-boot-sample-simple/src/test/java/sample/simple/SpringTestSampleSimpleApplicationTests.java b/spring-boot-samples/spring-boot-sample-simple/src/test/java/sample/simple/SpringTestSampleSimpleApplicationTests.java index 8a21ea0c39..22988c18a4 100644 --- a/spring-boot-samples/spring-boot-sample-simple/src/test/java/sample/simple/SpringTestSampleSimpleApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-simple/src/test/java/sample/simple/SpringTestSampleSimpleApplicationTests.java @@ -24,8 +24,7 @@ import org.springframework.boot.test.SpringApplicationConfiguration; import org.springframework.context.ApplicationContext; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link SampleSimpleApplication}. @@ -41,9 +40,9 @@ public class SpringTestSampleSimpleApplicationTests { @Test public void testContextLoads() throws Exception { - assertNotNull(this.ctx); - assertTrue(this.ctx.containsBean("helloWorldService")); - assertTrue(this.ctx.containsBean("sampleSimpleApplication")); + assertThat(this.ctx).isNotNull(); + assertThat(this.ctx.containsBean("helloWorldService")).isTrue(); + assertThat(this.ctx.containsBean("sampleSimpleApplication")).isTrue(); } } diff --git a/spring-boot-samples/spring-boot-sample-testng/pom.xml b/spring-boot-samples/spring-boot-sample-testng/pom.xml index 85aa584291..5a19a3def2 100644 --- a/spring-boot-samples/spring-boot-sample-testng/pom.xml +++ b/spring-boot-samples/spring-boot-sample-testng/pom.xml @@ -40,6 +40,10 @@ <artifactId>testng</artifactId> <version>6.8.13</version> </dependency> + <dependency> + <groupId>org.assertj</groupId> + <artifactId>assertj-core</artifactId> + </dependency> </dependencies> <build> <plugins> diff --git a/spring-boot-samples/spring-boot-sample-testng/src/test/java/sample/testng/SampleTestNGApplicationTests.java b/spring-boot-samples/spring-boot-sample-testng/src/test/java/sample/testng/SampleTestNGApplicationTests.java index 54f0911c7c..d4c002f479 100644 --- a/spring-boot-samples/spring-boot-sample-testng/src/test/java/sample/testng/SampleTestNGApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-testng/src/test/java/sample/testng/SampleTestNGApplicationTests.java @@ -27,7 +27,7 @@ import org.springframework.http.ResponseEntity; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.testng.AbstractTestNGSpringContextTests; -import static org.testng.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * Basic integration tests for demo application. @@ -46,8 +46,8 @@ public class SampleTestNGApplicationTests extends AbstractTestNGSpringContextTes public void testHome() throws Exception { ResponseEntity<String> entity = new TestRestTemplate() .getForEntity("http://localhost:" + this.port, String.class); - assertEquals(HttpStatus.OK, entity.getStatusCode()); - assertEquals("Hello World", entity.getBody()); + assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); + assertThat(entity.getBody()).isEqualTo("Hello World"); } } diff --git a/spring-boot-samples/spring-boot-sample-tomcat-jsp/src/test/java/sample/tomcat/jsp/SampleWebJspApplicationTests.java b/spring-boot-samples/spring-boot-sample-tomcat-jsp/src/test/java/sample/tomcat/jsp/SampleWebJspApplicationTests.java index 9095087685..18d3df15fd 100644 --- a/spring-boot-samples/spring-boot-sample-tomcat-jsp/src/test/java/sample/tomcat/jsp/SampleWebJspApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-tomcat-jsp/src/test/java/sample/tomcat/jsp/SampleWebJspApplicationTests.java @@ -28,8 +28,7 @@ import org.springframework.http.ResponseEntity; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * Basic integration tests for JSP application. @@ -49,9 +48,8 @@ public class SampleWebJspApplicationTests { public void testJspWithEl() throws Exception { ResponseEntity<String> entity = new TestRestTemplate() .getForEntity("http://localhost:" + this.port, String.class); - assertEquals(HttpStatus.OK, entity.getStatusCode()); - assertTrue("Wrong body:\n" + entity.getBody(), - entity.getBody().contains("/resources/text.txt")); + assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); + assertThat(entity.getBody()).contains("/resources/text.txt"); } } diff --git a/spring-boot-samples/spring-boot-sample-tomcat-multi-connectors/src/test/java/sample/tomcat/multiconnector/SampleTomcatTwoConnectorsApplicationTests.java b/spring-boot-samples/spring-boot-sample-tomcat-multi-connectors/src/test/java/sample/tomcat/multiconnector/SampleTomcatTwoConnectorsApplicationTests.java index 1199493f2c..84cabbf921 100644 --- a/spring-boot-samples/spring-boot-sample-tomcat-multi-connectors/src/test/java/sample/tomcat/multiconnector/SampleTomcatTwoConnectorsApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-tomcat-multi-connectors/src/test/java/sample/tomcat/multiconnector/SampleTomcatTwoConnectorsApplicationTests.java @@ -42,7 +42,7 @@ import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.web.client.RestTemplate; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * Basic integration tests for {@link SampleTomcatTwoConnectorsApplication}. @@ -111,13 +111,13 @@ public class SampleTomcatTwoConnectorsApplicationTests { ResponseEntity<String> entity = template.getForEntity( "http://localhost:" + this.context.getBean("port") + "/hello", String.class); - assertEquals(HttpStatus.OK, entity.getStatusCode()); - assertEquals("hello", entity.getBody()); + assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); + assertThat(entity.getBody()).isEqualTo("hello"); ResponseEntity<String> httpsEntity = template .getForEntity("https://localhost:" + this.port + "/hello", String.class); - assertEquals(HttpStatus.OK, httpsEntity.getStatusCode()); - assertEquals("hello", httpsEntity.getBody()); + assertThat(httpsEntity.getStatusCode()).isEqualTo(HttpStatus.OK); + assertThat(httpsEntity.getBody()).isEqualTo("hello"); } diff --git a/spring-boot-samples/spring-boot-sample-tomcat-ssl/src/test/java/sample/tomcat/SampleTomcatSslApplicationTests.java b/spring-boot-samples/spring-boot-sample-tomcat-ssl/src/test/java/sample/tomcat/SampleTomcatSslApplicationTests.java index e158130a49..4b353b472b 100644 --- a/spring-boot-samples/spring-boot-sample-tomcat-ssl/src/test/java/sample/tomcat/SampleTomcatSslApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-tomcat-ssl/src/test/java/sample/tomcat/SampleTomcatSslApplicationTests.java @@ -23,19 +23,19 @@ import org.apache.http.impl.client.HttpClients; import org.apache.http.ssl.SSLContextBuilder; import org.junit.Test; import org.junit.runner.RunWith; -import org.springframework.boot.test.WebIntegrationTest; import sample.tomcat.ssl.SampleTomcatSslApplication; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.test.SpringApplicationConfiguration; import org.springframework.boot.test.TestRestTemplate; +import org.springframework.boot.test.WebIntegrationTest; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.http.client.HttpComponentsClientHttpRequestFactory; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(SampleTomcatSslApplication.class) @@ -60,8 +60,8 @@ public class SampleTomcatSslApplicationTests { .setHttpClient(httpClient); ResponseEntity<String> entity = testRestTemplate .getForEntity("https://localhost:" + this.port, String.class); - assertEquals(HttpStatus.OK, entity.getStatusCode()); - assertEquals("Hello, world", entity.getBody()); + assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); + assertThat(entity.getBody()).isEqualTo("Hello, world"); } } diff --git a/spring-boot-samples/spring-boot-sample-tomcat/src/test/java/sample/tomcat/NonAutoConfigurationSampleTomcatApplicationTests.java b/spring-boot-samples/spring-boot-sample-tomcat/src/test/java/sample/tomcat/NonAutoConfigurationSampleTomcatApplicationTests.java index bf706d8bcb..5aba54cf4a 100644 --- a/spring-boot-samples/spring-boot-sample-tomcat/src/test/java/sample/tomcat/NonAutoConfigurationSampleTomcatApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-tomcat/src/test/java/sample/tomcat/NonAutoConfigurationSampleTomcatApplicationTests.java @@ -18,7 +18,6 @@ package sample.tomcat; import org.junit.Test; import org.junit.runner.RunWith; -import org.springframework.boot.test.WebIntegrationTest; import sample.tomcat.NonAutoConfigurationSampleTomcatApplicationTests.NonAutoConfigurationSampleTomcatApplication; import sample.tomcat.service.HelloWorldService; import sample.tomcat.web.SampleController; @@ -33,6 +32,7 @@ import org.springframework.boot.autoconfigure.web.ServerPropertiesAutoConfigurat import org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration; import org.springframework.boot.test.SpringApplicationConfiguration; import org.springframework.boot.test.TestRestTemplate; +import org.springframework.boot.test.WebIntegrationTest; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; @@ -41,7 +41,7 @@ import org.springframework.http.ResponseEntity; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * Basic integration tests for demo application. @@ -77,8 +77,8 @@ public class NonAutoConfigurationSampleTomcatApplicationTests { public void testHome() throws Exception { ResponseEntity<String> entity = new TestRestTemplate() .getForEntity("http://localhost:" + this.port, String.class); - assertEquals(HttpStatus.OK, entity.getStatusCode()); - assertEquals("Hello World", entity.getBody()); + assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); + assertThat(entity.getBody()).isEqualTo("Hello World"); } } diff --git a/spring-boot-samples/spring-boot-sample-tomcat/src/test/java/sample/tomcat/SampleTomcatApplicationTests.java b/spring-boot-samples/spring-boot-sample-tomcat/src/test/java/sample/tomcat/SampleTomcatApplicationTests.java index 944ca61f80..88ed4cc4e9 100644 --- a/spring-boot-samples/spring-boot-sample-tomcat/src/test/java/sample/tomcat/SampleTomcatApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-tomcat/src/test/java/sample/tomcat/SampleTomcatApplicationTests.java @@ -37,7 +37,7 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.util.StreamUtils; import org.springframework.web.client.RestTemplate; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * Basic integration tests for demo application. @@ -58,8 +58,8 @@ public class SampleTomcatApplicationTests { public void testHome() throws Exception { ResponseEntity<String> entity = new TestRestTemplate() .getForEntity("http://localhost:" + this.port, String.class); - assertEquals(HttpStatus.OK, entity.getStatusCode()); - assertEquals("Hello World", entity.getBody()); + assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); + assertThat(entity.getBody()).isEqualTo("Hello World"); } @Test @@ -71,12 +71,12 @@ public class SampleTomcatApplicationTests { ResponseEntity<byte[]> entity = restTemplate.exchange( "http://localhost:" + this.port, HttpMethod.GET, requestEntity, byte[].class); - assertEquals(HttpStatus.OK, entity.getStatusCode()); + assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); GZIPInputStream inflater = new GZIPInputStream( new ByteArrayInputStream(entity.getBody())); try { - assertEquals("Hello World", - StreamUtils.copyToString(inflater, Charset.forName("UTF-8"))); + assertThat(StreamUtils.copyToString(inflater, Charset.forName("UTF-8"))) + .isEqualTo("Hello World"); } finally { inflater.close(); diff --git a/spring-boot-samples/spring-boot-sample-tomcat7-jsp/src/test/java/sample/tomcat7/jsp/SampleWebJspApplicationTests.java b/spring-boot-samples/spring-boot-sample-tomcat7-jsp/src/test/java/sample/tomcat7/jsp/SampleWebJspApplicationTests.java index d55e19afa1..26877e8bbd 100644 --- a/spring-boot-samples/spring-boot-sample-tomcat7-jsp/src/test/java/sample/tomcat7/jsp/SampleWebJspApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-tomcat7-jsp/src/test/java/sample/tomcat7/jsp/SampleWebJspApplicationTests.java @@ -28,8 +28,7 @@ import org.springframework.http.ResponseEntity; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * Basic integration tests for JSP application. @@ -49,9 +48,8 @@ public class SampleWebJspApplicationTests { public void testJspWithEl() throws Exception { ResponseEntity<String> entity = new TestRestTemplate() .getForEntity("http://localhost:" + this.port, String.class); - assertEquals(HttpStatus.OK, entity.getStatusCode()); - assertTrue("Wrong body:\n" + entity.getBody(), - entity.getBody().contains("/resources/text.txt")); + assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); + assertThat(entity.getBody()).contains("/resources/text.txt"); } } diff --git a/spring-boot-samples/spring-boot-sample-traditional/src/test/java/sample/traditional/SampleTraditionalApplicationTests.java b/spring-boot-samples/spring-boot-sample-traditional/src/test/java/sample/traditional/SampleTraditionalApplicationTests.java index 8a84bffa77..0ae8fef537 100644 --- a/spring-boot-samples/spring-boot-sample-traditional/src/test/java/sample/traditional/SampleTraditionalApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-traditional/src/test/java/sample/traditional/SampleTraditionalApplicationTests.java @@ -28,8 +28,7 @@ import org.springframework.http.ResponseEntity; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * Basic integration tests for demo application. @@ -49,20 +48,18 @@ public class SampleTraditionalApplicationTests { public void testHomeJsp() throws Exception { ResponseEntity<String> entity = new TestRestTemplate() .getForEntity("http://localhost:" + this.port, String.class); - assertEquals(HttpStatus.OK, entity.getStatusCode()); + assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); String body = entity.getBody(); - assertTrue("Wrong body:\n" + body, body.contains("<html>")); - assertTrue("Wrong body:\n" + body, body.contains("<h1>Home</h1>")); + assertThat(body).contains("<html>").contains("<h1>Home</h1>"); } @Test public void testStaticPage() throws Exception { ResponseEntity<String> entity = new TestRestTemplate().getForEntity( "http://localhost:" + this.port + "/index.html", String.class); - assertEquals(HttpStatus.OK, entity.getStatusCode()); + assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); String body = entity.getBody(); - assertTrue("Wrong body:\n" + body, body.contains("<html>")); - assertTrue("Wrong body:\n" + body, body.contains("<h1>Hello</h1>")); + assertThat(body).contains("<html>").contains("<h1>Hello</h1>"); } } diff --git a/spring-boot-samples/spring-boot-sample-undertow-ssl/src/test/java/sample/undertow/ssl/SampleUndertowSslApplicationTests.java b/spring-boot-samples/spring-boot-sample-undertow-ssl/src/test/java/sample/undertow/ssl/SampleUndertowSslApplicationTests.java index 63f0ecf3a5..892efc110e 100644 --- a/spring-boot-samples/spring-boot-sample-undertow-ssl/src/test/java/sample/undertow/ssl/SampleUndertowSslApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-undertow-ssl/src/test/java/sample/undertow/ssl/SampleUndertowSslApplicationTests.java @@ -34,7 +34,7 @@ import org.springframework.http.client.HttpComponentsClientHttpRequestFactory; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * Basic integration tests for demo application. @@ -64,8 +64,8 @@ public class SampleUndertowSslApplicationTests { .setHttpClient(httpClient); ResponseEntity<String> entity = testRestTemplate .getForEntity("https://localhost:" + this.port, String.class); - assertEquals(HttpStatus.OK, entity.getStatusCode()); - assertEquals("Hello World", entity.getBody()); + assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); + assertThat(entity.getBody()).isEqualTo("Hello World"); } } diff --git a/spring-boot-samples/spring-boot-sample-undertow/src/test/java/sample/undertow/SampleUndertowApplicationTests.java b/spring-boot-samples/spring-boot-sample-undertow/src/test/java/sample/undertow/SampleUndertowApplicationTests.java index cba1eff262..a57ad05271 100644 --- a/spring-boot-samples/spring-boot-sample-undertow/src/test/java/sample/undertow/SampleUndertowApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-undertow/src/test/java/sample/undertow/SampleUndertowApplicationTests.java @@ -37,7 +37,7 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.util.StreamUtils; import org.springframework.web.client.RestTemplate; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * Basic integration tests for demo application. @@ -73,12 +73,12 @@ public class SampleUndertowApplicationTests { ResponseEntity<byte[]> entity = restTemplate.exchange( "http://localhost:" + this.port, HttpMethod.GET, requestEntity, byte[].class); - assertEquals(HttpStatus.OK, entity.getStatusCode()); + assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); GZIPInputStream inflater = new GZIPInputStream( new ByteArrayInputStream(entity.getBody())); try { - assertEquals("Hello World", - StreamUtils.copyToString(inflater, Charset.forName("UTF-8"))); + assertThat(StreamUtils.copyToString(inflater, Charset.forName("UTF-8"))) + .isEqualTo("Hello World"); } finally { inflater.close(); @@ -88,8 +88,8 @@ public class SampleUndertowApplicationTests { private void assertOkResponse(String path, String body) { ResponseEntity<String> entity = new TestRestTemplate() .getForEntity("http://localhost:" + this.port + path, String.class); - assertEquals(HttpStatus.OK, entity.getStatusCode()); - assertEquals(body, entity.getBody()); + assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); + assertThat(entity.getBody()).isEqualTo(body); } } diff --git a/spring-boot-samples/spring-boot-sample-velocity/src/test/java/sample/velocity/SampleVelocityApplicationTests.java b/spring-boot-samples/spring-boot-sample-velocity/src/test/java/sample/velocity/SampleVelocityApplicationTests.java index 94dcbac26a..f1cb56bbbb 100644 --- a/spring-boot-samples/spring-boot-sample-velocity/src/test/java/sample/velocity/SampleVelocityApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-velocity/src/test/java/sample/velocity/SampleVelocityApplicationTests.java @@ -24,7 +24,7 @@ import org.springframework.boot.test.OutputCapture; import org.springframework.boot.test.SpringApplicationConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * Basic integration tests for Velocity application with no web layer. @@ -41,7 +41,7 @@ public class SampleVelocityApplicationTests { @Test public void testVelocityTemplate() throws Exception { String result = SampleVelocityApplicationTests.output.toString(); - assertTrue("Wrong output: " + result, result.contains("Hello, Andy")); + assertThat(result).contains("Hello, Andy"); } } diff --git a/spring-boot-samples/spring-boot-sample-web-freemarker/src/test/java/sample/freemarker/SampleWebFreeMarkerApplicationTests.java b/spring-boot-samples/spring-boot-sample-web-freemarker/src/test/java/sample/freemarker/SampleWebFreeMarkerApplicationTests.java index 3cdca9c8d4..85c6b6ef09 100644 --- a/spring-boot-samples/spring-boot-sample-web-freemarker/src/test/java/sample/freemarker/SampleWebFreeMarkerApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-web-freemarker/src/test/java/sample/freemarker/SampleWebFreeMarkerApplicationTests.java @@ -34,8 +34,7 @@ import org.springframework.http.ResponseEntity; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * Basic integration tests for FreeMarker application. @@ -55,10 +54,9 @@ public class SampleWebFreeMarkerApplicationTests { @Test public void testFreeMarkerTemplate() throws Exception { ResponseEntity<String> entity = new TestRestTemplate() - .getForEntity("http://localhost:" + port, String.class); - assertEquals(HttpStatus.OK, entity.getStatusCode()); - assertTrue("Wrong body:\n" + entity.getBody(), - entity.getBody().contains("Hello, Andy")); + .getForEntity("http://localhost:" + this.port, String.class); + assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); + assertThat(entity.getBody()).contains("Hello, Andy"); } @Test @@ -68,12 +66,12 @@ public class SampleWebFreeMarkerApplicationTests { HttpEntity<String> requestEntity = new HttpEntity<String>(headers); ResponseEntity<String> responseEntity = new TestRestTemplate().exchange( - "http://localhost:" + port + "/does-not-exist", HttpMethod.GET, + "http://localhost:" + this.port + "/does-not-exist", HttpMethod.GET, requestEntity, String.class); - assertEquals(HttpStatus.NOT_FOUND, responseEntity.getStatusCode()); - assertTrue("Wrong body:\n" + responseEntity.getBody(), - responseEntity.getBody().contains("Something went wrong: 404 Not Found")); + assertThat(responseEntity.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND); + assertThat(responseEntity.getBody()) + .contains("Something went wrong: 404 Not Found"); } } diff --git a/spring-boot-samples/spring-boot-sample-web-groovy-templates/src/test/java/sample/groovytemplates/SampleGroovyTemplateApplicationTests.java b/spring-boot-samples/spring-boot-sample-web-groovy-templates/src/test/java/sample/groovytemplates/SampleGroovyTemplateApplicationTests.java index 19cec7ce8d..c4f16b87d2 100644 --- a/spring-boot-samples/spring-boot-sample-web-groovy-templates/src/test/java/sample/groovytemplates/SampleGroovyTemplateApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-web-groovy-templates/src/test/java/sample/groovytemplates/SampleGroovyTemplateApplicationTests.java @@ -32,9 +32,7 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; -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; /** * Basic integration tests for demo application. @@ -54,11 +52,9 @@ public class SampleGroovyTemplateApplicationTests { public void testHome() throws Exception { ResponseEntity<String> entity = new TestRestTemplate() .getForEntity("http://localhost:" + this.port, String.class); - assertEquals(HttpStatus.OK, entity.getStatusCode()); - assertTrue("Wrong body (title doesn't match):\n" + entity.getBody(), - entity.getBody().contains("<title>Messages")); - assertFalse("Wrong body (found layout:fragment):\n" + entity.getBody(), - entity.getBody().contains("layout:fragment")); + assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); + assertThat(entity.getBody()).contains("<title>Messages"); + assertThat(entity.getBody()).doesNotContain("layout:fragment"); } @Test @@ -68,16 +64,15 @@ public class SampleGroovyTemplateApplicationTests { map.set("summary", "FOO"); URI location = new TestRestTemplate() .postForLocation("http://localhost:" + this.port, map); - assertTrue("Wrong location:\n" + location, - location.toString().contains("localhost:" + this.port)); + assertThat(location.toString()).contains("localhost:" + this.port); } @Test public void testCss() throws Exception { ResponseEntity<String> entity = new TestRestTemplate().getForEntity( "http://localhost:" + this.port + "/css/bootstrap.min.css", String.class); - assertEquals(HttpStatus.OK, entity.getStatusCode()); - assertTrue("Wrong body:\n" + entity.getBody(), entity.getBody().contains("body")); + assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); + assertThat(entity.getBody()).contains("body"); } } diff --git a/spring-boot-samples/spring-boot-sample-web-jsp/src/test/java/sample/jsp/SampleWebJspApplicationTests.java b/spring-boot-samples/spring-boot-sample-web-jsp/src/test/java/sample/jsp/SampleWebJspApplicationTests.java index 37a0cbbd0e..2b16f8fe12 100644 --- a/spring-boot-samples/spring-boot-sample-web-jsp/src/test/java/sample/jsp/SampleWebJspApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-web-jsp/src/test/java/sample/jsp/SampleWebJspApplicationTests.java @@ -28,8 +28,7 @@ import org.springframework.http.ResponseEntity; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * Basic integration tests for JSP application. @@ -49,9 +48,8 @@ public class SampleWebJspApplicationTests { public void testJspWithEl() throws Exception { ResponseEntity<String> entity = new TestRestTemplate() .getForEntity("http://localhost:" + this.port, String.class); - assertEquals(HttpStatus.OK, entity.getStatusCode()); - assertTrue("Wrong body:\n" + entity.getBody(), - entity.getBody().contains("/resources/text.txt")); + assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); + assertThat(entity.getBody()).contains("/resources/text.txt"); } } diff --git a/spring-boot-samples/spring-boot-sample-web-method-security/src/test/java/sample/security/method/SampleMethodSecurityApplicationTests.java b/spring-boot-samples/spring-boot-sample-web-method-security/src/test/java/sample/security/method/SampleMethodSecurityApplicationTests.java index 022a2e6803..7687e3a157 100644 --- a/spring-boot-samples/spring-boot-sample-web-method-security/src/test/java/sample/security/method/SampleMethodSecurityApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-web-method-security/src/test/java/sample/security/method/SampleMethodSecurityApplicationTests.java @@ -38,8 +38,7 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * Basic integration tests for demo application. @@ -62,9 +61,8 @@ public class SampleMethodSecurityApplicationTests { ResponseEntity<String> entity = new TestRestTemplate().exchange( "http://localhost:" + this.port, HttpMethod.GET, new HttpEntity<Void>(headers), String.class); - assertEquals(HttpStatus.OK, entity.getStatusCode()); - assertTrue("Wrong body (title doesn't match):\n" + entity.getBody(), - entity.getBody().contains("<title>Login")); + assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); + assertThat(entity.getBody()).contains("<title>Login"); } @Test @@ -79,9 +77,9 @@ public class SampleMethodSecurityApplicationTests { "http://localhost:" + this.port + "/login", HttpMethod.POST, new HttpEntity<MultiValueMap<String, String>>(form, headers), String.class); - assertEquals(HttpStatus.FOUND, entity.getStatusCode()); - assertEquals("http://localhost:" + this.port + "/", - entity.getHeaders().getLocation().toString()); + assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.FOUND); + assertThat(entity.getHeaders().getLocation().toString()) + .isEqualTo("http://localhost:" + this.port + "/"); } @Test @@ -96,36 +94,35 @@ public class SampleMethodSecurityApplicationTests { "http://localhost:" + this.port + "/login", HttpMethod.POST, new HttpEntity<MultiValueMap<String, String>>(form, headers), String.class); - assertEquals(HttpStatus.FOUND, entity.getStatusCode()); + assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.FOUND); String cookie = entity.getHeaders().getFirst("Set-Cookie"); headers.set("Cookie", cookie); ResponseEntity<String> page = new TestRestTemplate().exchange( entity.getHeaders().getLocation(), HttpMethod.GET, new HttpEntity<Void>(headers), String.class); - assertEquals(HttpStatus.FORBIDDEN, page.getStatusCode()); - assertTrue("Wrong body (message doesn't match):\n" + entity.getBody(), - page.getBody().contains("Access denied")); + assertThat(page.getStatusCode()).isEqualTo(HttpStatus.FORBIDDEN); + assertThat(page.getBody()).contains("Access denied"); } @Test public void testManagementProtected() throws Exception { ResponseEntity<String> entity = new TestRestTemplate() .getForEntity("http://localhost:" + this.port + "/beans", String.class); - assertEquals(HttpStatus.UNAUTHORIZED, entity.getStatusCode()); + assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED); } @Test public void testManagementAuthorizedAccess() throws Exception { ResponseEntity<String> entity = new TestRestTemplate("admin", "admin") .getForEntity("http://localhost:" + this.port + "/beans", String.class); - assertEquals(HttpStatus.OK, entity.getStatusCode()); + assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); } @Test public void testManagementUnauthorizedAccess() throws Exception { ResponseEntity<String> entity = new TestRestTemplate("user", "user") .getForEntity("http://localhost:" + this.port + "/beans", String.class); - assertEquals(HttpStatus.FORBIDDEN, entity.getStatusCode()); + assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.FORBIDDEN); } private void getCsrf(MultiValueMap<String, String> form, HttpHeaders headers) { diff --git a/spring-boot-samples/spring-boot-sample-web-mustache/src/test/java/sample/mustache/SampleWebMustacheApplicationTests.java b/spring-boot-samples/spring-boot-sample-web-mustache/src/test/java/sample/mustache/SampleWebMustacheApplicationTests.java index f7c6f0b162..7dfeb7b977 100644 --- a/spring-boot-samples/spring-boot-sample-web-mustache/src/test/java/sample/mustache/SampleWebMustacheApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-web-mustache/src/test/java/sample/mustache/SampleWebMustacheApplicationTests.java @@ -34,8 +34,7 @@ import org.springframework.http.ResponseEntity; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * Basic integration tests for Mustache application. @@ -56,9 +55,8 @@ public class SampleWebMustacheApplicationTests { public void testMustacheTemplate() throws Exception { ResponseEntity<String> entity = new TestRestTemplate() .getForEntity("http://localhost:" + this.port, String.class); - assertEquals(HttpStatus.OK, entity.getStatusCode()); - assertTrue("Wrong body:\n" + entity.getBody(), - entity.getBody().contains("Hello, Andy")); + assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); + assertThat(entity.getBody()).contains("Hello, Andy"); } @Test @@ -71,9 +69,9 @@ public class SampleWebMustacheApplicationTests { "http://localhost:" + this.port + "/does-not-exist", HttpMethod.GET, requestEntity, String.class); - assertEquals(HttpStatus.NOT_FOUND, responseEntity.getStatusCode()); - assertTrue("Wrong body:\n" + responseEntity.getBody(), - responseEntity.getBody().contains("Something went wrong: 404 Not Found")); + assertThat(responseEntity.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND); + assertThat(responseEntity.getBody()) + .contains("Something went wrong: 404 Not Found"); } } diff --git a/spring-boot-samples/spring-boot-sample-web-secure-custom/src/test/java/sample/ui/secure/SampleWebSecureCustomApplicationTests.java b/spring-boot-samples/spring-boot-sample-web-secure-custom/src/test/java/sample/ui/secure/SampleWebSecureCustomApplicationTests.java index 7e87264c4c..263169a389 100644 --- a/spring-boot-samples/spring-boot-sample-web-secure-custom/src/test/java/sample/ui/secure/SampleWebSecureCustomApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-web-secure-custom/src/test/java/sample/ui/secure/SampleWebSecureCustomApplicationTests.java @@ -22,12 +22,12 @@ import java.util.regex.Pattern; import org.junit.Test; import org.junit.runner.RunWith; -import org.springframework.boot.test.WebIntegrationTest; import sample.web.secure.custom.SampleWebSecureCustomApplication; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.test.SpringApplicationConfiguration; import org.springframework.boot.test.TestRestTemplate; +import org.springframework.boot.test.WebIntegrationTest; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; @@ -39,9 +39,7 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; -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; /** * Basic integration tests for demo application. @@ -64,9 +62,9 @@ public class SampleWebSecureCustomApplicationTests { ResponseEntity<String> entity = new TestRestTemplate().exchange( "http://localhost:" + this.port, HttpMethod.GET, new HttpEntity<Void>(headers), String.class); - assertEquals(HttpStatus.FOUND, entity.getStatusCode()); - assertTrue("Wrong location:\n" + entity.getHeaders(), - entity.getHeaders().getLocation().toString().endsWith(port + "/login")); + assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.FOUND); + assertThat(entity.getHeaders().getLocation().toString()) + .endsWith(this.port + "/login"); } @Test @@ -76,9 +74,8 @@ public class SampleWebSecureCustomApplicationTests { ResponseEntity<String> entity = new TestRestTemplate().exchange( "http://localhost:" + this.port + "/login", HttpMethod.GET, new HttpEntity<Void>(headers), String.class); - assertEquals(HttpStatus.OK, entity.getStatusCode()); - assertTrue("Wrong content:\n" + entity.getBody(), - entity.getBody().contains("_csrf")); + assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); + assertThat(entity.getBody()).contains("_csrf"); } @Test @@ -93,23 +90,22 @@ public class SampleWebSecureCustomApplicationTests { "http://localhost:" + this.port + "/login", HttpMethod.POST, new HttpEntity<MultiValueMap<String, String>>(form, headers), String.class); - assertEquals(HttpStatus.FOUND, entity.getStatusCode()); - assertTrue("Wrong location:\n" + entity.getHeaders(), - entity.getHeaders().getLocation().toString().endsWith(port + "/")); - assertNotNull("Missing cookie:\n" + entity.getHeaders(), - entity.getHeaders().get("Set-Cookie")); + assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.FOUND); + assertThat(entity.getHeaders().getLocation().toString()) + .endsWith(this.port + "/"); + assertThat(entity.getHeaders().get("Set-Cookie")).isNotNull(); } private HttpHeaders getHeaders() { HttpHeaders headers = new HttpHeaders(); ResponseEntity<String> page = new TestRestTemplate() .getForEntity("http://localhost:" + this.port + "/login", String.class); - assertEquals(HttpStatus.OK, page.getStatusCode()); + assertThat(page.getStatusCode()).isEqualTo(HttpStatus.OK); String cookie = page.getHeaders().getFirst("Set-Cookie"); headers.set("Cookie", cookie); - Matcher matcher = Pattern.compile("(?s).*name=\"_csrf\".*?value=\"([^\"]+).*") - .matcher(page.getBody()); - assertTrue("No csrf token: " + page.getBody(), matcher.matches()); + Pattern pattern = Pattern.compile("(?s).*name=\"_csrf\".*?value=\"([^\"]+).*"); + Matcher matcher = pattern.matcher(page.getBody()); + assertThat(matcher.matches()).as(page.getBody()).isTrue(); headers.set("X-CSRF-TOKEN", matcher.group(1)); return headers; } @@ -118,8 +114,8 @@ public class SampleWebSecureCustomApplicationTests { public void testCss() throws Exception { ResponseEntity<String> entity = new TestRestTemplate().getForEntity( "http://localhost:" + this.port + "/css/bootstrap.min.css", String.class); - assertEquals(HttpStatus.OK, entity.getStatusCode()); - assertTrue("Wrong body:\n" + entity.getBody(), entity.getBody().contains("body")); + assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); + assertThat(entity.getBody()).contains("body"); } } diff --git a/spring-boot-samples/spring-boot-sample-web-secure-github/src/test/java/sample/web/secure/github/SampleGithubApplicationTests.java b/spring-boot-samples/spring-boot-sample-web-secure-github/src/test/java/sample/web/secure/github/SampleGithubApplicationTests.java index 8964d41044..d206331121 100644 --- a/spring-boot-samples/spring-boot-sample-web-secure-github/src/test/java/sample/web/secure/github/SampleGithubApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-web-secure-github/src/test/java/sample/web/secure/github/SampleGithubApplicationTests.java @@ -30,10 +30,7 @@ import org.springframework.http.ResponseEntity; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.startsWith; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; /** * Basic integration tests for GitHub SSO application. @@ -55,9 +52,9 @@ public class SampleGithubApplicationTests { TestRestTemplate restTemplate = new TestRestTemplate(); ResponseEntity<Void> entity = restTemplate .getForEntity("http://localhost:" + this.port, Void.class); - assertThat(entity.getStatusCode(), is(HttpStatus.FOUND)); - assertThat(entity.getHeaders().getLocation(), - is(equalTo(URI.create("http://localhost:" + this.port + "/login")))); + assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.FOUND); + assertThat(entity.getHeaders().getLocation()) + .isEqualTo(URI.create("http://localhost:" + this.port + "/login")); } @Test @@ -65,9 +62,9 @@ public class SampleGithubApplicationTests { TestRestTemplate restTemplate = new TestRestTemplate(); ResponseEntity<Void> entity = restTemplate .getForEntity("http://localhost:" + this.port + "/login", Void.class); - assertThat(entity.getStatusCode(), is(HttpStatus.FOUND)); - assertThat(entity.getHeaders().getLocation().toString(), - startsWith("https://github.com/login/oauth")); + assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.FOUND); + assertThat(entity.getHeaders().getLocation().toString()) + .startsWith("https://github.com/login/oauth"); } } diff --git a/spring-boot-samples/spring-boot-sample-web-secure-jdbc/src/test/java/sample/web/secure/jdbc/SampleWebSecureCustomApplicationTests.java b/spring-boot-samples/spring-boot-sample-web-secure-jdbc/src/test/java/sample/web/secure/jdbc/SampleWebSecureCustomApplicationTests.java index eba294b82d..62cb371c61 100644 --- a/spring-boot-samples/spring-boot-sample-web-secure-jdbc/src/test/java/sample/web/secure/jdbc/SampleWebSecureCustomApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-web-secure-jdbc/src/test/java/sample/web/secure/jdbc/SampleWebSecureCustomApplicationTests.java @@ -38,9 +38,7 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; -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; /** * Basic integration tests for demo application. @@ -63,9 +61,9 @@ public class SampleWebSecureCustomApplicationTests { ResponseEntity<String> entity = new TestRestTemplate().exchange( "http://localhost:" + this.port, HttpMethod.GET, new HttpEntity<Void>(headers), String.class); - assertEquals(HttpStatus.FOUND, entity.getStatusCode()); - assertTrue("Wrong location:\n" + entity.getHeaders(), - entity.getHeaders().getLocation().toString().endsWith(port + "/login")); + assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.FOUND); + assertThat(entity.getHeaders().getLocation().toString()) + .endsWith(this.port + "/login"); } @Test @@ -75,9 +73,8 @@ public class SampleWebSecureCustomApplicationTests { ResponseEntity<String> entity = new TestRestTemplate().exchange( "http://localhost:" + this.port + "/login", HttpMethod.GET, new HttpEntity<Void>(headers), String.class); - assertEquals(HttpStatus.OK, entity.getStatusCode()); - assertTrue("Wrong content:\n" + entity.getBody(), - entity.getBody().contains("_csrf")); + assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); + assertThat(entity.getBody()).contains("_csrf"); } @Test @@ -92,23 +89,22 @@ public class SampleWebSecureCustomApplicationTests { "http://localhost:" + this.port + "/login", HttpMethod.POST, new HttpEntity<MultiValueMap<String, String>>(form, headers), String.class); - assertEquals(HttpStatus.FOUND, entity.getStatusCode()); - assertTrue("Wrong location:\n" + entity.getHeaders(), - entity.getHeaders().getLocation().toString().endsWith(port + "/")); - assertNotNull("Missing cookie:\n" + entity.getHeaders(), - entity.getHeaders().get("Set-Cookie")); + assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.FOUND); + assertThat(entity.getHeaders().getLocation().toString()) + .endsWith(this.port + "/"); + assertThat(entity.getHeaders().get("Set-Cookie")).isNotNull(); } private HttpHeaders getHeaders() { HttpHeaders headers = new HttpHeaders(); ResponseEntity<String> page = new TestRestTemplate() .getForEntity("http://localhost:" + this.port + "/login", String.class); - assertEquals(HttpStatus.OK, page.getStatusCode()); + assertThat(page.getStatusCode()).isEqualTo(HttpStatus.OK); String cookie = page.getHeaders().getFirst("Set-Cookie"); headers.set("Cookie", cookie); - Matcher matcher = Pattern.compile("(?s).*name=\"_csrf\".*?value=\"([^\"]+).*") - .matcher(page.getBody()); - assertTrue("No csrf token: " + page.getBody(), matcher.matches()); + Pattern pattern = Pattern.compile("(?s).*name=\"_csrf\".*?value=\"([^\"]+).*"); + Matcher matcher = pattern.matcher(page.getBody()); + assertThat(matcher.matches()).as(page.getBody()).isTrue(); headers.set("X-CSRF-TOKEN", matcher.group(1)); return headers; } @@ -117,8 +113,8 @@ public class SampleWebSecureCustomApplicationTests { public void testCss() throws Exception { ResponseEntity<String> entity = new TestRestTemplate().getForEntity( "http://localhost:" + this.port + "/css/bootstrap.min.css", String.class); - assertEquals(HttpStatus.OK, entity.getStatusCode()); - assertTrue("Wrong body:\n" + entity.getBody(), entity.getBody().contains("body")); + assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); + assertThat(entity.getBody()).contains("body"); } } diff --git a/spring-boot-samples/spring-boot-sample-web-secure/src/test/java/sample/web/secure/SampleSecureApplicationTests.java b/spring-boot-samples/spring-boot-sample-web-secure/src/test/java/sample/web/secure/SampleSecureApplicationTests.java index 92948514a2..3f3d6d0624 100644 --- a/spring-boot-samples/spring-boot-sample-web-secure/src/test/java/sample/web/secure/SampleSecureApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-web-secure/src/test/java/sample/web/secure/SampleSecureApplicationTests.java @@ -38,9 +38,7 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; -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; /** * Basic integration tests for demo application. @@ -63,9 +61,9 @@ public class SampleSecureApplicationTests { ResponseEntity<String> entity = new TestRestTemplate().exchange( "http://localhost:" + this.port, HttpMethod.GET, new HttpEntity<Void>(headers), String.class); - assertEquals(HttpStatus.FOUND, entity.getStatusCode()); - assertTrue("Wrong location:\n" + entity.getHeaders(), - entity.getHeaders().getLocation().toString().endsWith(port + "/login")); + assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.FOUND); + assertThat(entity.getHeaders().getLocation().toString()) + .endsWith(this.port + "/login"); } @Test @@ -75,9 +73,8 @@ public class SampleSecureApplicationTests { ResponseEntity<String> entity = new TestRestTemplate().exchange( "http://localhost:" + this.port + "/login", HttpMethod.GET, new HttpEntity<Void>(headers), String.class); - assertEquals(HttpStatus.OK, entity.getStatusCode()); - assertTrue("Wrong content:\n" + entity.getBody(), - entity.getBody().contains("_csrf")); + assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); + assertThat(entity.getBody()).contains("_csrf"); } @Test @@ -92,23 +89,22 @@ public class SampleSecureApplicationTests { "http://localhost:" + this.port + "/login", HttpMethod.POST, new HttpEntity<MultiValueMap<String, String>>(form, headers), String.class); - assertEquals(HttpStatus.FOUND, entity.getStatusCode()); - assertTrue("Wrong location:\n" + entity.getHeaders(), - entity.getHeaders().getLocation().toString().endsWith(port + "/")); - assertNotNull("Missing cookie:\n" + entity.getHeaders(), - entity.getHeaders().get("Set-Cookie")); + assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.FOUND); + assertThat(entity.getHeaders().getLocation().toString()) + .endsWith(this.port + "/"); + assertThat(entity.getHeaders().get("Set-Cookie")).isNotNull(); } private HttpHeaders getHeaders() { HttpHeaders headers = new HttpHeaders(); ResponseEntity<String> page = new TestRestTemplate() .getForEntity("http://localhost:" + this.port + "/login", String.class); - assertEquals(HttpStatus.OK, page.getStatusCode()); + assertThat(page.getStatusCode()).isEqualTo(HttpStatus.OK); String cookie = page.getHeaders().getFirst("Set-Cookie"); headers.set("Cookie", cookie); - Matcher matcher = Pattern.compile("(?s).*name=\"_csrf\".*?value=\"([^\"]+).*") - .matcher(page.getBody()); - assertTrue("No csrf token: " + page.getBody(), matcher.matches()); + Pattern pattern = Pattern.compile("(?s).*name=\"_csrf\".*?value=\"([^\"]+).*"); + Matcher matcher = pattern.matcher(page.getBody()); + assertThat(matcher.matches()).as(page.getBody()).isTrue(); headers.set("X-CSRF-TOKEN", matcher.group(1)); return headers; } @@ -117,8 +113,8 @@ public class SampleSecureApplicationTests { public void testCss() throws Exception { ResponseEntity<String> entity = new TestRestTemplate().getForEntity( "http://localhost:" + this.port + "/css/bootstrap.min.css", String.class); - assertEquals(HttpStatus.OK, entity.getStatusCode()); - assertTrue("Wrong body:\n" + entity.getBody(), entity.getBody().contains("body")); + assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); + assertThat(entity.getBody()).contains("body"); } } diff --git a/spring-boot-samples/spring-boot-sample-web-static/src/test/java/sample/webstatic/SampleWebStaticApplicationTests.java b/spring-boot-samples/spring-boot-sample-web-static/src/test/java/sample/webstatic/SampleWebStaticApplicationTests.java index 037db3756d..dd1285fe27 100644 --- a/spring-boot-samples/spring-boot-sample-web-static/src/test/java/sample/webstatic/SampleWebStaticApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-web-static/src/test/java/sample/webstatic/SampleWebStaticApplicationTests.java @@ -18,20 +18,19 @@ package sample.webstatic; import org.junit.Test; import org.junit.runner.RunWith; -import org.springframework.boot.test.WebIntegrationTest; import sample.web.staticcontent.SampleWebStaticApplication; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.test.SpringApplicationConfiguration; import org.springframework.boot.test.TestRestTemplate; +import org.springframework.boot.test.WebIntegrationTest; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * Basic integration tests for demo application. @@ -51,9 +50,8 @@ public class SampleWebStaticApplicationTests { public void testHome() throws Exception { ResponseEntity<String> entity = new TestRestTemplate() .getForEntity("http://localhost:" + this.port, String.class); - assertEquals(HttpStatus.OK, entity.getStatusCode()); - assertTrue("Wrong body (title doesn't match):\n" + entity.getBody(), - entity.getBody().contains("<title>Static")); + assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); + assertThat(entity.getBody()).contains("<title>Static"); } @Test @@ -63,11 +61,10 @@ public class SampleWebStaticApplicationTests { "http://localhost:" + this.port + "/webjars/bootstrap/3.0.3/css/bootstrap.min.css", String.class); - assertEquals(HttpStatus.OK, entity.getStatusCode()); - assertTrue("Wrong body:\n" + entity.getBody(), entity.getBody().contains("body")); - assertEquals("Wrong content type:\n" + entity.getHeaders().getContentType(), - MediaType.valueOf("text/css;charset=UTF-8"), - entity.getHeaders().getContentType()); + assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); + assertThat(entity.getBody()).contains("body"); + assertThat(entity.getHeaders().getContentType()) + .isEqualTo(MediaType.valueOf("text/css;charset=UTF-8")); } } diff --git a/spring-boot-samples/spring-boot-sample-web-ui/src/test/java/sample/ui/SampleWebUiApplicationTests.java b/spring-boot-samples/spring-boot-sample-web-ui/src/test/java/sample/ui/SampleWebUiApplicationTests.java index 2a9cc77b4b..b24c4eb3b3 100644 --- a/spring-boot-samples/spring-boot-sample-web-ui/src/test/java/sample/ui/SampleWebUiApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-web-ui/src/test/java/sample/ui/SampleWebUiApplicationTests.java @@ -20,12 +20,12 @@ import java.net.URI; import org.junit.Test; import org.junit.runner.RunWith; -import org.springframework.boot.test.WebIntegrationTest; import sample.web.ui.SampleWebUiApplication; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.test.SpringApplicationConfiguration; import org.springframework.boot.test.TestRestTemplate; +import org.springframework.boot.test.WebIntegrationTest; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.test.annotation.DirtiesContext; @@ -33,9 +33,7 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; -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; /** * Basic integration tests for demo application. @@ -55,11 +53,9 @@ public class SampleWebUiApplicationTests { public void testHome() throws Exception { ResponseEntity<String> entity = new TestRestTemplate() .getForEntity("http://localhost:" + this.port, String.class); - assertEquals(HttpStatus.OK, entity.getStatusCode()); - assertTrue("Wrong body (title doesn't match):\n" + entity.getBody(), - entity.getBody().contains("<title>Messages")); - assertFalse("Wrong body (found layout:fragment):\n" + entity.getBody(), - entity.getBody().contains("layout:fragment")); + assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); + assertThat(entity.getBody()).contains("<title>Messages"); + assertThat(entity.getBody()).doesNotContain("layout:fragment"); } @Test @@ -69,16 +65,15 @@ public class SampleWebUiApplicationTests { map.set("summary", "FOO"); URI location = new TestRestTemplate() .postForLocation("http://localhost:" + this.port, map); - assertTrue("Wrong location:\n" + location, - location.toString().contains("localhost:" + this.port)); + assertThat(location.toString()).contains("localhost:" + this.port); } @Test public void testCss() throws Exception { ResponseEntity<String> entity = new TestRestTemplate().getForEntity( "http://localhost:" + this.port + "/css/bootstrap.min.css", String.class); - assertEquals(HttpStatus.OK, entity.getStatusCode()); - assertTrue("Wrong body:\n" + entity.getBody(), entity.getBody().contains("body")); + assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); + assertThat(entity.getBody()).contains("body"); } } diff --git a/spring-boot-samples/spring-boot-sample-web-velocity/src/test/java/sample/web/velocity/SampleWebVelocityApplicationTests.java b/spring-boot-samples/spring-boot-sample-web-velocity/src/test/java/sample/web/velocity/SampleWebVelocityApplicationTests.java index 6ea68371bb..4e39dc3b02 100644 --- a/spring-boot-samples/spring-boot-sample-web-velocity/src/test/java/sample/web/velocity/SampleWebVelocityApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-web-velocity/src/test/java/sample/web/velocity/SampleWebVelocityApplicationTests.java @@ -34,8 +34,7 @@ import org.springframework.http.ResponseEntity; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * Basic integration tests for Velocity application. @@ -56,9 +55,8 @@ public class SampleWebVelocityApplicationTests { public void testVelocityTemplate() throws Exception { ResponseEntity<String> entity = new TestRestTemplate() .getForEntity("http://localhost:" + this.port, String.class); - assertEquals(HttpStatus.OK, entity.getStatusCode()); - assertTrue("Wrong body:\n" + entity.getBody(), - entity.getBody().contains("Hello, Andy")); + assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); + assertThat(entity.getBody()).contains("Hello, Andy"); } @Test @@ -71,9 +69,9 @@ public class SampleWebVelocityApplicationTests { "http://localhost:" + this.port + "/does-not-exist", HttpMethod.GET, requestEntity, String.class); - assertEquals(HttpStatus.NOT_FOUND, responseEntity.getStatusCode()); - assertTrue("Wrong body:\n" + responseEntity.getBody(), - responseEntity.getBody().contains("Something went wrong: 404 Not Found")); + assertThat(responseEntity.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND); + assertThat(responseEntity.getBody()) + .contains("Something went wrong: 404 Not Found"); } } diff --git a/spring-boot-samples/spring-boot-sample-websocket-jetty/src/test/java/samples/websocket/jetty/SampleWebSocketsApplicationTests.java b/spring-boot-samples/spring-boot-sample-websocket-jetty/src/test/java/samples/websocket/jetty/SampleWebSocketsApplicationTests.java index a104a69961..71afa54ef0 100644 --- a/spring-boot-samples/spring-boot-sample-websocket-jetty/src/test/java/samples/websocket/jetty/SampleWebSocketsApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-websocket-jetty/src/test/java/samples/websocket/jetty/SampleWebSocketsApplicationTests.java @@ -24,7 +24,6 @@ import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.junit.Test; import org.junit.runner.RunWith; -import org.springframework.boot.test.WebIntegrationTest; import samples.websocket.jetty.client.GreetingService; import samples.websocket.jetty.client.SimpleClientWebSocketHandler; import samples.websocket.jetty.client.SimpleGreetingService; @@ -34,6 +33,7 @@ import org.springframework.boot.CommandLineRunner; import org.springframework.boot.autoconfigure.PropertyPlaceholderAutoConfiguration; import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.boot.test.SpringApplicationConfiguration; +import org.springframework.boot.test.WebIntegrationTest; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @@ -42,7 +42,7 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.web.socket.client.WebSocketConnectionManager; import org.springframework.web.socket.client.standard.StandardWebSocketClient; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(SampleJettyWebSocketsApplication.class) @@ -66,8 +66,9 @@ public class SampleWebSocketsApplicationTests { AtomicReference<String> messagePayloadReference = context .getBean(ClientConfiguration.class).messagePayload; context.close(); - assertEquals(0, count); - assertEquals("Did you say \"Hello world!\"?", messagePayloadReference.get()); + assertThat(count).isEqualTo(0); + assertThat(messagePayloadReference.get()) + .isEqualTo("Did you say \"Hello world!\"?"); } @Test @@ -81,8 +82,8 @@ public class SampleWebSocketsApplicationTests { AtomicReference<String> messagePayloadReference = context .getBean(ClientConfiguration.class).messagePayload; context.close(); - assertEquals(0, count); - assertEquals("Reversed: !dlrow olleH", messagePayloadReference.get()); + assertThat(count).isEqualTo(0); + assertThat(messagePayloadReference.get()).isEqualTo("Reversed: !dlrow olleH"); } @Configuration diff --git a/spring-boot-samples/spring-boot-sample-websocket-jetty/src/test/java/samples/websocket/jetty/echo/CustomContainerWebSocketsApplicationTests.java b/spring-boot-samples/spring-boot-sample-websocket-jetty/src/test/java/samples/websocket/jetty/echo/CustomContainerWebSocketsApplicationTests.java index 946021bfc3..23476b8c9d 100644 --- a/spring-boot-samples/spring-boot-sample-websocket-jetty/src/test/java/samples/websocket/jetty/echo/CustomContainerWebSocketsApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-websocket-jetty/src/test/java/samples/websocket/jetty/echo/CustomContainerWebSocketsApplicationTests.java @@ -24,7 +24,6 @@ import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.junit.Test; import org.junit.runner.RunWith; -import org.springframework.boot.test.WebIntegrationTest; import samples.websocket.jetty.SampleJettyWebSocketsApplication; import samples.websocket.jetty.client.GreetingService; import samples.websocket.jetty.client.SimpleClientWebSocketHandler; @@ -38,6 +37,7 @@ import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.boot.context.embedded.EmbeddedServletContainerFactory; import org.springframework.boot.context.embedded.jetty.JettyEmbeddedServletContainerFactory; import org.springframework.boot.test.SpringApplicationConfiguration; +import org.springframework.boot.test.WebIntegrationTest; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @@ -47,7 +47,7 @@ import org.springframework.util.SocketUtils; import org.springframework.web.socket.client.WebSocketConnectionManager; import org.springframework.web.socket.client.standard.StandardWebSocketClient; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration({ SampleJettyWebSocketsApplication.class, @@ -72,8 +72,9 @@ public class CustomContainerWebSocketsApplicationTests { AtomicReference<String> messagePayloadReference = context .getBean(ClientConfiguration.class).messagePayload; context.close(); - assertEquals(0, count); - assertEquals("Did you say \"Hello world!\"?", messagePayloadReference.get()); + assertThat(count).isEqualTo(0); + assertThat(messagePayloadReference.get()) + .isEqualTo("Did you say \"Hello world!\"?"); } @Test @@ -87,8 +88,8 @@ public class CustomContainerWebSocketsApplicationTests { AtomicReference<String> messagePayloadReference = context .getBean(ClientConfiguration.class).messagePayload; context.close(); - assertEquals(0, count); - assertEquals("Reversed: !dlrow olleH", messagePayloadReference.get()); + assertThat(count).isEqualTo(0); + assertThat(messagePayloadReference.get()).isEqualTo("Reversed: !dlrow olleH"); } @Configuration diff --git a/spring-boot-samples/spring-boot-sample-websocket-jetty/src/test/java/samples/websocket/jetty/snake/SnakeTimerTests.java b/spring-boot-samples/spring-boot-sample-websocket-jetty/src/test/java/samples/websocket/jetty/snake/SnakeTimerTests.java index 149978e313..bdb14a0c98 100644 --- a/spring-boot-samples/spring-boot-sample-websocket-jetty/src/test/java/samples/websocket/jetty/snake/SnakeTimerTests.java +++ b/spring-boot-samples/spring-boot-sample-websocket-jetty/src/test/java/samples/websocket/jetty/snake/SnakeTimerTests.java @@ -20,8 +20,7 @@ import java.io.IOException; import org.junit.Test; -import static org.hamcrest.CoreMatchers.is; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.BDDMockito.willThrow; import static org.mockito.Matchers.anyString; import static org.mockito.Mockito.mock; @@ -35,7 +34,7 @@ public class SnakeTimerTests { SnakeTimer.addSnake(snake); SnakeTimer.broadcast(""); - assertThat(SnakeTimer.getSnakes().size(), is(0)); + assertThat(SnakeTimer.getSnakes()).hasSize(0); } } diff --git a/spring-boot-samples/spring-boot-sample-websocket-tomcat/src/test/java/samples/websocket/tomcat/SampleWebSocketsApplicationTests.java b/spring-boot-samples/spring-boot-sample-websocket-tomcat/src/test/java/samples/websocket/tomcat/SampleWebSocketsApplicationTests.java index 20b8380a12..d64d42f953 100644 --- a/spring-boot-samples/spring-boot-sample-websocket-tomcat/src/test/java/samples/websocket/tomcat/SampleWebSocketsApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-websocket-tomcat/src/test/java/samples/websocket/tomcat/SampleWebSocketsApplicationTests.java @@ -24,7 +24,6 @@ import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.junit.Test; import org.junit.runner.RunWith; -import org.springframework.boot.test.WebIntegrationTest; import samples.websocket.tomcat.client.GreetingService; import samples.websocket.tomcat.client.SimpleClientWebSocketHandler; import samples.websocket.tomcat.client.SimpleGreetingService; @@ -34,6 +33,7 @@ import org.springframework.boot.CommandLineRunner; import org.springframework.boot.autoconfigure.PropertyPlaceholderAutoConfiguration; import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.boot.test.SpringApplicationConfiguration; +import org.springframework.boot.test.WebIntegrationTest; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @@ -42,7 +42,7 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.web.socket.client.WebSocketConnectionManager; import org.springframework.web.socket.client.standard.StandardWebSocketClient; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(SampleTomcatWebSocketApplication.class) @@ -66,8 +66,9 @@ public class SampleWebSocketsApplicationTests { AtomicReference<String> messagePayloadReference = context .getBean(ClientConfiguration.class).messagePayload; context.close(); - assertEquals(0, count); - assertEquals("Did you say \"Hello world!\"?", messagePayloadReference.get()); + assertThat(count).isEqualTo(0); + assertThat(messagePayloadReference.get()) + .isEqualTo("Did you say \"Hello world!\"?"); } @Test @@ -81,8 +82,8 @@ public class SampleWebSocketsApplicationTests { AtomicReference<String> messagePayloadReference = context .getBean(ClientConfiguration.class).messagePayload; context.close(); - assertEquals(0, count); - assertEquals("Reversed: !dlrow olleH", messagePayloadReference.get()); + assertThat(count).isEqualTo(0); + assertThat(messagePayloadReference.get()).isEqualTo("Reversed: !dlrow olleH"); } @Configuration diff --git a/spring-boot-samples/spring-boot-sample-websocket-tomcat/src/test/java/samples/websocket/tomcat/echo/CustomContainerWebSocketsApplicationTests.java b/spring-boot-samples/spring-boot-sample-websocket-tomcat/src/test/java/samples/websocket/tomcat/echo/CustomContainerWebSocketsApplicationTests.java index 8db59d37a1..16b2b814a8 100644 --- a/spring-boot-samples/spring-boot-sample-websocket-tomcat/src/test/java/samples/websocket/tomcat/echo/CustomContainerWebSocketsApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-websocket-tomcat/src/test/java/samples/websocket/tomcat/echo/CustomContainerWebSocketsApplicationTests.java @@ -24,7 +24,6 @@ import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.junit.Test; import org.junit.runner.RunWith; -import org.springframework.boot.test.WebIntegrationTest; import samples.websocket.tomcat.SampleTomcatWebSocketApplication; import samples.websocket.tomcat.client.GreetingService; import samples.websocket.tomcat.client.SimpleClientWebSocketHandler; @@ -38,6 +37,7 @@ import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.boot.context.embedded.EmbeddedServletContainerFactory; import org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainerFactory; import org.springframework.boot.test.SpringApplicationConfiguration; +import org.springframework.boot.test.WebIntegrationTest; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @@ -47,7 +47,7 @@ import org.springframework.util.SocketUtils; import org.springframework.web.socket.client.WebSocketConnectionManager; import org.springframework.web.socket.client.standard.StandardWebSocketClient; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration({ SampleTomcatWebSocketApplication.class, @@ -72,8 +72,9 @@ public class CustomContainerWebSocketsApplicationTests { AtomicReference<String> messagePayloadReference = context .getBean(ClientConfiguration.class).messagePayload; context.close(); - assertEquals(0, count); - assertEquals("Did you say \"Hello world!\"?", messagePayloadReference.get()); + assertThat(count).isEqualTo(0); + assertThat(messagePayloadReference.get()) + .isEqualTo("Did you say \"Hello world!\"?"); } @Test @@ -87,8 +88,8 @@ public class CustomContainerWebSocketsApplicationTests { AtomicReference<String> messagePayloadReference = context .getBean(ClientConfiguration.class).messagePayload; context.close(); - assertEquals(0, count); - assertEquals("Reversed: !dlrow olleH", messagePayloadReference.get()); + assertThat(count).isEqualTo(0); + assertThat(messagePayloadReference.get()).isEqualTo("Reversed: !dlrow olleH"); } @Configuration diff --git a/spring-boot-samples/spring-boot-sample-websocket-tomcat/src/test/java/samples/websocket/tomcat/snake/SnakeTimerTests.java b/spring-boot-samples/spring-boot-sample-websocket-tomcat/src/test/java/samples/websocket/tomcat/snake/SnakeTimerTests.java index eecf2ad6d8..92249d618c 100644 --- a/spring-boot-samples/spring-boot-sample-websocket-tomcat/src/test/java/samples/websocket/tomcat/snake/SnakeTimerTests.java +++ b/spring-boot-samples/spring-boot-sample-websocket-tomcat/src/test/java/samples/websocket/tomcat/snake/SnakeTimerTests.java @@ -20,8 +20,7 @@ import java.io.IOException; import org.junit.Test; -import static org.hamcrest.CoreMatchers.is; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.BDDMockito.willThrow; import static org.mockito.Matchers.anyString; import static org.mockito.Mockito.mock; @@ -35,6 +34,6 @@ public class SnakeTimerTests { SnakeTimer.addSnake(snake); SnakeTimer.broadcast(""); - assertThat(SnakeTimer.getSnakes().size(), is(0)); + assertThat(SnakeTimer.getSnakes()).hasSize(0); } } diff --git a/spring-boot-samples/spring-boot-sample-websocket-undertow/src/test/java/samples/websocket/undertow/SampleWebSocketsApplicationTests.java b/spring-boot-samples/spring-boot-sample-websocket-undertow/src/test/java/samples/websocket/undertow/SampleWebSocketsApplicationTests.java index 65edef653b..8c4a125248 100644 --- a/spring-boot-samples/spring-boot-sample-websocket-undertow/src/test/java/samples/websocket/undertow/SampleWebSocketsApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-websocket-undertow/src/test/java/samples/websocket/undertow/SampleWebSocketsApplicationTests.java @@ -24,7 +24,6 @@ import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.junit.Test; import org.junit.runner.RunWith; -import org.springframework.boot.test.WebIntegrationTest; import samples.websocket.undertow.client.GreetingService; import samples.websocket.undertow.client.SimpleClientWebSocketHandler; import samples.websocket.undertow.client.SimpleGreetingService; @@ -34,6 +33,7 @@ import org.springframework.boot.CommandLineRunner; import org.springframework.boot.autoconfigure.PropertyPlaceholderAutoConfiguration; import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.boot.test.SpringApplicationConfiguration; +import org.springframework.boot.test.WebIntegrationTest; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @@ -42,7 +42,7 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.web.socket.client.WebSocketConnectionManager; import org.springframework.web.socket.client.standard.StandardWebSocketClient; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(SampleUndertowWebSocketsApplication.class) @@ -66,8 +66,9 @@ public class SampleWebSocketsApplicationTests { AtomicReference<String> messagePayloadReference = context .getBean(ClientConfiguration.class).messagePayload; context.close(); - assertEquals(0, count); - assertEquals("Did you say \"Hello world!\"?", messagePayloadReference.get()); + assertThat(count).isEqualTo(0); + assertThat(messagePayloadReference.get()) + .isEqualTo("Did you say \"Hello world!\"?"); } @Test @@ -81,8 +82,8 @@ public class SampleWebSocketsApplicationTests { AtomicReference<String> messagePayloadReference = context .getBean(ClientConfiguration.class).messagePayload; context.close(); - assertEquals(0, count); - assertEquals("Reversed: !dlrow olleH", messagePayloadReference.get()); + assertThat(count).isEqualTo(0); + assertThat(messagePayloadReference.get()).isEqualTo("Reversed: !dlrow olleH"); } @Configuration diff --git a/spring-boot-samples/spring-boot-sample-websocket-undertow/src/test/java/samples/websocket/undertow/echo/CustomContainerWebSocketsApplicationTests.java b/spring-boot-samples/spring-boot-sample-websocket-undertow/src/test/java/samples/websocket/undertow/echo/CustomContainerWebSocketsApplicationTests.java index ce73a6a8e5..0d1a8598f3 100644 --- a/spring-boot-samples/spring-boot-sample-websocket-undertow/src/test/java/samples/websocket/undertow/echo/CustomContainerWebSocketsApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-websocket-undertow/src/test/java/samples/websocket/undertow/echo/CustomContainerWebSocketsApplicationTests.java @@ -24,7 +24,6 @@ import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.junit.Test; import org.junit.runner.RunWith; -import org.springframework.boot.test.WebIntegrationTest; import samples.websocket.undertow.SampleUndertowWebSocketsApplication; import samples.websocket.undertow.client.GreetingService; import samples.websocket.undertow.client.SimpleClientWebSocketHandler; @@ -38,6 +37,7 @@ import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.boot.context.embedded.EmbeddedServletContainerFactory; import org.springframework.boot.context.embedded.undertow.UndertowEmbeddedServletContainerFactory; import org.springframework.boot.test.SpringApplicationConfiguration; +import org.springframework.boot.test.WebIntegrationTest; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @@ -47,7 +47,7 @@ import org.springframework.util.SocketUtils; import org.springframework.web.socket.client.WebSocketConnectionManager; import org.springframework.web.socket.client.standard.StandardWebSocketClient; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration({ SampleUndertowWebSocketsApplication.class, @@ -72,8 +72,9 @@ public class CustomContainerWebSocketsApplicationTests { AtomicReference<String> messagePayloadReference = context .getBean(ClientConfiguration.class).messagePayload; context.close(); - assertEquals(0, count); - assertEquals("Did you say \"Hello world!\"?", messagePayloadReference.get()); + assertThat(count).isEqualTo(0); + assertThat(messagePayloadReference.get()) + .isEqualTo("Did you say \"Hello world!\"?"); } @Test @@ -87,8 +88,8 @@ public class CustomContainerWebSocketsApplicationTests { AtomicReference<String> messagePayloadReference = context .getBean(ClientConfiguration.class).messagePayload; context.close(); - assertEquals(0, count); - assertEquals("Reversed: !dlrow olleH", messagePayloadReference.get()); + assertThat(count).isEqualTo(0); + assertThat(messagePayloadReference.get()).isEqualTo("Reversed: !dlrow olleH"); } @Configuration diff --git a/spring-boot-samples/spring-boot-sample-websocket-undertow/src/test/java/samples/websocket/undertow/snake/SnakeTimerTests.java b/spring-boot-samples/spring-boot-sample-websocket-undertow/src/test/java/samples/websocket/undertow/snake/SnakeTimerTests.java index 64bbd24bf3..4fcd726549 100644 --- a/spring-boot-samples/spring-boot-sample-websocket-undertow/src/test/java/samples/websocket/undertow/snake/SnakeTimerTests.java +++ b/spring-boot-samples/spring-boot-sample-websocket-undertow/src/test/java/samples/websocket/undertow/snake/SnakeTimerTests.java @@ -20,8 +20,7 @@ import java.io.IOException; import org.junit.Test; -import static org.hamcrest.CoreMatchers.is; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.BDDMockito.willThrow; import static org.mockito.Matchers.anyString; import static org.mockito.Mockito.mock; @@ -35,6 +34,6 @@ public class SnakeTimerTests { SnakeTimer.addSnake(snake); SnakeTimer.broadcast(""); - assertThat(SnakeTimer.getSnakes().size(), is(0)); + assertThat(SnakeTimer.getSnakes()).hasSize(0); } } diff --git a/spring-boot-samples/spring-boot-sample-ws/src/test/java/sample/ws/SampleWsApplicationTests.java b/spring-boot-samples/spring-boot-sample-ws/src/test/java/sample/ws/SampleWsApplicationTests.java index 2a2a79dc37..2f71d01d59 100644 --- a/spring-boot-samples/spring-boot-sample-ws/src/test/java/sample/ws/SampleWsApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-ws/src/test/java/sample/ws/SampleWsApplicationTests.java @@ -32,8 +32,7 @@ import org.springframework.boot.test.WebIntegrationTest; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.ws.client.core.WebServiceTemplate; -import static org.hamcrest.Matchers.containsString; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(SampleWsApplication.class) @@ -68,7 +67,7 @@ public class SampleWsApplicationTests { StreamResult result = new StreamResult(System.out); this.webServiceTemplate.sendSourceAndReceiveToResult(source, result); - assertThat(this.output.toString(), containsString("Booking holiday for")); + assertThat(this.output.toString()).contains("Booking holiday for"); } } diff --git a/spring-boot-samples/spring-boot-sample-xml/src/test/java/sample/xml/SampleSpringXmlApplicationTests.java b/spring-boot-samples/spring-boot-sample-xml/src/test/java/sample/xml/SampleSpringXmlApplicationTests.java index 0b25755ac0..b8d8094e99 100644 --- a/spring-boot-samples/spring-boot-sample-xml/src/test/java/sample/xml/SampleSpringXmlApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-xml/src/test/java/sample/xml/SampleSpringXmlApplicationTests.java @@ -21,7 +21,7 @@ import org.junit.Test; import org.springframework.boot.test.OutputCapture; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; public class SampleSpringXmlApplicationTests { @@ -32,7 +32,7 @@ public class SampleSpringXmlApplicationTests { public void testDefaultSettings() throws Exception { SampleSpringXmlApplication.main(new String[0]); String output = this.outputCapture.toString(); - assertTrue("Wrong output: " + output, output.contains("Hello World")); + assertThat(output).contains("Hello World"); } } From e214fa0949b205864efd8b2411ea1485c50bd9f9 Mon Sep 17 00:00:00 2001 From: Phillip Webb <pwebb@pivotal.io> Date: Sat, 6 Feb 2016 15:09:40 -0800 Subject: [PATCH 08/10] Use AssertJ in spring-boot-integration-tests See gh-5083 --- .../boot/gradle/BootRunResourceTests.java | 8 +- .../boot/gradle/ClassifierTests.java | 6 +- .../boot/gradle/FullyExecutableJarTests.java | 29 ++++--- .../gradle/MultiProjectRepackagingTests.java | 11 ++- .../boot/gradle/NoJarTests.java | 4 +- .../boot/gradle/ProjectCreator.java | 1 + .../boot/gradle/RepackagingTests.java | 76 ++++++++++--------- .../springframework/boot/gradle/Versions.java | 1 + .../boot/gradle/WarPackagingTests.java | 22 ++---- .../launchscript/SysVinitLaunchScriptIT.java | 60 ++++++++------- .../HelloWebSecurityApplicationTests.java | 10 +-- 11 files changed, 110 insertions(+), 118 deletions(-) diff --git a/spring-boot-integration-tests/spring-boot-gradle-tests/src/test/java/org/springframework/boot/gradle/BootRunResourceTests.java b/spring-boot-integration-tests/spring-boot-gradle-tests/src/test/java/org/springframework/boot/gradle/BootRunResourceTests.java index f9f50ad489..28a4c38780 100644 --- a/spring-boot-integration-tests/spring-boot-gradle-tests/src/test/java/org/springframework/boot/gradle/BootRunResourceTests.java +++ b/spring-boot-integration-tests/spring-boot-gradle-tests/src/test/java/org/springframework/boot/gradle/BootRunResourceTests.java @@ -25,8 +25,7 @@ import org.junit.Test; import org.springframework.boot.test.OutputCapture; -import static org.hamcrest.Matchers.containsString; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; /** * Integration tests for bootRun's resource handling @@ -53,7 +52,7 @@ public class BootRunResourceTests { .withArguments("-PbootVersion=" + BOOT_VERSION, "-PaddResources=true") .run(); - assertThat(this.output.toString(), containsString("src/main/resources/test.txt")); + assertThat(this.output.toString()).contains("src/main/resources/test.txt"); } @Test @@ -61,8 +60,7 @@ public class BootRunResourceTests { project.newBuild().forTasks("clean", "bootRun") .withArguments("-PbootVersion=" + BOOT_VERSION, "-PaddResources=false") .run(); - assertThat(this.output.toString(), - containsString("build/resources/main/test.txt")); + assertThat(this.output.toString()).contains("build/resources/main/test.txt"); } } diff --git a/spring-boot-integration-tests/spring-boot-gradle-tests/src/test/java/org/springframework/boot/gradle/ClassifierTests.java b/spring-boot-integration-tests/spring-boot-gradle-tests/src/test/java/org/springframework/boot/gradle/ClassifierTests.java index 257beb76e3..5b6c963f1e 100644 --- a/spring-boot-integration-tests/spring-boot-gradle-tests/src/test/java/org/springframework/boot/gradle/ClassifierTests.java +++ b/spring-boot-integration-tests/spring-boot-gradle-tests/src/test/java/org/springframework/boot/gradle/ClassifierTests.java @@ -21,7 +21,7 @@ import java.util.jar.JarFile; import org.gradle.tooling.ProjectConnection; import org.junit.Test; -import static org.junit.Assert.assertNotNull; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for using the Gradle plugin's support for installing artifacts @@ -52,10 +52,10 @@ public class ClassifierTests { private void checkFilesExist(String name) throws Exception { JarFile jar = new JarFile("target/" + name + "/build/libs/" + name + ".jar"); - assertNotNull(jar.getManifest()); + assertThat(jar.getManifest()).isNotNull(); jar.close(); jar = new JarFile("target/" + name + "/build/libs/" + name + "-exec.jar"); - assertNotNull(jar.getManifest()); + assertThat(jar.getManifest()).isNotNull(); jar.close(); } diff --git a/spring-boot-integration-tests/spring-boot-gradle-tests/src/test/java/org/springframework/boot/gradle/FullyExecutableJarTests.java b/spring-boot-integration-tests/spring-boot-gradle-tests/src/test/java/org/springframework/boot/gradle/FullyExecutableJarTests.java index 4396ea0c7a..ffdfc54267 100644 --- a/spring-boot-integration-tests/spring-boot-gradle-tests/src/test/java/org/springframework/boot/gradle/FullyExecutableJarTests.java +++ b/spring-boot-integration-tests/spring-boot-gradle-tests/src/test/java/org/springframework/boot/gradle/FullyExecutableJarTests.java @@ -28,8 +28,7 @@ import org.gradle.tooling.ProjectConnection; import org.junit.BeforeClass; import org.junit.Test; -import static org.hamcrest.Matchers.is; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; /** * Integration tests for creating a fully executable jar with Gradle. @@ -53,7 +52,7 @@ public class FullyExecutableJarTests { .withArguments("-PbootVersion=" + BOOT_VERSION).run(); File buildLibs = new File("target/executable-jar/build/libs"); File executableJar = new File(buildLibs, "executable-jar.jar"); - assertThat(isFullyExecutable(executableJar), is(false)); + assertThat(isFullyExecutable(executableJar)).isFalse(); } @Test @@ -62,7 +61,7 @@ public class FullyExecutableJarTests { "-PbootVersion=" + BOOT_VERSION, "-PextensionExecutable=true").run(); File buildLibs = new File("target/executable-jar/build/libs"); File executableJar = new File(buildLibs, "executable-jar.jar"); - assertThat(isFullyExecutable(executableJar), is(true)); + assertThat(isFullyExecutable(executableJar)).isTrue(); } @Test @@ -72,7 +71,7 @@ public class FullyExecutableJarTests { .run(); File buildLibs = new File("target/executable-jar/build/libs"); File executableJar = new File(buildLibs, "executable-jar.jar"); - assertThat(isFullyExecutable(executableJar), is(true)); + assertThat(isFullyExecutable(executableJar)).isTrue(); } @Test @@ -83,7 +82,7 @@ public class FullyExecutableJarTests { .run(); File buildLibs = new File("target/executable-jar/build/libs"); File executableJar = new File(buildLibs, "executable-jar.jar"); - assertThat(isFullyExecutable(executableJar), is(true)); + assertThat(isFullyExecutable(executableJar)).isTrue(); } @Test @@ -93,8 +92,8 @@ public class FullyExecutableJarTests { .run(); File buildLibs = new File("target/executable-jar/build/libs"); File executableJar = new File(buildLibs, "executable-jar.jar"); - assertThat(isFullyExecutable(executableJar), is(true)); - assertThat(containsLine("# Provides:.*__task__", executableJar), is(true)); + assertThat(isFullyExecutable(executableJar)).isTrue(); + assertThat(containsLine("# Provides:.*__task__", executableJar)).isTrue(); } @Test @@ -103,8 +102,8 @@ public class FullyExecutableJarTests { "-PbootVersion=" + BOOT_VERSION, "-PextensionProperties=true").run(); File buildLibs = new File("target/executable-jar/build/libs"); File executableJar = new File(buildLibs, "executable-jar.jar"); - assertThat(isFullyExecutable(executableJar), is(true)); - assertThat(containsLine("# Provides:.*__extension__", executableJar), is(true)); + assertThat(isFullyExecutable(executableJar)).isTrue(); + assertThat(containsLine("# Provides:.*__extension__", executableJar)).isTrue(); } @Test @@ -115,8 +114,8 @@ public class FullyExecutableJarTests { .run(); File buildLibs = new File("target/executable-jar/build/libs"); File executableJar = new File(buildLibs, "executable-jar.jar"); - assertThat(isFullyExecutable(executableJar), is(true)); - assertThat(containsLine("# Provides:.*__task__", executableJar), is(true)); + assertThat(isFullyExecutable(executableJar)).isTrue(); + assertThat(containsLine("# Provides:.*__task__", executableJar)).isTrue(); } @Test @@ -126,7 +125,7 @@ public class FullyExecutableJarTests { .run(); File buildLibs = new File("target/executable-jar/build/libs"); File executableJar = new File(buildLibs, "executable-jar.jar"); - assertThat(containsLine("Custom task script", executableJar), is(true)); + assertThat(containsLine("Custom task script", executableJar)).isTrue(); } @Test @@ -136,7 +135,7 @@ public class FullyExecutableJarTests { .run(); File buildLibs = new File("target/executable-jar/build/libs"); File executableJar = new File(buildLibs, "executable-jar.jar"); - assertThat(containsLine("Custom extension script", executableJar), is(true)); + assertThat(containsLine("Custom extension script", executableJar)).isTrue(); } @Test @@ -147,7 +146,7 @@ public class FullyExecutableJarTests { .run(); File buildLibs = new File("target/executable-jar/build/libs"); File executableJar = new File(buildLibs, "executable-jar.jar"); - assertThat(containsLine("Custom task script", executableJar), is(true)); + assertThat(containsLine("Custom task script", executableJar)).isTrue(); } private boolean isFullyExecutable(File file) throws IOException { diff --git a/spring-boot-integration-tests/spring-boot-gradle-tests/src/test/java/org/springframework/boot/gradle/MultiProjectRepackagingTests.java b/spring-boot-integration-tests/spring-boot-gradle-tests/src/test/java/org/springframework/boot/gradle/MultiProjectRepackagingTests.java index 6d211a790a..ac83d90e31 100644 --- a/spring-boot-integration-tests/spring-boot-gradle-tests/src/test/java/org/springframework/boot/gradle/MultiProjectRepackagingTests.java +++ b/spring-boot-integration-tests/spring-boot-gradle-tests/src/test/java/org/springframework/boot/gradle/MultiProjectRepackagingTests.java @@ -22,8 +22,7 @@ import java.util.jar.JarFile; import org.gradle.tooling.ProjectConnection; import org.junit.Test; -import static org.hamcrest.Matchers.notNullValue; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; /** * Integration tests for Gradle repackaging with a multi-project build. @@ -43,8 +42,8 @@ public class MultiProjectRepackagingTests { File buildLibs = new File( "target/multi-project-transitive-file-dependency/main/build/libs"); JarFile jarFile = new JarFile(new File(buildLibs, "main.jar")); - assertThat(jarFile.getEntry("lib/commons-logging-1.1.3.jar"), notNullValue()); - assertThat(jarFile.getEntry("lib/foo.jar"), notNullValue()); + assertThat(jarFile.getEntry("lib/commons-logging-1.1.3.jar")).isNotNull(); + assertThat(jarFile.getEntry("lib/foo.jar")).isNotNull(); jarFile.close(); } @@ -58,7 +57,7 @@ public class MultiProjectRepackagingTests { "target/multi-project-common-file-dependency/build/libs"); JarFile jarFile = new JarFile( new File(buildLibs, "multi-project-common-file-dependency.jar")); - assertThat(jarFile.getEntry("lib/foo.jar"), notNullValue()); + assertThat(jarFile.getEntry("lib/foo.jar")).isNotNull(); jarFile.close(); } @@ -71,7 +70,7 @@ public class MultiProjectRepackagingTests { File buildLibs = new File( "target/multi-project-runtime-project-dependency/projectA/build/libs"); JarFile jarFile = new JarFile(new File(buildLibs, "projectA.jar")); - assertThat(jarFile.getEntry("lib/projectB.jar"), notNullValue()); + assertThat(jarFile.getEntry("lib/projectB.jar")).isNotNull(); jarFile.close(); } diff --git a/spring-boot-integration-tests/spring-boot-gradle-tests/src/test/java/org/springframework/boot/gradle/NoJarTests.java b/spring-boot-integration-tests/spring-boot-gradle-tests/src/test/java/org/springframework/boot/gradle/NoJarTests.java index 26fb8f1eaf..17962c6ddd 100644 --- a/spring-boot-integration-tests/spring-boot-gradle-tests/src/test/java/org/springframework/boot/gradle/NoJarTests.java +++ b/spring-boot-integration-tests/spring-boot-gradle-tests/src/test/java/org/springframework/boot/gradle/NoJarTests.java @@ -21,7 +21,7 @@ import java.io.File; import org.gradle.tooling.ProjectConnection; import org.junit.Test; -import static org.junit.Assert.assertFalse; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for using the Gradle plugin's support for flat directory repos @@ -39,7 +39,7 @@ public class NoJarTests { this.project = new ProjectCreator().createProject("nojar"); this.project.newBuild().forTasks("build") .withArguments("-PbootVersion=" + BOOT_VERSION, "--stacktrace").run(); - assertFalse(new File("target/nojar/build/libs").exists()); + assertThat(new File("target/nojar/build/libs")).doesNotExist(); } } diff --git a/spring-boot-integration-tests/spring-boot-gradle-tests/src/test/java/org/springframework/boot/gradle/ProjectCreator.java b/spring-boot-integration-tests/spring-boot-gradle-tests/src/test/java/org/springframework/boot/gradle/ProjectCreator.java index cb1a6be692..3a22370a0c 100644 --- a/spring-boot-integration-tests/spring-boot-gradle-tests/src/test/java/org/springframework/boot/gradle/ProjectCreator.java +++ b/spring-boot-integration-tests/spring-boot-gradle-tests/src/test/java/org/springframework/boot/gradle/ProjectCreator.java @@ -62,4 +62,5 @@ public class ProjectCreator { ((DefaultGradleConnector) gradleConnector).embedded(true); return gradleConnector.forProjectDirectory(projectDirectory).connect(); } + } diff --git a/spring-boot-integration-tests/spring-boot-gradle-tests/src/test/java/org/springframework/boot/gradle/RepackagingTests.java b/spring-boot-integration-tests/spring-boot-gradle-tests/src/test/java/org/springframework/boot/gradle/RepackagingTests.java index 683a26df09..87b62ccdaf 100644 --- a/spring-boot-integration-tests/spring-boot-gradle-tests/src/test/java/org/springframework/boot/gradle/RepackagingTests.java +++ b/spring-boot-integration-tests/spring-boot-gradle-tests/src/test/java/org/springframework/boot/gradle/RepackagingTests.java @@ -26,10 +26,7 @@ import org.junit.Test; import org.springframework.util.FileCopyUtils; -import static org.hamcrest.Matchers.notNullValue; -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; /** * Integration tests for gradle repackaging. @@ -55,10 +52,11 @@ public class RepackagingTests { .run(); File buildLibs = new File("target/repackage/build/libs"); File repackageFile = new File(buildLibs, "repackage.jar"); - assertTrue(repackageFile.exists()); - assertTrue(new File(buildLibs, "repackage.jar.original").exists()); - assertFalse(new File(buildLibs, "repackage-sources.jar.original").exists()); - assertTrue(isDevToolsJarIncluded(repackageFile)); + assertThat(repackageFile.exists()).isTrue(); + assertThat(new File(buildLibs, "repackage.jar.original").exists()).isTrue(); + assertThat(new File(buildLibs, "repackage-sources.jar.original").exists()) + .isFalse(); + assertThat(isDevToolsJarIncluded(repackageFile)).isTrue(); } @Test @@ -68,9 +66,10 @@ public class RepackagingTests { "-PexcludeDevtools=false") .run(); File buildLibs = new File("target/repackage/build/libs"); - assertTrue(new File(buildLibs, "repackage.jar").exists()); - assertFalse(new File(buildLibs, "repackage.jar.original").exists()); - assertFalse(new File(buildLibs, "repackage-sources.jar.original").exists()); + assertThat(new File(buildLibs, "repackage.jar").exists()).isTrue(); + assertThat(new File(buildLibs, "repackage.jar.original").exists()).isFalse(); + assertThat(new File(buildLibs, "repackage-sources.jar.original").exists()) + .isFalse(); } @Test @@ -80,11 +79,12 @@ public class RepackagingTests { "-PexcludeDevtools=false") .run(); File buildLibs = new File("target/repackage/build/libs"); - assertTrue(new File(buildLibs, "repackage.jar").exists()); - assertFalse(new File(buildLibs, "repackage.jar.original").exists()); - assertFalse(new File(buildLibs, "repackage-sources.jar.original").exists()); - assertTrue(new File(buildLibs, "custom.jar").exists()); - assertTrue(new File(buildLibs, "custom.jar.original").exists()); + assertThat(new File(buildLibs, "repackage.jar").exists()).isTrue(); + assertThat(new File(buildLibs, "repackage.jar.original").exists()).isFalse(); + assertThat(new File(buildLibs, "repackage-sources.jar.original").exists()) + .isFalse(); + assertThat(new File(buildLibs, "custom.jar").exists()).isTrue(); + assertThat(new File(buildLibs, "custom.jar.original").exists()).isTrue(); } @Test @@ -95,11 +95,12 @@ public class RepackagingTests { "-PexcludeDevtools=false") .run(); File buildLibs = new File("target/repackage/build/libs"); - assertTrue(new File(buildLibs, "repackage.jar").exists()); - assertFalse(new File(buildLibs, "repackage.jar.original").exists()); - assertFalse(new File(buildLibs, "repackage-sources.jar.original").exists()); - assertTrue(new File(buildLibs, "custom.jar").exists()); - assertTrue(new File(buildLibs, "custom.jar.original").exists()); + assertThat(new File(buildLibs, "repackage.jar").exists()).isTrue(); + assertThat(new File(buildLibs, "repackage.jar.original").exists()).isFalse(); + assertThat(new File(buildLibs, "repackage-sources.jar.original").exists()) + .isFalse(); + assertThat(new File(buildLibs, "custom.jar").exists()).isTrue(); + assertThat(new File(buildLibs, "custom.jar.original").exists()).isTrue(); } @Test @@ -109,11 +110,12 @@ public class RepackagingTests { "-PexcludeDevtools=false") .run(); File buildLibs = new File("target/repackage/build/libs"); - assertTrue(new File(buildLibs, "repackage.jar").exists()); - assertTrue(new File(buildLibs, "repackage.jar.original").exists()); - assertFalse(new File(buildLibs, "repackage-sources.jar.original").exists()); - assertTrue(new File(buildLibs, "custom.jar").exists()); - assertTrue(new File(buildLibs, "custom.jar.original").exists()); + assertThat(new File(buildLibs, "repackage.jar").exists()).isTrue(); + assertThat(new File(buildLibs, "repackage.jar.original").exists()).isTrue(); + assertThat(new File(buildLibs, "repackage-sources.jar.original").exists()) + .isFalse(); + assertThat(new File(buildLibs, "custom.jar").exists()).isTrue(); + assertThat(new File(buildLibs, "custom.jar.original").exists()).isTrue(); } @Test @@ -124,11 +126,12 @@ public class RepackagingTests { "-PexcludeDevtools=false") .run(); File buildLibs = new File("target/repackage/build/libs"); - assertTrue(new File(buildLibs, "repackage.jar").exists()); - assertTrue(new File(buildLibs, "repackage.jar.original").exists()); - assertFalse(new File(buildLibs, "repackage-sources.jar.original").exists()); - assertTrue(new File(buildLibs, "custom.jar").exists()); - assertTrue(new File(buildLibs, "custom.jar.original").exists()); + assertThat(new File(buildLibs, "repackage.jar").exists()).isTrue(); + assertThat(new File(buildLibs, "repackage.jar.original").exists()).isTrue(); + assertThat(new File(buildLibs, "repackage-sources.jar.original").exists()) + .isFalse(); + assertThat(new File(buildLibs, "custom.jar").exists()).isTrue(); + assertThat(new File(buildLibs, "custom.jar.original").exists()).isTrue(); } @Test @@ -141,7 +144,7 @@ public class RepackagingTests { .run(); File buildLibs = new File("target/repackage/build/libs"); JarFile jarFile = new JarFile(new File(buildLibs, "repackage.jar")); - assertThat(jarFile.getEntry("lib/foo.jar"), notNullValue()); + assertThat(jarFile.getEntry("lib/foo.jar")).isNotNull(); jarFile.close(); } @@ -153,10 +156,11 @@ public class RepackagingTests { .run(); File buildLibs = new File("target/repackage/build/libs"); File repackageFile = new File(buildLibs, "repackage.jar"); - assertTrue(repackageFile.exists()); - assertTrue(new File(buildLibs, "repackage.jar.original").exists()); - assertFalse(new File(buildLibs, "repackage-sources.jar.original").exists()); - assertFalse(isDevToolsJarIncluded(repackageFile)); + assertThat(repackageFile.exists()).isTrue(); + assertThat(new File(buildLibs, "repackage.jar.original").exists()).isTrue(); + assertThat(new File(buildLibs, "repackage-sources.jar.original").exists()) + .isFalse(); + assertThat(isDevToolsJarIncluded(repackageFile)).isFalse(); } private boolean isDevToolsJarIncluded(File repackageFile) throws IOException { diff --git a/spring-boot-integration-tests/spring-boot-gradle-tests/src/test/java/org/springframework/boot/gradle/Versions.java b/spring-boot-integration-tests/spring-boot-gradle-tests/src/test/java/org/springframework/boot/gradle/Versions.java index f2dba96c60..675e6a81a0 100644 --- a/spring-boot-integration-tests/spring-boot-gradle-tests/src/test/java/org/springframework/boot/gradle/Versions.java +++ b/spring-boot-integration-tests/spring-boot-gradle-tests/src/test/java/org/springframework/boot/gradle/Versions.java @@ -62,4 +62,5 @@ public final class Versions { throw new IllegalStateException("Failed to evaluate expression", ex); } } + } diff --git a/spring-boot-integration-tests/spring-boot-gradle-tests/src/test/java/org/springframework/boot/gradle/WarPackagingTests.java b/spring-boot-integration-tests/spring-boot-gradle-tests/src/test/java/org/springframework/boot/gradle/WarPackagingTests.java index 132a02b965..88971fa865 100644 --- a/spring-boot-integration-tests/spring-boot-gradle-tests/src/test/java/org/springframework/boot/gradle/WarPackagingTests.java +++ b/spring-boot-integration-tests/spring-boot-gradle-tests/src/test/java/org/springframework/boot/gradle/WarPackagingTests.java @@ -30,8 +30,7 @@ import org.gradle.tooling.ProjectConnection; import org.junit.BeforeClass; import org.junit.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for war packaging with Gradle to ensure that only the Servlet container and its @@ -59,8 +58,7 @@ public class WarPackagingTests { "asm-", "javax.websocket-api-", "asm-tree-", "asm-commons-", "websocket-common-", "jetty-annotations-", "javax-websocket-client-impl-", "websocket-client-", - "websocket-server-", "jetty-xml-", - "websocket-servlet-")); + "websocket-server-", "jetty-xml-", "websocket-servlet-")); private static final String BOOT_VERSION = Versions.getBootVersion(); @@ -107,35 +105,26 @@ public class WarPackagingTests { private void checkWebInfLibProvidedEntries(JarFile war, Set<String> expectedEntries) throws IOException { Set<String> entries = getWebInfLibProvidedEntries(war); - - assertEquals("Expected " + expectedEntries.size() + " but found " + entries.size() - + ": " + entries, expectedEntries.size(), entries.size()); - + assertThat(entries).hasSameSizeAs(expectedEntries); List<String> unexpectedLibProvidedEntries = new ArrayList<String>(); for (String entry : entries) { if (!isExpectedInWebInfLibProvided(entry, expectedEntries)) { unexpectedLibProvidedEntries.add(entry); } } - assertTrue( - "Found unexpected entries in WEB-INF/lib-provided: " - + unexpectedLibProvidedEntries, - unexpectedLibProvidedEntries.isEmpty()); + assertThat(unexpectedLibProvidedEntries.isEmpty()); } private void checkWebInfLibEntries(JarFile war, Set<String> entriesOnlyInLibProvided) throws IOException { Set<String> entries = getWebInfLibEntries(war); - List<String> unexpectedLibEntries = new ArrayList<String>(); for (String entry : entries) { if (!isExpectedInWebInfLib(entry, entriesOnlyInLibProvided)) { unexpectedLibEntries.add(entry); } } - - assertTrue("Found unexpected entries in WEB-INF/lib: " + unexpectedLibEntries, - unexpectedLibEntries.isEmpty()); + assertThat(unexpectedLibEntries.isEmpty()); } private Set<String> getWebInfLibProvidedEntries(JarFile war) throws IOException { @@ -189,4 +178,5 @@ public class WarPackagingTests { } return true; } + } diff --git a/spring-boot-integration-tests/spring-boot-launch-script-tests/src/test/java/org/springframework/boot/launchscript/SysVinitLaunchScriptIT.java b/spring-boot-integration-tests/spring-boot-launch-script-tests/src/test/java/org/springframework/boot/launchscript/SysVinitLaunchScriptIT.java index 22ab687d1e..d1e96863f8 100644 --- a/spring-boot-integration-tests/spring-boot-launch-script-tests/src/test/java/org/springframework/boot/launchscript/SysVinitLaunchScriptIT.java +++ b/spring-boot-integration-tests/spring-boot-launch-script-tests/src/test/java/org/springframework/boot/launchscript/SysVinitLaunchScriptIT.java @@ -41,18 +41,19 @@ import com.github.dockerjava.core.command.AttachContainerResultCallback; import com.github.dockerjava.core.command.BuildImageResultCallback; import com.github.dockerjava.jaxrs.AbstrSyncDockerCmdExec; import com.github.dockerjava.jaxrs.DockerCmdExecFactoryImpl; -import org.hamcrest.Matcher; +import org.assertj.core.api.Condition; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; import org.springframework.boot.ansi.AnsiColor; +import org.springframework.boot.test.assertj.Matched; +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.junit.Assert.assertThat; import static org.junit.Assume.assumeThat; /** @@ -90,70 +91,70 @@ public class SysVinitLaunchScriptIT { @Test public void statusWhenStopped() throws Exception { String output = doTest("status-when-stopped.sh"); - assertThat(output, containsString("Status: 3")); - assertThat(output, containsColoredString(AnsiColor.RED, "Not running")); + assertThat(output).contains("Status: 3"); + assertThat(output).has(coloredString(AnsiColor.RED, "Not running")); } @Test public void statusWhenStarted() throws Exception { String output = doTest("status-when-started.sh"); - assertThat(output, containsString("Status: 0")); - assertThat(output, containsColoredString(AnsiColor.GREEN, - "Started [" + extractPid(output) + "]")); + assertThat(output).contains("Status: 0"); + assertThat(output).has( + coloredString(AnsiColor.GREEN, "Started [" + extractPid(output) + "]")); } @Test public void statusWhenKilled() throws Exception { String output = doTest("status-when-killed.sh"); - assertThat(output, containsString("Status: 1")); - assertThat(output, containsColoredString(AnsiColor.RED, + assertThat(output).contains("Status: 1"); + assertThat(output).has(coloredString(AnsiColor.RED, "Not running (process " + extractPid(output) + " not found)")); } @Test public void stopWhenStopped() throws Exception { String output = doTest("stop-when-stopped.sh"); - assertThat(output, containsString("Status: 0")); - assertThat(output, containsColoredString(AnsiColor.YELLOW, - "Not running (pidfile not found)")); + assertThat(output).contains("Status: 0"); + assertThat(output) + .has(coloredString(AnsiColor.YELLOW, "Not running (pidfile not found)")); } @Test public void startWhenStarted() throws Exception { String output = doTest("start-when-started.sh"); - assertThat(output, containsString("Status: 0")); - assertThat(output, containsColoredString(AnsiColor.YELLOW, + assertThat(output).contains("Status: 0"); + assertThat(output).has(coloredString(AnsiColor.YELLOW, "Already running [" + extractPid(output) + "]")); } @Test public void restartWhenStopped() throws Exception { String output = doTest("restart-when-stopped.sh"); - assertThat(output, containsString("Status: 0")); - assertThat(output, containsColoredString(AnsiColor.YELLOW, - "Not running (pidfile not found)")); - assertThat(output, containsColoredString(AnsiColor.GREEN, - "Started [" + extractPid(output) + "]")); + assertThat(output).contains("Status: 0"); + assertThat(output) + .has(coloredString(AnsiColor.YELLOW, "Not running (pidfile not found)")); + assertThat(output).has( + coloredString(AnsiColor.GREEN, "Started [" + extractPid(output) + "]")); } @Test public void restartWhenStarted() throws Exception { String output = doTest("restart-when-started.sh"); - assertThat(output, containsString("Status: 0")); - assertThat(output, containsColoredString(AnsiColor.GREEN, + assertThat(output).contains("Status: 0"); + assertThat(output).has(coloredString(AnsiColor.GREEN, "Started [" + extract("PID1", output) + "]")); - assertThat(output, containsColoredString(AnsiColor.GREEN, + assertThat(output).has(coloredString(AnsiColor.GREEN, "Stopped [" + extract("PID1", output) + "]")); - assertThat(output, containsColoredString(AnsiColor.GREEN, + assertThat(output).has(coloredString(AnsiColor.GREEN, "Started [" + extract("PID2", output) + "]")); } @Test public void startWhenStopped() throws Exception { String output = doTest("start-when-stopped.sh"); - assertThat(output, containsString("Status: 0")); - assertThat(output, containsColoredString(AnsiColor.GREEN, - "Started [" + extractPid(output) + "]")); + assertThat(output).contains("Status: 0"); + assertThat(output).has( + coloredString(AnsiColor.GREEN, "Started [" + extractPid(output) + "]")); } @Test @@ -199,7 +200,7 @@ public class SysVinitLaunchScriptIT { } private void doLaunch(String script) throws Exception { - assertThat(doTest(script), containsString("Launched")); + assertThat(doTest(script)).contains("Launched"); } private String doTest(String script) throws Exception { @@ -277,8 +278,9 @@ public class SysVinitLaunchScriptIT { "Could not find test application in target directory. Have you built it (mvn package)?"); } - private Matcher<String> containsColoredString(AnsiColor color, String string) { - return containsString(ESC + "[0;" + color + "m" + string + ESC + "[0m"); + private Condition<String> coloredString(AnsiColor color, String string) { + String colorString = ESC + "[0;" + color + "m" + string + ESC + "[0m"; + return Matched.by(containsString(colorString)); } private String extractPid(String output) { diff --git a/spring-boot-integration-tests/spring-boot-security-tests/spring-boot-security-test-web-helloworld/src/test/java/sample/HelloWebSecurityApplicationTests.java b/spring-boot-integration-tests/spring-boot-security-tests/spring-boot-security-test-web-helloworld/src/test/java/sample/HelloWebSecurityApplicationTests.java index 6253effddf..cedf45af16 100644 --- a/spring-boot-integration-tests/spring-boot-security-tests/spring-boot-security-test-web-helloworld/src/test/java/sample/HelloWebSecurityApplicationTests.java +++ b/spring-boot-integration-tests/spring-boot-security-tests/spring-boot-security-test-web-helloworld/src/test/java/sample/HelloWebSecurityApplicationTests.java @@ -32,8 +32,7 @@ import org.springframework.security.crypto.codec.Base64; import org.springframework.security.web.FilterChainProxy; 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; @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(HelloWebSecurityApplication.class) @@ -59,9 +58,8 @@ public class HelloWebSecurityApplicationTests { @Test public void requiresAuthentication() throws Exception { this.springSecurityFilterChain.doFilter(this.request, this.response, this.chain); - - assertThat(this.response.getStatus(), - equalTo(HttpServletResponse.SC_UNAUTHORIZED)); + assertThat(this.response.getStatus()) + .isEqualTo(HttpServletResponse.SC_UNAUTHORIZED); } @Test @@ -71,7 +69,7 @@ public class HelloWebSecurityApplicationTests { this.springSecurityFilterChain.doFilter(this.request, this.response, this.chain); - assertThat(this.response.getStatus(), equalTo(HttpServletResponse.SC_OK)); + assertThat(this.response.getStatus()).isEqualTo(HttpServletResponse.SC_OK); } } From c5add2ef08ac8f7a5b5a51bb478ad8a38b4c0ab3 Mon Sep 17 00:00:00 2001 From: Phillip Webb <pwebb@pivotal.io> Date: Sat, 6 Feb 2016 15:09:47 -0800 Subject: [PATCH 09/10] Use AssertJ in spring-boot-deployment-tests See gh-5083 --- .../java/sample/SampleGlassfishDeployApplicationIT.java | 6 +++--- .../test/java/sample/SampleTomcatDeployApplicationIT.java | 7 +++---- .../test/java/sample/SampleTomEEDeployApplicationIT.java | 7 +++---- .../test/java/sample/SampleWildFlyDeployApplicationIT.java | 7 +++---- 4 files changed, 12 insertions(+), 15 deletions(-) diff --git a/spring-boot-deployment-tests/spring-boot-deployment-test-glassfish/src/test/java/sample/SampleGlassfishDeployApplicationIT.java b/spring-boot-deployment-tests/spring-boot-deployment-test-glassfish/src/test/java/sample/SampleGlassfishDeployApplicationIT.java index ceb681fe08..89e0af9e5d 100644 --- a/spring-boot-deployment-tests/spring-boot-deployment-test-glassfish/src/test/java/sample/SampleGlassfishDeployApplicationIT.java +++ b/spring-boot-deployment-tests/spring-boot-deployment-test-glassfish/src/test/java/sample/SampleGlassfishDeployApplicationIT.java @@ -22,7 +22,7 @@ import org.springframework.boot.test.TestRestTemplate; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * Integration Tests for {@link SampleGlassfishDeployApplication}. @@ -37,8 +37,8 @@ public class SampleGlassfishDeployApplicationIT { System.out.println(url); ResponseEntity<String> entity = new TestRestTemplate().getForEntity(url, String.class); - assertEquals(HttpStatus.OK, entity.getStatusCode()); - assertEquals("Hello World", entity.getBody()); + assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); + assertThat(entity.getBody()).isEqualTo("Hello World"); } } diff --git a/spring-boot-deployment-tests/spring-boot-deployment-test-tomcat/src/test/java/sample/SampleTomcatDeployApplicationIT.java b/spring-boot-deployment-tests/spring-boot-deployment-test-tomcat/src/test/java/sample/SampleTomcatDeployApplicationIT.java index ad68e041df..8bbe329ec6 100644 --- a/spring-boot-deployment-tests/spring-boot-deployment-test-tomcat/src/test/java/sample/SampleTomcatDeployApplicationIT.java +++ b/spring-boot-deployment-tests/spring-boot-deployment-test-tomcat/src/test/java/sample/SampleTomcatDeployApplicationIT.java @@ -22,7 +22,7 @@ import org.springframework.boot.test.TestRestTemplate; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * Integration Tests for {@link SampleTomcatDeployApplication}. @@ -34,11 +34,10 @@ public class SampleTomcatDeployApplicationIT { @Test public void testHome() throws Exception { String url = "http://localhost:" + this.port + "/bootapp/"; - System.out.println(url); ResponseEntity<String> entity = new TestRestTemplate().getForEntity(url, String.class); - assertEquals(HttpStatus.OK, entity.getStatusCode()); - assertEquals("Hello World", entity.getBody()); + assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); + assertThat(entity.getBody()).isEqualTo("Hello World"); } } diff --git a/spring-boot-deployment-tests/spring-boot-deployment-test-tomee/src/test/java/sample/SampleTomEEDeployApplicationIT.java b/spring-boot-deployment-tests/spring-boot-deployment-test-tomee/src/test/java/sample/SampleTomEEDeployApplicationIT.java index 35c467e2c6..3860d3bfa5 100644 --- a/spring-boot-deployment-tests/spring-boot-deployment-test-tomee/src/test/java/sample/SampleTomEEDeployApplicationIT.java +++ b/spring-boot-deployment-tests/spring-boot-deployment-test-tomee/src/test/java/sample/SampleTomEEDeployApplicationIT.java @@ -22,7 +22,7 @@ import org.springframework.boot.test.TestRestTemplate; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * Integration Tests for {@link SampleTomEEDeployApplication}. @@ -34,11 +34,10 @@ public class SampleTomEEDeployApplicationIT { @Test public void testHome() throws Exception { String url = "http://localhost:" + this.port + "/bootapp/"; - System.out.println(url); ResponseEntity<String> entity = new TestRestTemplate().getForEntity(url, String.class); - assertEquals(HttpStatus.OK, entity.getStatusCode()); - assertEquals("Hello World", entity.getBody()); + assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); + assertThat(entity.getBody()).isEqualTo("Hello World"); } } diff --git a/spring-boot-deployment-tests/spring-boot-deployment-test-wildfly/src/test/java/sample/SampleWildFlyDeployApplicationIT.java b/spring-boot-deployment-tests/spring-boot-deployment-test-wildfly/src/test/java/sample/SampleWildFlyDeployApplicationIT.java index 69d6b42757..043274749d 100644 --- a/spring-boot-deployment-tests/spring-boot-deployment-test-wildfly/src/test/java/sample/SampleWildFlyDeployApplicationIT.java +++ b/spring-boot-deployment-tests/spring-boot-deployment-test-wildfly/src/test/java/sample/SampleWildFlyDeployApplicationIT.java @@ -22,7 +22,7 @@ import org.springframework.boot.test.TestRestTemplate; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * Integration Tests for {@link SampleWildFlyDeployApplication}. @@ -34,11 +34,10 @@ public class SampleWildFlyDeployApplicationIT { @Test public void testHome() throws Exception { String url = "http://localhost:" + this.port + "/bootapp/"; - System.out.println(url); ResponseEntity<String> entity = new TestRestTemplate().getForEntity(url, String.class); - assertEquals(HttpStatus.OK, entity.getStatusCode()); - assertEquals("Hello World", entity.getBody()); + assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); + assertThat(entity.getBody()).isEqualTo("Hello World"); } } From cc5d4b8b7fd56f8eb2b6ca920c1547bce3e8f4df Mon Sep 17 00:00:00 2001 From: Phillip Webb <pwebb@pivotal.io> Date: Fri, 5 Feb 2016 21:57:38 -0800 Subject: [PATCH 10/10] Add AssertJ checkstyle rule Closes gh-5083 --- spring-boot-parent/src/checkstyle/checkstyle.xml | 9 ++++++++- .../org/springframework/boot/test/OutputCapture.java | 4 ++-- 2 files changed, 10 insertions(+), 3 deletions(-) diff --git a/spring-boot-parent/src/checkstyle/checkstyle.xml b/spring-boot-parent/src/checkstyle/checkstyle.xml index 7b55179e89..856ee2b40d 100644 --- a/spring-boot-parent/src/checkstyle/checkstyle.xml +++ b/spring-boot-parent/src/checkstyle/checkstyle.xml @@ -71,7 +71,7 @@ <module name="AvoidStarImport" /> <module name="AvoidStaticImport"> <property name="excludes" - value="org.junit.Assert.*, org.junit.Assume.*, org.junit.internal.matchers.ThrowableMessageMatcher.*, org.hamcrest.CoreMatchers.*, org.hamcrest.Matchers.*, org.springframework.boot.configurationprocessor.ConfigurationMetadataMatchers.*, org.springframework.boot.configurationprocessor.TestCompiler.*, org.mockito.Mockito.*, org.mockito.BDDMockito.*, org.mockito.Matchers.*, org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*, org.springframework.test.web.servlet.result.MockMvcResultMatchers.*, org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.*, org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers.*, org.springframework.hateoas.mvc.ControllerLinkBuilder.linkTo" /> + value="org.assertj.core.api.Assertions.*, org.junit.Assert.*, org.junit.Assume.*, org.junit.internal.matchers.ThrowableMessageMatcher.*, org.hamcrest.CoreMatchers.*, org.hamcrest.Matchers.*, org.springframework.boot.configurationprocessor.ConfigurationMetadataMatchers.*, org.springframework.boot.configurationprocessor.TestCompiler.*, org.mockito.Mockito.*, org.mockito.BDDMockito.*, org.mockito.Matchers.*, org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*, org.springframework.test.web.servlet.result.MockMvcResultMatchers.*, org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.*, org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers.*, org.springframework.hateoas.mvc.ControllerLinkBuilder.linkTo" /> </module> <module name="IllegalImport" /> <module name="RedundantImport" /> @@ -136,6 +136,13 @@ value="Please use BDDMockto imports." /> <property name="ignoreComments" value="true" /> </module> + <module name="RegexpSinglelineJava"> + <property name="maximum" value="0"/> + <property name="format" value="org\.junit\.Assert\.assert" /> + <property name="message" + value="Please use AssertJ imports." /> + <property name="ignoreComments" value="true" /> + </module> <module name="Regexp"> <property name="format" value="[ \t]+$" /> <property name="illegalPattern" value="true" /> diff --git a/spring-boot/src/main/java/org/springframework/boot/test/OutputCapture.java b/spring-boot/src/main/java/org/springframework/boot/test/OutputCapture.java index 1bc1e3beab..2dfcadd562 100644 --- a/spring-boot/src/main/java/org/springframework/boot/test/OutputCapture.java +++ b/spring-boot/src/main/java/org/springframework/boot/test/OutputCapture.java @@ -24,6 +24,7 @@ import java.util.ArrayList; import java.util.List; import org.hamcrest.Matcher; +import org.junit.Assert; import org.junit.rules.TestRule; import org.junit.runner.Description; import org.junit.runners.model.Statement; @@ -32,7 +33,6 @@ import org.springframework.boot.ansi.AnsiOutput; import org.springframework.boot.ansi.AnsiOutput.Enabled; import static org.hamcrest.Matchers.allOf; -import static org.junit.Assert.assertThat; /** * JUnit {@code @Rule} to capture output from System.out and System.err. @@ -63,7 +63,7 @@ public class OutputCapture implements TestRule { try { if (!OutputCapture.this.matchers.isEmpty()) { String output = OutputCapture.this.toString(); - assertThat(output, allOf(OutputCapture.this.matchers)); + Assert.assertThat(output, allOf(OutputCapture.this.matchers)); } } finally {