Use AssertJ in spring-boot-autoconfigure

See gh-5083
This commit is contained in:
Phillip Webb
2016-02-06 14:48:43 -08:00
parent e19e3209d9
commit a5ae81c1c1
164 changed files with 2104 additions and 2500 deletions

View File

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

View File

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

View File

@@ -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<String> 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<String> 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<String> 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<String> 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<String> 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<String> 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<String> 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<String> 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<? super List<String>> nameMatcher(String... names) {
final List<String> list = Arrays.asList(names);
return new IsEqual<List<String>>(list) {
@Override
public void describeMismatch(Object item, Description description) {
@SuppressWarnings("unchecked")
List<String> items = (List<String>) item;
description.appendText("was ").appendValue(prettify(items));
}
@Override
public void describeTo(Description description) {
description.appendValue(prettify(list));
}
private String prettify(List<String> items) {
List<String> pretty = new ArrayList<String>();
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 {
}
}

View File

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

View File

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

View File

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

View File

@@ -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();

View File

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

View File

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

View File

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

View File

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

View File

@@ -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");
}
}

View File

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

View File

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

View File

@@ -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);
}
}

View File

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

View File

@@ -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 extends CacheManager> T validateCacheManager(Class<T> 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);
}

View File

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

View File

@@ -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<String> ordered = sorter.getInPriorityOrder(classNames);
assertThat(ordered.get(0), equalTo(CloudAutoConfiguration.class.getName()));
assertThat(ordered.get(0)).isEqualTo(CloudAutoConfiguration.class.getName());
}
}

View File

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

View File

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

View File

@@ -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<String, ConditionAndOutcomes> map = this.report
.getConditionAndOutcomesBySource();
assertThat(map.size(), equalTo(2));
assertThat(map.size()).isEqualTo(2);
Iterator<ConditionAndOutcome> 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<String> messages = new ArrayList<String>();
for (ConditionAndOutcome outcome : outcomes) {
messages.add(outcome.getOutcome().getMessage());
}
Matcher<String> 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<String, ConditionAndOutcomes> 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) {

View File

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

View File

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

View File

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

View File

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

View File

@@ -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<Iterable<String>> 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) {

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -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<String, PersistenceExceptionTranslationPostProcessor> 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<String, PersistenceExceptionTranslationPostProcessor> beans = this.context
.getBeansOfType(PersistenceExceptionTranslationPostProcessor.class);
assertThat(beans.entrySet(), empty());
assertThat(beans.entrySet()).isEmpty();
}
@Test(expected = IllegalArgumentException.class)

View File

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

View File

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

View File

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

View File

@@ -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);
}
}

View File

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

View File

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

View File

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

View File

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

View File

@@ -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<Class> initialEntitySet = (Set<Class>) ReflectionTestUtils
.getField(mappingContext, "initialEntitySet");
assertThat(initialEntitySet, hasSize(types.length));
assertThat(initialEntitySet, Matchers.<Class>hasItems(types));
assertThat(initialEntitySet).containsOnly(types);
}
@Configuration

View File

@@ -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<? extends Class<?>> entities = (Set<? extends Class<?>>) 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)

View File

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

View File

@@ -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<String, ObjectMapper> 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) {

View File

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

View File

@@ -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<String, PageableHandlerMethodArgumentResolver> 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<String, PageableHandlerMethodArgumentResolver> beans = this.context
.getBeansOfType(PageableHandlerMethodArgumentResolver.class);
assertThat(beans.size(), is(equalTo(0)));
assertThat(beans).isEmpty();
}
}

View File

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

View File

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

View File

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

View File

@@ -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<String, Object>(
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;
}
}

View File

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

View File

