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