@@ -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/*");
}
}

View File

@@ -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);
}
}
}

View File

@@ -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<String, QueueConfig> 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<String, QueueConfig> 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) {

View File

@@ -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<String, EntityManagerFactoryDependsOnPostProcessor> getPostProcessor() {

View File

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

View File

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

View File

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

View File

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

View File

@@ -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);
}
}

View File

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

View File

@@ -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");
}
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -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<String> excludedBeans = (Set<String>) 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<String> excludedBeans = (Set<String>) new DirectFieldAccessor(exporter)
.getPropertyValue("excludedBeans");
assertThat(excludedBeans, hasSize(0));
assertThat(excludedBeans).isEmpty();
}
private void configureJndi(String name, DataSource dataSource)

View File

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

View File

@@ -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");
}

View File

@@ -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<D extends AbstractData
@Test
public void getMaxPoolSize() {
assertEquals(Integer.valueOf(2), getDataSourceMetadata().getMax());
assertThat(getDataSourceMetadata().getMax()).isEqualTo(Integer.valueOf(2));
}
@Test
public void getMinPoolSize() {
assertEquals(Integer.valueOf(0), getDataSourceMetadata().getMin());
assertThat(getDataSourceMetadata().getMin()).isEqualTo(Integer.valueOf(0));
}
@Test
@@ -64,8 +64,8 @@ public abstract class AbstractDataSourcePoolMetadataTests<D extends AbstractData
return null;
}
});
assertEquals(Integer.valueOf(0), getDataSourceMetadata().getActive());
assertEquals(Float.valueOf(0), getDataSourceMetadata().getUsage());
assertThat(getDataSourceMetadata().getActive()).isEqualTo(Integer.valueOf(0));
assertThat(getDataSourceMetadata().getUsage()).isEqualTo(Float.valueOf(0));
}
@Test
@@ -76,8 +76,10 @@ public abstract class AbstractDataSourcePoolMetadataTests<D extends AbstractData
@Override
public Void doInConnection(Connection connection)
throws SQLException, DataAccessException {
assertEquals(Integer.valueOf(1), getDataSourceMetadata().getActive());
assertEquals(Float.valueOf(0.5F), getDataSourceMetadata().getUsage());
assertThat(getDataSourceMetadata().getActive())
.isEqualTo(Integer.valueOf(1));
assertThat(getDataSourceMetadata().getUsage())
.isEqualTo(Float.valueOf(0.5F));
return null;
}
});
@@ -88,22 +90,24 @@ public abstract class AbstractDataSourcePoolMetadataTests<D extends AbstractData
final JdbcTemplate jdbcTemplate = new JdbcTemplate(
getDataSourceMetadata().getDataSource());
jdbcTemplate.execute(new ConnectionCallback<Void>() {
@Override
public Void doInConnection(Connection connection)
throws SQLException, DataAccessException {
jdbcTemplate.execute(new ConnectionCallback<Void>() {
@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;
}
});
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -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<String> entity = this.restTemplate.getForEntity(
"http://localhost:" + this.port + "/rest/hello", String.class);
assertEquals(HttpStatus.OK, entity.getStatusCode());
assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK);
}
@MinimalWebConfiguration

View File

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

View File

@@ -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<String> entity = this.restTemplate.getForEntity(
"http://localhost:" + this.port + "/rest/hello", String.class);
assertEquals(HttpStatus.OK, entity.getStatusCode());
assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK);
}
@MinimalWebConfiguration

View File

@@ -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<String> entity = this.restTemplate
.getForEntity("http://localhost:" + this.port + "/hello", String.class);
assertEquals(HttpStatus.OK, entity.getStatusCode());
assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK);
}
@MinimalWebConfiguration

View File

@@ -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<String> entity = this.restTemplate
.getForEntity("http://localhost:" + this.port + "/hello", String.class);
assertEquals(HttpStatus.OK, entity.getStatusCode());
assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK);
}
@MinimalWebConfiguration

View File

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

View File

@@ -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<String> entity = this.restTemplate.getForEntity(
"http://localhost:" + this.port + "/api/hello", String.class);
assertEquals(HttpStatus.OK, entity.getStatusCode());
assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK);
}
@MinimalWebConfiguration

View File

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

View File

@@ -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");
}
}

View File

@@ -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);
}
}
}

View File

@@ -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");
}
}

View File

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

View File

@@ -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");
}
}

View File

@@ -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];
}

View File

@@ -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");
}
}

View File

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

View File

@@ -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<? super String> matcher;
private final String expected;
AssertFetch(DSLContext dsl, String sql, Matcher<? super String> 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);
}
}

Some files were not shown because too many files have changed in this diff Show More