Migrate Hamcrest assertions to AssertJ

Migrate all existing `assertThat(..., Matcher)` assertions to AssertJ
and add checkstyle rules to ensure they don't return.

See gh-23022
This commit is contained in:
Phillip Webb 2019-05-23 15:48:03 -07:00
parent 2294625cf0
commit 95a9d46a87
322 changed files with 4358 additions and 4814 deletions

View File

@ -58,11 +58,10 @@ import org.springframework.tests.sample.beans.ITestBean;
import org.springframework.tests.sample.beans.TestBean; import org.springframework.tests.sample.beans.TestBean;
import org.springframework.util.ObjectUtils; import org.springframework.util.ObjectUtils;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.assertj.core.api.Assertions.assertThatIllegalStateException; import static org.assertj.core.api.Assertions.assertThatIllegalStateException;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.instanceOf;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotSame; import static org.junit.Assert.assertNotSame;
@ -384,7 +383,7 @@ public abstract class AbstractAspectJAdvisorFactoryTests {
CannotBeUnlocked.class CannotBeUnlocked.class
), ),
CannotBeUnlocked.class); CannotBeUnlocked.class);
assertThat(proxy, instanceOf(Lockable.class)); assertThat(proxy).isInstanceOf(Lockable.class);
Lockable lockable = proxy; Lockable lockable = proxy;
assertTrue("Already locked", lockable.locked()); assertTrue("Already locked", lockable.locked());
lockable.lock(); lockable.lock();
@ -429,7 +428,7 @@ public abstract class AbstractAspectJAdvisorFactoryTests {
new SingletonMetadataAwareAspectInstanceFactory(new MakeLockable(), "someBean"))); new SingletonMetadataAwareAspectInstanceFactory(new MakeLockable(), "someBean")));
Modifiable modifiable = (Modifiable) createProxy(target, advisors, ITestBean.class); Modifiable modifiable = (Modifiable) createProxy(target, advisors, ITestBean.class);
assertThat(modifiable, instanceOf(Modifiable.class)); assertThat(modifiable).isInstanceOf(Modifiable.class);
Lockable lockable = (Lockable) modifiable; Lockable lockable = (Lockable) modifiable;
assertFalse(lockable.locked()); assertFalse(lockable.locked());

View File

@ -42,9 +42,8 @@ import org.springframework.tests.sample.beans.IOther;
import org.springframework.tests.sample.beans.ITestBean; import org.springframework.tests.sample.beans.ITestBean;
import org.springframework.tests.sample.beans.TestBean; import org.springframework.tests.sample.beans.TestBean;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.hamcrest.CoreMatchers.instanceOf;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull; import static org.junit.Assert.assertNull;
@ -187,7 +186,7 @@ public class ProxyFactoryTests {
// This call should be ignored without error // This call should be ignored without error
pf.addInterface(TimeStamped.class); pf.addInterface(TimeStamped.class);
// All cool // All cool
assertThat(pf.getProxy(), instanceOf(TimeStamped.class)); assertThat(pf.getProxy()).isInstanceOf(TimeStamped.class);
} }
@Test @Test
@ -204,8 +203,7 @@ public class ProxyFactoryTests {
//System.out.println("Proxied interfaces are " + StringUtils.arrayToDelimitedString(factory.getProxiedInterfaces(), ",")); //System.out.println("Proxied interfaces are " + StringUtils.arrayToDelimitedString(factory.getProxiedInterfaces(), ","));
assertEquals("Found correct number of interfaces", 5, factory.getProxiedInterfaces().length); assertEquals("Found correct number of interfaces", 5, factory.getProxiedInterfaces().length);
ITestBean tb = (ITestBean) factory.getProxy(); ITestBean tb = (ITestBean) factory.getProxy();
assertThat("Picked up secondary interface", tb, instanceOf(IOther.class)); assertThat(tb).as("Picked up secondary interface").isInstanceOf(IOther.class);
raw.setAge(25); raw.setAge(25);
assertTrue(tb.getAge() == raw.getAge()); assertTrue(tb.getAge() == raw.getAge());
@ -238,7 +236,7 @@ public class ProxyFactoryTests {
NopInterceptor diUnused = new NopInterceptor(); NopInterceptor diUnused = new NopInterceptor();
ProxyFactory factory = new ProxyFactory(new TestBean()); ProxyFactory factory = new ProxyFactory(new TestBean());
factory.addAdvice(0, di); factory.addAdvice(0, di);
assertThat(factory.getProxy(), instanceOf(ITestBean.class)); assertThat(factory.getProxy()).isInstanceOf(ITestBean.class);
assertTrue(factory.adviceIncluded(di)); assertTrue(factory.adviceIncluded(di));
assertTrue(!factory.adviceIncluded(diUnused)); assertTrue(!factory.adviceIncluded(diUnused));
assertTrue(factory.countAdvicesOfType(NopInterceptor.class) == 1); assertTrue(factory.countAdvicesOfType(NopInterceptor.class) == 1);

View File

@ -34,9 +34,8 @@ import org.springframework.tests.sample.beans.SerializablePerson;
import org.springframework.tests.sample.beans.TestBean; import org.springframework.tests.sample.beans.TestBean;
import org.springframework.util.SerializationTestUtils; import org.springframework.util.SerializationTestUtils;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.instanceOf;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertSame; import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertTrue;
@ -162,7 +161,7 @@ public class DelegatingIntroductionInterceptorTests {
//assertTrue(Arrays.binarySearch(pf.getProxiedInterfaces(), TimeStamped.class) != -1); //assertTrue(Arrays.binarySearch(pf.getProxiedInterfaces(), TimeStamped.class) != -1);
TimeStamped ts = (TimeStamped) pf.getProxy(); TimeStamped ts = (TimeStamped) pf.getProxy();
assertThat(ts, instanceOf(TimeStamped.class)); assertThat(ts).isInstanceOf(TimeStamped.class);
// Shouldn't proxy framework interfaces // Shouldn't proxy framework interfaces
assertTrue(!(ts instanceof MethodInterceptor)); assertTrue(!(ts instanceof MethodInterceptor));
assertTrue(!(ts instanceof IntroductionInterceptor)); assertTrue(!(ts instanceof IntroductionInterceptor));

View File

@ -38,9 +38,7 @@ import org.springframework.tests.TestGroup;
import org.springframework.util.ReflectionUtils; import org.springframework.util.ReflectionUtils;
import org.springframework.util.concurrent.ListenableFuture; import org.springframework.util.concurrent.ListenableFuture;
import static org.hamcrest.CoreMatchers.startsWith; import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.not;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertFalse;
@ -140,14 +138,14 @@ public class AnnotationAsyncExecutionAspectTests {
ClassWithQualifiedAsyncMethods obj = new ClassWithQualifiedAsyncMethods(); ClassWithQualifiedAsyncMethods obj = new ClassWithQualifiedAsyncMethods();
Future<Thread> defaultThread = obj.defaultWork(); Future<Thread> defaultThread = obj.defaultWork();
assertThat(defaultThread.get(), not(Thread.currentThread())); assertThat(defaultThread.get()).isNotEqualTo(Thread.currentThread());
assertThat(defaultThread.get().getName(), not(startsWith("e1-"))); assertThat(defaultThread.get().getName()).doesNotStartWith("e1-");
ListenableFuture<Thread> e1Thread = obj.e1Work(); ListenableFuture<Thread> e1Thread = obj.e1Work();
assertThat(e1Thread.get().getName(), startsWith("e1-")); assertThat(e1Thread.get().getName()).startsWith("e1-");
CompletableFuture<Thread> e1OtherThread = obj.e1OtherWork(); CompletableFuture<Thread> e1OtherThread = obj.e1OtherWork();
assertThat(e1OtherThread.get().getName(), startsWith("e1-")); assertThat(e1OtherThread.get().getName()).startsWith("e1-");
} }
@Test @Test

View File

@ -61,11 +61,6 @@ import org.springframework.util.StringUtils;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.notNullValue;
import static org.hamcrest.CoreMatchers.nullValue;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertSame; import static org.junit.Assert.assertSame;
@ -98,7 +93,7 @@ public abstract class AbstractPropertyAccessorTests {
public void isReadableProperty() { public void isReadableProperty() {
AbstractPropertyAccessor accessor = createAccessor(new Simple("John", 2)); AbstractPropertyAccessor accessor = createAccessor(new Simple("John", 2));
assertThat(accessor.isReadableProperty("name"), is(true)); assertThat(accessor.isReadableProperty("name")).isTrue();
} }
@Test @Test
@ -130,7 +125,7 @@ public abstract class AbstractPropertyAccessorTests {
public void isWritableProperty() { public void isWritableProperty() {
AbstractPropertyAccessor accessor = createAccessor(new Simple("John", 2)); AbstractPropertyAccessor accessor = createAccessor(new Simple("John", 2));
assertThat(accessor.isWritableProperty("name"), is(true)); assertThat(accessor.isWritableProperty("name")).isTrue();
} }
@Test @Test
@ -198,21 +193,21 @@ public abstract class AbstractPropertyAccessorTests {
public void getSimpleProperty() { public void getSimpleProperty() {
Simple target = new Simple("John", 2); Simple target = new Simple("John", 2);
AbstractPropertyAccessor accessor = createAccessor(target); AbstractPropertyAccessor accessor = createAccessor(target);
assertThat(accessor.getPropertyValue("name"), is("John")); assertThat(accessor.getPropertyValue("name")).isEqualTo("John");
} }
@Test @Test
public void getNestedProperty() { public void getNestedProperty() {
Person target = createPerson("John", "London", "UK"); Person target = createPerson("John", "London", "UK");
AbstractPropertyAccessor accessor = createAccessor(target); AbstractPropertyAccessor accessor = createAccessor(target);
assertThat(accessor.getPropertyValue("address.city"), is("London")); assertThat(accessor.getPropertyValue("address.city")).isEqualTo("London");
} }
@Test @Test
public void getNestedDeepProperty() { public void getNestedDeepProperty() {
Person target = createPerson("John", "London", "UK"); Person target = createPerson("John", "London", "UK");
AbstractPropertyAccessor accessor = createAccessor(target); AbstractPropertyAccessor accessor = createAccessor(target);
assertThat(accessor.getPropertyValue("address.country.name"), is("UK")); assertThat(accessor.getPropertyValue("address.country.name")).isEqualTo("UK");
} }
@Test @Test
@ -291,8 +286,8 @@ public abstract class AbstractPropertyAccessorTests {
accessor.setPropertyValue("name", "SomeValue"); accessor.setPropertyValue("name", "SomeValue");
assertThat(target.name, is("SomeValue")); assertThat(target.name).isEqualTo("SomeValue");
assertThat(target.getName(), is("SomeValue")); assertThat(target.getName()).isEqualTo("SomeValue");
} }
@Test @Test
@ -301,7 +296,7 @@ public abstract class AbstractPropertyAccessorTests {
AbstractPropertyAccessor accessor = createAccessor(target); AbstractPropertyAccessor accessor = createAccessor(target);
accessor.setPropertyValue("address.city", "London"); accessor.setPropertyValue("address.city", "London");
assertThat(target.address.city, is("London")); assertThat(target.address.city).isEqualTo("London");
} }
@Test @Test
@ -364,7 +359,7 @@ public abstract class AbstractPropertyAccessorTests {
AbstractPropertyAccessor accessor = createAccessor(target); AbstractPropertyAccessor accessor = createAccessor(target);
accessor.setPropertyValue("address.country.name", "UK"); accessor.setPropertyValue("address.country.name", "UK");
assertThat(target.address.country.name, is("UK")); assertThat(target.address.country.name).isEqualTo("UK");
} }
@Test @Test
@ -413,7 +408,7 @@ public abstract class AbstractPropertyAccessorTests {
accessor.setAutoGrowNestedPaths(true); accessor.setAutoGrowNestedPaths(true);
accessor.setPropertyValue("address.country.name", "UK"); accessor.setPropertyValue("address.country.name", "UK");
assertThat(target.address.country.name, is("UK")); assertThat(target.address.country.name).isEqualTo("UK");
} }
@SuppressWarnings("AssertEqualsBetweenInconvertibleTypes") @SuppressWarnings("AssertEqualsBetweenInconvertibleTypes")
@ -1108,11 +1103,11 @@ public abstract class AbstractPropertyAccessorTests {
Object[] array = new Object[] {"1", "2"}; Object[] array = new Object[] {"1", "2"};
accessor.setPropertyValue("object", array); accessor.setPropertyValue("object", array);
assertThat(target.getObject(), equalTo((Object) array)); assertThat(target.getObject()).isEqualTo(array);
array = new Object[] {"1"}; array = new Object[] {"1"};
accessor.setPropertyValue("object", array); accessor.setPropertyValue("object", array);
assertThat(target.getObject(), equalTo((Object) array)); assertThat(target.getObject()).isEqualTo(array);
} }
@ -1636,7 +1631,7 @@ public abstract class AbstractPropertyAccessorTests {
Simple target = new Simple("John", 2); Simple target = new Simple("John", 2);
AbstractPropertyAccessor accessor = createAccessor(target); AbstractPropertyAccessor accessor = createAccessor(target);
assertThat(accessor.getPropertyType("foo"), is(nullValue())); assertThat(accessor.getPropertyType("foo")).isNull();
} }
@Test @Test
@ -1644,7 +1639,7 @@ public abstract class AbstractPropertyAccessorTests {
Person target = createPerson("John", "Paris", "FR"); Person target = createPerson("John", "Paris", "FR");
AbstractPropertyAccessor accessor = createAccessor(target); AbstractPropertyAccessor accessor = createAccessor(target);
assertThat(accessor.getPropertyTypeDescriptor("address.city"), is(notNullValue())); assertThat(accessor.getPropertyTypeDescriptor("address.city")).isNotNull();
} }
@Test @Test
@ -1652,7 +1647,7 @@ public abstract class AbstractPropertyAccessorTests {
Simple target = new Simple("John", 2); Simple target = new Simple("John", 2);
AbstractPropertyAccessor accessor = createAccessor(target); AbstractPropertyAccessor accessor = createAccessor(target);
assertThat(accessor.getPropertyTypeDescriptor("foo"), is(nullValue())); assertThat(accessor.getPropertyTypeDescriptor("foo")).isNull();
} }
@Test @Test

View File

@ -22,9 +22,8 @@ import java.util.Map;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.instanceOf;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull; import static org.junit.Assert.assertNull;
@ -67,7 +66,7 @@ public class BeanWrapperAutoGrowingTests {
public void getPropertyValueAutoGrowArray() { public void getPropertyValueAutoGrowArray() {
assertNotNull(wrapper.getPropertyValue("array[0]")); assertNotNull(wrapper.getPropertyValue("array[0]"));
assertEquals(1, bean.getArray().length); assertEquals(1, bean.getArray().length);
assertThat(bean.getArray()[0], instanceOf(Bean.class)); assertThat(bean.getArray()[0]).isInstanceOf(Bean.class);
} }
@Test @Test
@ -80,11 +79,11 @@ public class BeanWrapperAutoGrowingTests {
public void getPropertyValueAutoGrowArrayBySeveralElements() { public void getPropertyValueAutoGrowArrayBySeveralElements() {
assertNotNull(wrapper.getPropertyValue("array[4]")); assertNotNull(wrapper.getPropertyValue("array[4]"));
assertEquals(5, bean.getArray().length); assertEquals(5, bean.getArray().length);
assertThat(bean.getArray()[0], instanceOf(Bean.class)); assertThat(bean.getArray()[0]).isInstanceOf(Bean.class);
assertThat(bean.getArray()[1], instanceOf(Bean.class)); assertThat(bean.getArray()[1]).isInstanceOf(Bean.class);
assertThat(bean.getArray()[2], instanceOf(Bean.class)); assertThat(bean.getArray()[2]).isInstanceOf(Bean.class);
assertThat(bean.getArray()[3], instanceOf(Bean.class)); assertThat(bean.getArray()[3]).isInstanceOf(Bean.class);
assertThat(bean.getArray()[4], instanceOf(Bean.class)); assertThat(bean.getArray()[4]).isInstanceOf(Bean.class);
assertNotNull(wrapper.getPropertyValue("array[0]")); assertNotNull(wrapper.getPropertyValue("array[0]"));
assertNotNull(wrapper.getPropertyValue("array[1]")); assertNotNull(wrapper.getPropertyValue("array[1]"));
assertNotNull(wrapper.getPropertyValue("array[2]")); assertNotNull(wrapper.getPropertyValue("array[2]"));
@ -95,14 +94,14 @@ public class BeanWrapperAutoGrowingTests {
public void getPropertyValueAutoGrowMultiDimensionalArray() { public void getPropertyValueAutoGrowMultiDimensionalArray() {
assertNotNull(wrapper.getPropertyValue("multiArray[0][0]")); assertNotNull(wrapper.getPropertyValue("multiArray[0][0]"));
assertEquals(1, bean.getMultiArray()[0].length); assertEquals(1, bean.getMultiArray()[0].length);
assertThat(bean.getMultiArray()[0][0], instanceOf(Bean.class)); assertThat(bean.getMultiArray()[0][0]).isInstanceOf(Bean.class);
} }
@Test @Test
public void getPropertyValueAutoGrowList() { public void getPropertyValueAutoGrowList() {
assertNotNull(wrapper.getPropertyValue("list[0]")); assertNotNull(wrapper.getPropertyValue("list[0]"));
assertEquals(1, bean.getList().size()); assertEquals(1, bean.getList().size());
assertThat(bean.getList().get(0), instanceOf(Bean.class)); assertThat(bean.getList().get(0)).isInstanceOf(Bean.class);
} }
@Test @Test
@ -115,11 +114,11 @@ public class BeanWrapperAutoGrowingTests {
public void getPropertyValueAutoGrowListBySeveralElements() { public void getPropertyValueAutoGrowListBySeveralElements() {
assertNotNull(wrapper.getPropertyValue("list[4]")); assertNotNull(wrapper.getPropertyValue("list[4]"));
assertEquals(5, bean.getList().size()); assertEquals(5, bean.getList().size());
assertThat(bean.getList().get(0), instanceOf(Bean.class)); assertThat(bean.getList().get(0)).isInstanceOf(Bean.class);
assertThat(bean.getList().get(1), instanceOf(Bean.class)); assertThat(bean.getList().get(1)).isInstanceOf(Bean.class);
assertThat(bean.getList().get(2), instanceOf(Bean.class)); assertThat(bean.getList().get(2)).isInstanceOf(Bean.class);
assertThat(bean.getList().get(3), instanceOf(Bean.class)); assertThat(bean.getList().get(3)).isInstanceOf(Bean.class);
assertThat(bean.getList().get(4), instanceOf(Bean.class)); assertThat(bean.getList().get(4)).isInstanceOf(Bean.class);
assertNotNull(wrapper.getPropertyValue("list[0]")); assertNotNull(wrapper.getPropertyValue("list[0]"));
assertNotNull(wrapper.getPropertyValue("list[1]")); assertNotNull(wrapper.getPropertyValue("list[1]"));
assertNotNull(wrapper.getPropertyValue("list[2]")); assertNotNull(wrapper.getPropertyValue("list[2]"));
@ -138,7 +137,7 @@ public class BeanWrapperAutoGrowingTests {
public void getPropertyValueAutoGrowMultiDimensionalList() { public void getPropertyValueAutoGrowMultiDimensionalList() {
assertNotNull(wrapper.getPropertyValue("multiList[0][0]")); assertNotNull(wrapper.getPropertyValue("multiList[0][0]"));
assertEquals(1, bean.getMultiList().get(0).size()); assertEquals(1, bean.getMultiList().get(0).size());
assertThat(bean.getMultiList().get(0).get(0), instanceOf(Bean.class)); assertThat(bean.getMultiList().get(0).get(0)).isInstanceOf(Bean.class);
} }
@Test @Test
@ -150,13 +149,13 @@ public class BeanWrapperAutoGrowingTests {
@Test @Test
public void setPropertyValueAutoGrowMap() { public void setPropertyValueAutoGrowMap() {
wrapper.setPropertyValue("map[A]", new Bean()); wrapper.setPropertyValue("map[A]", new Bean());
assertThat(bean.getMap().get("A"), instanceOf(Bean.class)); assertThat(bean.getMap().get("A")).isInstanceOf(Bean.class);
} }
@Test @Test
public void setNestedPropertyValueAutoGrowMap() { public void setNestedPropertyValueAutoGrowMap() {
wrapper.setPropertyValue("map[A].nested", new Bean()); wrapper.setPropertyValue("map[A].nested", new Bean());
assertThat(bean.getMap().get("A").getNested(), instanceOf(Bean.class)); assertThat(bean.getMap().get("A").getNested()).isInstanceOf(Bean.class);
} }

View File

@ -25,9 +25,7 @@ import org.junit.Test;
import org.springframework.core.OverridingClassLoader; import org.springframework.core.OverridingClassLoader;
import org.springframework.tests.sample.beans.TestBean; import org.springframework.tests.sample.beans.TestBean;
import static org.hamcrest.CoreMatchers.equalTo; import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.CoreMatchers.notNullValue;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertTrue;
@ -87,13 +85,11 @@ public class CachedIntrospectionResultsTests {
} }
// resulting in a property descriptor including the non-standard setFoo method // resulting in a property descriptor including the non-standard setFoo method
assertThat(pd, notNullValue()); assertThat(pd).isNotNull();
assertThat(pd.getReadMethod(), equalTo(C.class.getMethod("getFoo"))); assertThat(pd.getReadMethod()).isEqualTo(C.class.getMethod("getFoo"));
assertThat( // No write method found for non-void returning 'setFoo' method.
"No write method found for non-void returning 'setFoo' method. " + // Check to see if CachedIntrospectionResults is delegating to ExtendedBeanInfo as expected
"Check to see if CachedIntrospectionResults is delegating to " + assertThat(pd.getWriteMethod()).isEqualTo(C.class.getMethod("setFoo", String.class));
"ExtendedBeanInfo as expected",
pd.getWriteMethod(), equalTo(C.class.getMethod("setFoo", String.class)));
} }
} }

View File

@ -20,9 +20,8 @@ import java.beans.IntrospectionException;
import org.junit.Test; import org.junit.Test;
import static org.hamcrest.CoreMatchers.notNullValue; import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.CoreMatchers.nullValue;
import static org.hamcrest.MatcherAssert.assertThat;
/** /**
* Unit tests for {@link ExtendedBeanInfoTests}. * Unit tests for {@link ExtendedBeanInfoTests}.
@ -39,7 +38,7 @@ public class ExtendedBeanInfoFactoryTests {
class C { class C {
public void setFoo(String s) { } public void setFoo(String s) { }
} }
assertThat(factory.getBeanInfo(C.class), nullValue()); assertThat(factory.getBeanInfo(C.class)).isNull();
} }
@Test @Test
@ -48,7 +47,7 @@ public class ExtendedBeanInfoFactoryTests {
class C { class C {
public C setFoo(String s) { return this; } public C setFoo(String s) { return this; }
} }
assertThat(factory.getBeanInfo(C.class), notNullValue()); assertThat(factory.getBeanInfo(C.class)).isNotNull();
} }
@Test @Test
@ -57,7 +56,7 @@ public class ExtendedBeanInfoFactoryTests {
class C { class C {
public C setFoo(int i, String s) { return this; } public C setFoo(int i, String s) { return this; }
} }
assertThat(factory.getBeanInfo(C.class), notNullValue()); assertThat(factory.getBeanInfo(C.class)).isNotNull();
} }
@Test @Test
@ -66,7 +65,7 @@ public class ExtendedBeanInfoFactoryTests {
class C { class C {
void setBar(String s) { } void setBar(String s) { }
} }
assertThat(factory.getBeanInfo(C.class), nullValue()); assertThat(factory.getBeanInfo(C.class)).isNull();
} }
@Test @Test
@ -75,7 +74,7 @@ public class ExtendedBeanInfoFactoryTests {
class C { class C {
C setBar() { return this; } C setBar() { return this; }
} }
assertThat(factory.getBeanInfo(C.class), nullValue()); assertThat(factory.getBeanInfo(C.class)).isNull();
} }
@Test @Test
@ -84,7 +83,7 @@ public class ExtendedBeanInfoFactoryTests {
class C { class C {
C set(String s) { return this; } C set(String s) { return this; }
} }
assertThat(factory.getBeanInfo(C.class), nullValue()); assertThat(factory.getBeanInfo(C.class)).isNull();
} }
} }

View File

@ -27,11 +27,7 @@ import org.junit.Test;
import org.springframework.tests.sample.beans.TestBean; import org.springframework.tests.sample.beans.TestBean;
import static org.hamcrest.CoreMatchers.equalTo; import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.greaterThan;
import static org.hamcrest.Matchers.lessThan;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
/** /**
@ -51,11 +47,11 @@ public class ExtendedBeanInfoTests {
BeanInfo bi = Introspector.getBeanInfo(C.class); BeanInfo bi = Introspector.getBeanInfo(C.class);
ExtendedBeanInfo ebi = new ExtendedBeanInfo(bi); ExtendedBeanInfo ebi = new ExtendedBeanInfo(bi);
assertThat(hasReadMethodForProperty(bi, "foo"), is(true)); assertThat(hasReadMethodForProperty(bi, "foo")).isTrue();
assertThat(hasWriteMethodForProperty(bi, "foo"), is(false)); assertThat(hasWriteMethodForProperty(bi, "foo")).isFalse();
assertThat(hasReadMethodForProperty(ebi, "foo"), is(true)); assertThat(hasReadMethodForProperty(ebi, "foo")).isTrue();
assertThat(hasWriteMethodForProperty(ebi, "foo"), is(false)); assertThat(hasWriteMethodForProperty(ebi, "foo")).isFalse();
} }
@Test @Test
@ -67,11 +63,11 @@ public class ExtendedBeanInfoTests {
BeanInfo bi = Introspector.getBeanInfo(C.class); BeanInfo bi = Introspector.getBeanInfo(C.class);
ExtendedBeanInfo ebi = new ExtendedBeanInfo(bi); ExtendedBeanInfo ebi = new ExtendedBeanInfo(bi);
assertThat(hasReadMethodForProperty(bi, "foo"), is(false)); assertThat(hasReadMethodForProperty(bi, "foo")).isFalse();
assertThat(hasWriteMethodForProperty(bi, "foo"), is(true)); assertThat(hasWriteMethodForProperty(bi, "foo")).isTrue();
assertThat(hasReadMethodForProperty(ebi, "foo"), is(false)); assertThat(hasReadMethodForProperty(ebi, "foo")).isFalse();
assertThat(hasWriteMethodForProperty(ebi, "foo"), is(true)); assertThat(hasWriteMethodForProperty(ebi, "foo")).isTrue();
} }
@Test @Test
@ -84,11 +80,11 @@ public class ExtendedBeanInfoTests {
BeanInfo bi = Introspector.getBeanInfo(C.class); BeanInfo bi = Introspector.getBeanInfo(C.class);
ExtendedBeanInfo ebi = new ExtendedBeanInfo(bi); ExtendedBeanInfo ebi = new ExtendedBeanInfo(bi);
assertThat(hasReadMethodForProperty(bi, "foo"), is(true)); assertThat(hasReadMethodForProperty(bi, "foo")).isTrue();
assertThat(hasWriteMethodForProperty(bi, "foo"), is(true)); assertThat(hasWriteMethodForProperty(bi, "foo")).isTrue();
assertThat(hasReadMethodForProperty(ebi, "foo"), is(true)); assertThat(hasReadMethodForProperty(ebi, "foo")).isTrue();
assertThat(hasWriteMethodForProperty(ebi, "foo"), is(true)); assertThat(hasWriteMethodForProperty(ebi, "foo")).isTrue();
} }
@Test @Test
@ -100,11 +96,11 @@ public class ExtendedBeanInfoTests {
BeanInfo bi = Introspector.getBeanInfo(C.class); BeanInfo bi = Introspector.getBeanInfo(C.class);
ExtendedBeanInfo ebi = new ExtendedBeanInfo(bi); ExtendedBeanInfo ebi = new ExtendedBeanInfo(bi);
assertThat(hasReadMethodForProperty(bi, "foo"), is(false)); assertThat(hasReadMethodForProperty(bi, "foo")).isFalse();
assertThat(hasWriteMethodForProperty(bi, "foo"), is(false)); assertThat(hasWriteMethodForProperty(bi, "foo")).isFalse();
assertThat(hasReadMethodForProperty(ebi, "foo"), is(false)); assertThat(hasReadMethodForProperty(ebi, "foo")).isFalse();
assertThat(hasWriteMethodForProperty(ebi, "foo"), is(true)); assertThat(hasWriteMethodForProperty(ebi, "foo")).isTrue();
} }
@Test @Test
@ -116,16 +112,16 @@ public class ExtendedBeanInfoTests {
BeanInfo bi = Introspector.getBeanInfo(C.class); BeanInfo bi = Introspector.getBeanInfo(C.class);
assertThat(hasReadMethodForProperty(bi, "foo"), is(true)); assertThat(hasReadMethodForProperty(bi, "foo")).isTrue();
assertThat(hasWriteMethodForProperty(bi, "foo"), is(false)); assertThat(hasWriteMethodForProperty(bi, "foo")).isFalse();
ExtendedBeanInfo ebi = new ExtendedBeanInfo(bi); ExtendedBeanInfo ebi = new ExtendedBeanInfo(bi);
assertThat(hasReadMethodForProperty(bi, "foo"), is(true)); assertThat(hasReadMethodForProperty(bi, "foo")).isTrue();
assertThat(hasWriteMethodForProperty(bi, "foo"), is(false)); assertThat(hasWriteMethodForProperty(bi, "foo")).isFalse();
assertThat(hasReadMethodForProperty(ebi, "foo"), is(true)); assertThat(hasReadMethodForProperty(ebi, "foo")).isTrue();
assertThat(hasWriteMethodForProperty(ebi, "foo"), is(true)); assertThat(hasWriteMethodForProperty(ebi, "foo")).isTrue();
} }
@Test @Test
@ -137,15 +133,15 @@ public class ExtendedBeanInfoTests {
BeanInfo bi = Introspector.getBeanInfo(C.class); BeanInfo bi = Introspector.getBeanInfo(C.class);
assertThat(hasReadMethodForProperty(bi, "foo"), is(true)); assertThat(hasReadMethodForProperty(bi, "foo")).isTrue();
assertThat(hasWriteMethodForProperty(bi, "foo"), is(false)); assertThat(hasWriteMethodForProperty(bi, "foo")).isFalse();
assertThat(hasIndexedWriteMethodForProperty(bi, "foo"), is(false)); assertThat(hasIndexedWriteMethodForProperty(bi, "foo")).isFalse();
BeanInfo ebi = new ExtendedBeanInfo(bi); BeanInfo ebi = new ExtendedBeanInfo(bi);
assertThat(hasReadMethodForProperty(ebi, "foo"), is(true)); assertThat(hasReadMethodForProperty(ebi, "foo")).isTrue();
assertThat(hasWriteMethodForProperty(ebi, "foo"), is(false)); assertThat(hasWriteMethodForProperty(ebi, "foo")).isFalse();
assertThat(hasIndexedWriteMethodForProperty(ebi, "foo"), is(true)); assertThat(hasIndexedWriteMethodForProperty(ebi, "foo")).isTrue();
} }
@Test @Test
@ -158,20 +154,20 @@ public class ExtendedBeanInfoTests {
BeanInfo bi = Introspector.getBeanInfo(C.class); BeanInfo bi = Introspector.getBeanInfo(C.class);
assertThat(hasReadMethodForProperty(bi, "foo"), is(true)); assertThat(hasReadMethodForProperty(bi, "foo")).isTrue();
assertThat(hasWriteMethodForProperty(bi, "foo"), is(false)); assertThat(hasWriteMethodForProperty(bi, "foo")).isFalse();
ExtendedBeanInfo ebi = new ExtendedBeanInfo(bi); ExtendedBeanInfo ebi = new ExtendedBeanInfo(bi);
assertThat(hasReadMethodForProperty(bi, "foo"), is(true)); assertThat(hasReadMethodForProperty(bi, "foo")).isTrue();
assertThat(hasWriteMethodForProperty(bi, "foo"), is(false)); assertThat(hasWriteMethodForProperty(bi, "foo")).isFalse();
assertThat(hasReadMethodForProperty(ebi, "foo"), is(true)); assertThat(hasReadMethodForProperty(ebi, "foo")).isTrue();
assertThat(hasWriteMethodForProperty(ebi, "foo"), is(true)); assertThat(hasWriteMethodForProperty(ebi, "foo")).isTrue();
for (PropertyDescriptor pd : ebi.getPropertyDescriptors()) { for (PropertyDescriptor pd : ebi.getPropertyDescriptors()) {
if (pd.getName().equals("foo")) { if (pd.getName().equals("foo")) {
assertThat(pd.getWriteMethod(), is(C.class.getMethod("setFoo", String.class))); assertThat(pd.getWriteMethod()).isEqualTo(C.class.getMethod("setFoo", String.class));
return; return;
} }
} }
@ -193,11 +189,11 @@ public class ExtendedBeanInfoTests {
} }
{ // always passes { // always passes
ExtendedBeanInfo bi = new ExtendedBeanInfo(Introspector.getBeanInfo(Parent.class)); ExtendedBeanInfo bi = new ExtendedBeanInfo(Introspector.getBeanInfo(Parent.class));
assertThat(hasReadMethodForProperty(bi, "property1"), is(true)); assertThat(hasReadMethodForProperty(bi, "property1")).isTrue();
} }
{ // failed prior to fix for SPR-9414 { // failed prior to fix for SPR-9414
ExtendedBeanInfo bi = new ExtendedBeanInfo(Introspector.getBeanInfo(Child.class)); ExtendedBeanInfo bi = new ExtendedBeanInfo(Introspector.getBeanInfo(Child.class));
assertThat(hasReadMethodForProperty(bi, "property1"), is(true)); assertThat(hasReadMethodForProperty(bi, "property1")).isTrue();
} }
} }
@ -211,11 +207,11 @@ public class ExtendedBeanInfoTests {
} }
{ // always passes { // always passes
BeanInfo info = Introspector.getBeanInfo(Bean.class); BeanInfo info = Introspector.getBeanInfo(Bean.class);
assertThat(info.getPropertyDescriptors().length, equalTo(2)); assertThat(info.getPropertyDescriptors().length).isEqualTo(2);
} }
{ // failed prior to fix for SPR-9453 { // failed prior to fix for SPR-9453
BeanInfo info = new ExtendedBeanInfo(Introspector.getBeanInfo(Bean.class)); BeanInfo info = new ExtendedBeanInfo(Introspector.getBeanInfo(Bean.class));
assertThat(info.getPropertyDescriptors().length, equalTo(2)); assertThat(info.getPropertyDescriptors().length).isEqualTo(2);
} }
} }
@ -230,16 +226,16 @@ public class ExtendedBeanInfoTests {
BeanInfo bi = Introspector.getBeanInfo(C.class); BeanInfo bi = Introspector.getBeanInfo(C.class);
assertThat(hasReadMethodForProperty(bi, "foo"), is(true)); assertThat(hasReadMethodForProperty(bi, "foo")).isTrue();
assertThat(hasWriteMethodForProperty(bi, "foo"), is(false)); assertThat(hasWriteMethodForProperty(bi, "foo")).isFalse();
ExtendedBeanInfo ebi = new ExtendedBeanInfo(bi); ExtendedBeanInfo ebi = new ExtendedBeanInfo(bi);
assertThat(hasReadMethodForProperty(bi, "foo"), is(true)); assertThat(hasReadMethodForProperty(bi, "foo")).isTrue();
assertThat(hasWriteMethodForProperty(bi, "foo"), is(false)); assertThat(hasWriteMethodForProperty(bi, "foo")).isFalse();
assertThat(hasReadMethodForProperty(ebi, "foo"), is(true)); assertThat(hasReadMethodForProperty(ebi, "foo")).isTrue();
assertThat(hasWriteMethodForProperty(ebi, "foo"), is(true)); assertThat(hasWriteMethodForProperty(ebi, "foo")).isTrue();
} }
@Test @Test
@ -268,30 +264,30 @@ public class ExtendedBeanInfoTests {
.setFoo("blue") .setFoo("blue")
.setBar(42); .setBar(42);
assertThat(c.getFoo(), is("blue")); assertThat(c.getFoo()).isEqualTo("blue");
assertThat(c.getBar(), is(42)); assertThat(c.getBar()).isEqualTo(42);
BeanInfo bi = Introspector.getBeanInfo(C.class); BeanInfo bi = Introspector.getBeanInfo(C.class);
assertThat(hasReadMethodForProperty(bi, "foo"), is(true)); assertThat(hasReadMethodForProperty(bi, "foo")).isTrue();
assertThat(hasWriteMethodForProperty(bi, "foo"), is(false)); assertThat(hasWriteMethodForProperty(bi, "foo")).isFalse();
assertThat(hasReadMethodForProperty(bi, "bar"), is(true)); assertThat(hasReadMethodForProperty(bi, "bar")).isTrue();
assertThat(hasWriteMethodForProperty(bi, "bar"), is(false)); assertThat(hasWriteMethodForProperty(bi, "bar")).isFalse();
BeanInfo ebi = new ExtendedBeanInfo(bi); BeanInfo ebi = new ExtendedBeanInfo(bi);
assertThat(hasReadMethodForProperty(bi, "foo"), is(true)); assertThat(hasReadMethodForProperty(bi, "foo")).isTrue();
assertThat(hasWriteMethodForProperty(bi, "foo"), is(false)); assertThat(hasWriteMethodForProperty(bi, "foo")).isFalse();
assertThat(hasReadMethodForProperty(bi, "bar"), is(true)); assertThat(hasReadMethodForProperty(bi, "bar")).isTrue();
assertThat(hasWriteMethodForProperty(bi, "bar"), is(false)); assertThat(hasWriteMethodForProperty(bi, "bar")).isFalse();
assertThat(hasReadMethodForProperty(ebi, "foo"), is(true)); assertThat(hasReadMethodForProperty(ebi, "foo")).isTrue();
assertThat(hasWriteMethodForProperty(ebi, "foo"), is(true)); assertThat(hasWriteMethodForProperty(ebi, "foo")).isTrue();
assertThat(hasReadMethodForProperty(ebi, "bar"), is(true)); assertThat(hasReadMethodForProperty(ebi, "bar")).isTrue();
assertThat(hasWriteMethodForProperty(ebi, "bar"), is(true)); assertThat(hasWriteMethodForProperty(ebi, "bar")).isTrue();
} }
@Test @Test
@ -304,11 +300,11 @@ public class ExtendedBeanInfoTests {
BeanInfo bi = Introspector.getBeanInfo(C.class); BeanInfo bi = Introspector.getBeanInfo(C.class);
BeanInfo ebi = new ExtendedBeanInfo(bi); BeanInfo ebi = new ExtendedBeanInfo(bi);
assertThat(hasReadMethodForProperty(bi, "foo"), is(false)); assertThat(hasReadMethodForProperty(bi, "foo")).isFalse();
assertThat(hasWriteMethodForProperty(bi, "foo"), is(false)); assertThat(hasWriteMethodForProperty(bi, "foo")).isFalse();
assertThat(hasReadMethodForProperty(ebi, "foo"), is(false)); assertThat(hasReadMethodForProperty(ebi, "foo")).isFalse();
assertThat(hasWriteMethodForProperty(ebi, "foo"), is(false)); assertThat(hasWriteMethodForProperty(ebi, "foo")).isFalse();
} }
/** /**
@ -325,8 +321,8 @@ public class ExtendedBeanInfoTests {
BeanInfo bi = Introspector.getBeanInfo(C.class); BeanInfo bi = Introspector.getBeanInfo(C.class);
BeanInfo ebi = new ExtendedBeanInfo(bi); BeanInfo ebi = new ExtendedBeanInfo(bi);
assertThat(hasReadMethodForProperty(bi, "foo"), is(true)); assertThat(hasReadMethodForProperty(bi, "foo")).isTrue();
assertThat(hasReadMethodForProperty(ebi, "foo"), is(true)); assertThat(hasReadMethodForProperty(ebi, "foo")).isTrue();
assertEquals(hasWriteMethodForProperty(bi, "foo"), hasWriteMethodForProperty(ebi, "foo")); assertEquals(hasWriteMethodForProperty(bi, "foo"), hasWriteMethodForProperty(ebi, "foo"));
} }
@ -340,8 +336,8 @@ public class ExtendedBeanInfoTests {
BeanInfo bi = Introspector.getBeanInfo(C.class); BeanInfo bi = Introspector.getBeanInfo(C.class);
BeanInfo ebi = new ExtendedBeanInfo(bi); BeanInfo ebi = new ExtendedBeanInfo(bi);
assertThat(hasIndexedReadMethodForProperty(bi, "foos"), is(true)); assertThat(hasIndexedReadMethodForProperty(bi, "foos")).isTrue();
assertThat(hasIndexedReadMethodForProperty(ebi, "foos"), is(true)); assertThat(hasIndexedReadMethodForProperty(ebi, "foos")).isTrue();
assertEquals(hasIndexedWriteMethodForProperty(bi, "foos"), hasIndexedWriteMethodForProperty(ebi, "foos")); assertEquals(hasIndexedWriteMethodForProperty(bi, "foos"), hasIndexedWriteMethodForProperty(ebi, "foos"));
} }
@ -359,11 +355,11 @@ public class ExtendedBeanInfoTests {
BeanInfo bi = Introspector.getBeanInfo(C.class); BeanInfo bi = Introspector.getBeanInfo(C.class);
BeanInfo ebi = new ExtendedBeanInfo(bi); BeanInfo ebi = new ExtendedBeanInfo(bi);
assertThat(hasReadMethodForProperty(bi, "foo"), is(true)); assertThat(hasReadMethodForProperty(bi, "foo")).isTrue();
assertThat(hasWriteMethodForProperty(bi, "foo"), is(false)); assertThat(hasWriteMethodForProperty(bi, "foo")).isFalse();
assertThat(hasReadMethodForProperty(ebi, "foo"), is(true)); assertThat(hasReadMethodForProperty(ebi, "foo")).isTrue();
assertThat(hasWriteMethodForProperty(ebi, "foo"), is(false)); assertThat(hasWriteMethodForProperty(ebi, "foo")).isFalse();
} }
@Test @Test
@ -376,11 +372,11 @@ public class ExtendedBeanInfoTests {
BeanInfo bi = Introspector.getBeanInfo(C.class); BeanInfo bi = Introspector.getBeanInfo(C.class);
BeanInfo ebi = new ExtendedBeanInfo(bi); BeanInfo ebi = new ExtendedBeanInfo(bi);
assertThat(hasIndexedReadMethodForProperty(bi, "foos"), is(true)); assertThat(hasIndexedReadMethodForProperty(bi, "foos")).isTrue();
assertThat(hasIndexedWriteMethodForProperty(bi, "foos"), is(false)); assertThat(hasIndexedWriteMethodForProperty(bi, "foos")).isFalse();
assertThat(hasIndexedReadMethodForProperty(ebi, "foos"), is(true)); assertThat(hasIndexedReadMethodForProperty(ebi, "foos")).isTrue();
assertThat(hasIndexedWriteMethodForProperty(ebi, "foos"), is(false)); assertThat(hasIndexedWriteMethodForProperty(ebi, "foos")).isFalse();
} }
@Test @Test
@ -394,11 +390,11 @@ public class ExtendedBeanInfoTests {
BeanInfo bi = Introspector.getBeanInfo(C.class); BeanInfo bi = Introspector.getBeanInfo(C.class);
BeanInfo ebi = new ExtendedBeanInfo(Introspector.getBeanInfo(C.class)); BeanInfo ebi = new ExtendedBeanInfo(Introspector.getBeanInfo(C.class));
assertThat(hasReadMethodForProperty(bi, "foos"), is(false)); assertThat(hasReadMethodForProperty(bi, "foos")).isFalse();
assertThat(hasIndexedReadMethodForProperty(bi, "foos"), is(true)); assertThat(hasIndexedReadMethodForProperty(bi, "foos")).isTrue();
assertThat(hasReadMethodForProperty(ebi, "foos"), is(false)); assertThat(hasReadMethodForProperty(ebi, "foos")).isFalse();
assertThat(hasIndexedReadMethodForProperty(ebi, "foos"), is(true)); assertThat(hasIndexedReadMethodForProperty(ebi, "foos")).isTrue();
} }
@Test @Test
@ -412,11 +408,11 @@ public class ExtendedBeanInfoTests {
BeanInfo bi = Introspector.getBeanInfo(C.class); BeanInfo bi = Introspector.getBeanInfo(C.class);
BeanInfo ebi = new ExtendedBeanInfo(Introspector.getBeanInfo(C.class)); BeanInfo ebi = new ExtendedBeanInfo(Introspector.getBeanInfo(C.class));
assertThat(hasWriteMethodForProperty(bi, "foos"), is(false)); assertThat(hasWriteMethodForProperty(bi, "foos")).isFalse();
assertThat(hasIndexedWriteMethodForProperty(bi, "foos"), is(true)); assertThat(hasIndexedWriteMethodForProperty(bi, "foos")).isTrue();
assertThat(hasWriteMethodForProperty(ebi, "foos"), is(false)); assertThat(hasWriteMethodForProperty(ebi, "foos")).isFalse();
assertThat(hasIndexedWriteMethodForProperty(ebi, "foos"), is(true)); assertThat(hasIndexedWriteMethodForProperty(ebi, "foos")).isTrue();
} }
@Test @Test
@ -432,15 +428,15 @@ public class ExtendedBeanInfoTests {
BeanInfo bi = Introspector.getBeanInfo(C.class); BeanInfo bi = Introspector.getBeanInfo(C.class);
BeanInfo ebi = new ExtendedBeanInfo(Introspector.getBeanInfo(C.class)); BeanInfo ebi = new ExtendedBeanInfo(Introspector.getBeanInfo(C.class));
assertThat(hasReadMethodForProperty(bi, "foos"), is(false)); assertThat(hasReadMethodForProperty(bi, "foos")).isFalse();
assertThat(hasIndexedReadMethodForProperty(bi, "foos"), is(true)); assertThat(hasIndexedReadMethodForProperty(bi, "foos")).isTrue();
assertThat(hasWriteMethodForProperty(bi, "foos"), is(false)); assertThat(hasWriteMethodForProperty(bi, "foos")).isFalse();
assertThat(hasIndexedWriteMethodForProperty(bi, "foos"), is(true)); assertThat(hasIndexedWriteMethodForProperty(bi, "foos")).isTrue();
assertThat(hasReadMethodForProperty(ebi, "foos"), is(false)); assertThat(hasReadMethodForProperty(ebi, "foos")).isFalse();
assertThat(hasIndexedReadMethodForProperty(ebi, "foos"), is(true)); assertThat(hasIndexedReadMethodForProperty(ebi, "foos")).isTrue();
assertThat(hasWriteMethodForProperty(ebi, "foos"), is(false)); assertThat(hasWriteMethodForProperty(ebi, "foos")).isFalse();
assertThat(hasIndexedWriteMethodForProperty(ebi, "foos"), is(true)); assertThat(hasIndexedWriteMethodForProperty(ebi, "foos")).isTrue();
} }
@Test @Test
@ -460,15 +456,15 @@ public class ExtendedBeanInfoTests {
BeanInfo bi = Introspector.getBeanInfo(C.class); BeanInfo bi = Introspector.getBeanInfo(C.class);
BeanInfo ebi = new ExtendedBeanInfo(Introspector.getBeanInfo(C.class)); BeanInfo ebi = new ExtendedBeanInfo(Introspector.getBeanInfo(C.class));
assertThat(hasReadMethodForProperty(bi, "foos"), is(true)); assertThat(hasReadMethodForProperty(bi, "foos")).isTrue();
assertThat(hasWriteMethodForProperty(bi, "foos"), is(true)); assertThat(hasWriteMethodForProperty(bi, "foos")).isTrue();
assertThat(hasIndexedReadMethodForProperty(bi, "foos"), is(true)); assertThat(hasIndexedReadMethodForProperty(bi, "foos")).isTrue();
assertThat(hasIndexedWriteMethodForProperty(bi, "foos"), is(true)); assertThat(hasIndexedWriteMethodForProperty(bi, "foos")).isTrue();
assertThat(hasReadMethodForProperty(ebi, "foos"), is(true)); assertThat(hasReadMethodForProperty(ebi, "foos")).isTrue();
assertThat(hasWriteMethodForProperty(ebi, "foos"), is(true)); assertThat(hasWriteMethodForProperty(ebi, "foos")).isTrue();
assertThat(hasIndexedReadMethodForProperty(ebi, "foos"), is(true)); assertThat(hasIndexedReadMethodForProperty(ebi, "foos")).isTrue();
assertThat(hasIndexedWriteMethodForProperty(ebi, "foos"), is(true)); assertThat(hasIndexedWriteMethodForProperty(ebi, "foos")).isTrue();
} }
@Test @Test
@ -483,14 +479,14 @@ public class ExtendedBeanInfoTests {
BeanInfo bi = Introspector.getBeanInfo(C.class); BeanInfo bi = Introspector.getBeanInfo(C.class);
assertThat(hasIndexedReadMethodForProperty(bi, "foos"), is(true)); assertThat(hasIndexedReadMethodForProperty(bi, "foos")).isTrue();
// interesting! standard Inspector picks up non-void return types on indexed write methods by default // interesting! standard Inspector picks up non-void return types on indexed write methods by default
assertThat(hasIndexedWriteMethodForProperty(bi, "foos"), is(false)); assertThat(hasIndexedWriteMethodForProperty(bi, "foos")).isFalse();
BeanInfo ebi = new ExtendedBeanInfo(Introspector.getBeanInfo(C.class)); BeanInfo ebi = new ExtendedBeanInfo(Introspector.getBeanInfo(C.class));
assertThat(hasIndexedReadMethodForProperty(ebi, "foos"), is(true)); assertThat(hasIndexedReadMethodForProperty(ebi, "foos")).isTrue();
assertThat(hasIndexedWriteMethodForProperty(ebi, "foos"), is(true)); assertThat(hasIndexedWriteMethodForProperty(ebi, "foos")).isTrue();
} }
@Test @Test
@ -507,20 +503,20 @@ public class ExtendedBeanInfoTests {
BeanInfo bi = Introspector.getBeanInfo(C.class); BeanInfo bi = Introspector.getBeanInfo(C.class);
assertThat(hasIndexedReadMethodForProperty(bi, "foos"), is(true)); assertThat(hasIndexedReadMethodForProperty(bi, "foos")).isTrue();
assertThat(hasWriteMethodForProperty(bi, "foos"), is(false)); assertThat(hasWriteMethodForProperty(bi, "foos")).isFalse();
// again as above, standard Inspector picks up non-void return types on indexed write methods by default // again as above, standard Inspector picks up non-void return types on indexed write methods by default
assertThat(hasIndexedWriteMethodForProperty(bi, "foos"), is(false)); assertThat(hasIndexedWriteMethodForProperty(bi, "foos")).isFalse();
BeanInfo ebi = new ExtendedBeanInfo(Introspector.getBeanInfo(C.class)); BeanInfo ebi = new ExtendedBeanInfo(Introspector.getBeanInfo(C.class));
assertThat(hasIndexedReadMethodForProperty(bi, "foos"), is(true)); assertThat(hasIndexedReadMethodForProperty(bi, "foos")).isTrue();
assertThat(hasWriteMethodForProperty(bi, "foos"), is(false)); assertThat(hasWriteMethodForProperty(bi, "foos")).isFalse();
assertThat(hasIndexedWriteMethodForProperty(bi, "foos"), is(false)); assertThat(hasIndexedWriteMethodForProperty(bi, "foos")).isFalse();
assertThat(hasIndexedReadMethodForProperty(ebi, "foos"), is(true)); assertThat(hasIndexedReadMethodForProperty(ebi, "foos")).isTrue();
assertThat(hasWriteMethodForProperty(ebi, "foos"), is(true)); assertThat(hasWriteMethodForProperty(ebi, "foos")).isTrue();
assertThat(hasIndexedWriteMethodForProperty(ebi, "foos"), is(true)); assertThat(hasIndexedWriteMethodForProperty(ebi, "foos")).isTrue();
} }
@Test @Test
@ -535,16 +531,16 @@ public class ExtendedBeanInfoTests {
} }
BeanInfo bi = Introspector.getBeanInfo(C.class); BeanInfo bi = Introspector.getBeanInfo(C.class);
assertThat(hasReadMethodForProperty(bi, "foos"), is(false)); assertThat(hasReadMethodForProperty(bi, "foos")).isFalse();
assertThat(hasIndexedReadMethodForProperty(bi, "foos"), is(true)); assertThat(hasIndexedReadMethodForProperty(bi, "foos")).isTrue();
assertThat(hasWriteMethodForProperty(bi, "foos"), is(true)); assertThat(hasWriteMethodForProperty(bi, "foos")).isTrue();
assertThat(hasIndexedWriteMethodForProperty(bi, "foos"), is(false)); assertThat(hasIndexedWriteMethodForProperty(bi, "foos")).isFalse();
BeanInfo ebi = Introspector.getBeanInfo(C.class); BeanInfo ebi = Introspector.getBeanInfo(C.class);
assertThat(hasReadMethodForProperty(ebi, "foos"), is(false)); assertThat(hasReadMethodForProperty(ebi, "foos")).isFalse();
assertThat(hasIndexedReadMethodForProperty(ebi, "foos"), is(true)); assertThat(hasIndexedReadMethodForProperty(ebi, "foos")).isTrue();
assertThat(hasWriteMethodForProperty(ebi, "foos"), is(true)); assertThat(hasWriteMethodForProperty(ebi, "foos")).isTrue();
assertThat(hasIndexedWriteMethodForProperty(ebi, "foos"), is(false)); assertThat(hasIndexedWriteMethodForProperty(ebi, "foos")).isFalse();
} }
{ // variant with non-standard write method { // variant with non-standard write method
@SuppressWarnings("unused") @SuppressWarnings("unused")
@ -556,16 +552,16 @@ public class ExtendedBeanInfoTests {
} }
BeanInfo bi = Introspector.getBeanInfo(C.class); BeanInfo bi = Introspector.getBeanInfo(C.class);
assertThat(hasReadMethodForProperty(bi, "foos"), is(false)); assertThat(hasReadMethodForProperty(bi, "foos")).isFalse();
assertThat(hasIndexedReadMethodForProperty(bi, "foos"), is(true)); assertThat(hasIndexedReadMethodForProperty(bi, "foos")).isTrue();
assertThat(hasWriteMethodForProperty(bi, "foos"), is(false)); assertThat(hasWriteMethodForProperty(bi, "foos")).isFalse();
assertThat(hasIndexedWriteMethodForProperty(bi, "foos"), is(false)); assertThat(hasIndexedWriteMethodForProperty(bi, "foos")).isFalse();
BeanInfo ebi = new ExtendedBeanInfo(Introspector.getBeanInfo(C.class)); BeanInfo ebi = new ExtendedBeanInfo(Introspector.getBeanInfo(C.class));
assertThat(hasReadMethodForProperty(ebi, "foos"), is(false)); assertThat(hasReadMethodForProperty(ebi, "foos")).isFalse();
assertThat(hasIndexedReadMethodForProperty(ebi, "foos"), is(true)); assertThat(hasIndexedReadMethodForProperty(ebi, "foos")).isTrue();
assertThat(hasWriteMethodForProperty(ebi, "foos"), is(true)); assertThat(hasWriteMethodForProperty(ebi, "foos")).isTrue();
assertThat(hasIndexedWriteMethodForProperty(ebi, "foos"), is(false)); assertThat(hasIndexedWriteMethodForProperty(ebi, "foos")).isFalse();
} }
} }
@ -597,18 +593,18 @@ public class ExtendedBeanInfoTests {
BeanInfo bi = Introspector.getBeanInfo(C.class); BeanInfo bi = Introspector.getBeanInfo(C.class);
assertThat(hasReadMethodForProperty(bi, "foo"), is(true)); assertThat(hasReadMethodForProperty(bi, "foo")).isTrue();
assertThat(hasWriteMethodForProperty(bi, "foo"), is(false)); assertThat(hasWriteMethodForProperty(bi, "foo")).isFalse();
BeanInfo ebi = new ExtendedBeanInfo(bi); BeanInfo ebi = new ExtendedBeanInfo(bi);
assertThat(hasReadMethodForProperty(bi, "foo"), is(true)); assertThat(hasReadMethodForProperty(bi, "foo")).isTrue();
assertThat(hasWriteMethodForProperty(bi, "foo"), is(false)); assertThat(hasWriteMethodForProperty(bi, "foo")).isFalse();
assertThat(hasReadMethodForProperty(ebi, "foo"), is(true)); assertThat(hasReadMethodForProperty(ebi, "foo")).isTrue();
assertThat(hasWriteMethodForProperty(ebi, "foo"), is(true)); assertThat(hasWriteMethodForProperty(ebi, "foo")).isTrue();
assertThat(ebi.getPropertyDescriptors().length, equalTo(bi.getPropertyDescriptors().length)); assertThat(ebi.getPropertyDescriptors().length).isEqualTo(bi.getPropertyDescriptors().length);
} }
@Test @Test
@ -621,11 +617,11 @@ public class ExtendedBeanInfoTests {
BeanInfo bi = Introspector.getBeanInfo(C.class); BeanInfo bi = Introspector.getBeanInfo(C.class);
BeanInfo ebi = new ExtendedBeanInfo(bi); BeanInfo ebi = new ExtendedBeanInfo(bi);
assertThat(hasReadMethodForProperty(bi, "foo"), is(false)); assertThat(hasReadMethodForProperty(bi, "foo")).isFalse();
assertThat(hasWriteMethodForProperty(bi, "foo"), is(true)); assertThat(hasWriteMethodForProperty(bi, "foo")).isTrue();
assertThat(hasReadMethodForProperty(ebi, "foo"), is(false)); assertThat(hasReadMethodForProperty(ebi, "foo")).isFalse();
assertThat(hasWriteMethodForProperty(ebi, "foo"), is(true)); assertThat(hasWriteMethodForProperty(ebi, "foo")).isTrue();
} }
/** /**
@ -642,7 +638,7 @@ public class ExtendedBeanInfoTests {
BeanInfo bi = Introspector.getBeanInfo(C.class); BeanInfo bi = Introspector.getBeanInfo(C.class);
BeanInfo ebi = new ExtendedBeanInfo(bi); BeanInfo ebi = new ExtendedBeanInfo(bi);
assertThat(ebi.getPropertyDescriptors(), equalTo(bi.getPropertyDescriptors())); assertThat(ebi.getPropertyDescriptors()).isEqualTo(bi.getPropertyDescriptors());
} }
@Test @Test
@ -653,20 +649,20 @@ public class ExtendedBeanInfoTests {
} }
BeanInfo bi = Introspector.getBeanInfo(C.class); BeanInfo bi = Introspector.getBeanInfo(C.class);
assertThat(hasReadMethodForProperty(bi, "foo"), is(false)); assertThat(hasReadMethodForProperty(bi, "foo")).isFalse();
assertThat(hasWriteMethodForProperty(bi, "foo"), is(false)); assertThat(hasWriteMethodForProperty(bi, "foo")).isFalse();
BeanInfo ebi = new ExtendedBeanInfo(bi); BeanInfo ebi = new ExtendedBeanInfo(bi);
assertThat(hasReadMethodForProperty(bi, "foo"), is(false)); assertThat(hasReadMethodForProperty(bi, "foo")).isFalse();
assertThat(hasWriteMethodForProperty(bi, "foo"), is(false)); assertThat(hasWriteMethodForProperty(bi, "foo")).isFalse();
assertThat(hasReadMethodForProperty(ebi, "foo"), is(false)); assertThat(hasReadMethodForProperty(ebi, "foo")).isFalse();
assertThat(hasWriteMethodForProperty(ebi, "foo"), is(true)); assertThat(hasWriteMethodForProperty(ebi, "foo")).isTrue();
for (PropertyDescriptor pd : ebi.getPropertyDescriptors()) { for (PropertyDescriptor pd : ebi.getPropertyDescriptors()) {
if (pd.getName().equals("foo")) { if (pd.getName().equals("foo")) {
assertThat(pd.getWriteMethod(), is(C.class.getMethod("setFoo", String.class))); assertThat(pd.getWriteMethod()).isEqualTo(C.class.getMethod("setFoo", String.class));
return; return;
} }
} }
@ -681,20 +677,20 @@ public class ExtendedBeanInfoTests {
} }
BeanInfo bi = Introspector.getBeanInfo(C.class); BeanInfo bi = Introspector.getBeanInfo(C.class);
assertThat(hasReadMethodForProperty(bi, "foo"), is(false)); assertThat(hasReadMethodForProperty(bi, "foo")).isFalse();
assertThat(hasWriteMethodForProperty(bi, "foo"), is(false)); assertThat(hasWriteMethodForProperty(bi, "foo")).isFalse();
BeanInfo ebi = new ExtendedBeanInfo(bi); BeanInfo ebi = new ExtendedBeanInfo(bi);
assertThat(hasReadMethodForProperty(bi, "foo"), is(false)); assertThat(hasReadMethodForProperty(bi, "foo")).isFalse();
assertThat(hasWriteMethodForProperty(bi, "foo"), is(false)); assertThat(hasWriteMethodForProperty(bi, "foo")).isFalse();
assertThat(hasReadMethodForProperty(ebi, "foo"), is(false)); assertThat(hasReadMethodForProperty(ebi, "foo")).isFalse();
assertThat(hasWriteMethodForProperty(ebi, "foo"), is(true)); assertThat(hasWriteMethodForProperty(ebi, "foo")).isTrue();
for (PropertyDescriptor pd : ebi.getPropertyDescriptors()) { for (PropertyDescriptor pd : ebi.getPropertyDescriptors()) {
if (pd.getName().equals("foo")) { if (pd.getName().equals("foo")) {
assertThat(pd.getWriteMethod(), is(C.class.getMethod("setFoo", String.class))); assertThat(pd.getWriteMethod()).isEqualTo(C.class.getMethod("setFoo", String.class));
return; return;
} }
} }
@ -717,22 +713,22 @@ public class ExtendedBeanInfoTests {
} }
BeanInfo bi = Introspector.getBeanInfo(C.class); BeanInfo bi = Introspector.getBeanInfo(C.class);
assertThat(hasReadMethodForProperty(bi, "dateFormat"), is(false)); assertThat(hasReadMethodForProperty(bi, "dateFormat")).isFalse();
assertThat(hasWriteMethodForProperty(bi, "dateFormat"), is(false)); assertThat(hasWriteMethodForProperty(bi, "dateFormat")).isFalse();
assertThat(hasIndexedReadMethodForProperty(bi, "dateFormat"), is(false)); assertThat(hasIndexedReadMethodForProperty(bi, "dateFormat")).isFalse();
assertThat(hasIndexedWriteMethodForProperty(bi, "dateFormat"), is(false)); assertThat(hasIndexedWriteMethodForProperty(bi, "dateFormat")).isFalse();
BeanInfo ebi = new ExtendedBeanInfo(bi); BeanInfo ebi = new ExtendedBeanInfo(bi);
assertThat(hasReadMethodForProperty(bi, "dateFormat"), is(false)); assertThat(hasReadMethodForProperty(bi, "dateFormat")).isFalse();
assertThat(hasWriteMethodForProperty(bi, "dateFormat"), is(false)); assertThat(hasWriteMethodForProperty(bi, "dateFormat")).isFalse();
assertThat(hasIndexedReadMethodForProperty(bi, "dateFormat"), is(false)); assertThat(hasIndexedReadMethodForProperty(bi, "dateFormat")).isFalse();
assertThat(hasIndexedWriteMethodForProperty(bi, "dateFormat"), is(false)); assertThat(hasIndexedWriteMethodForProperty(bi, "dateFormat")).isFalse();
assertThat(hasReadMethodForProperty(ebi, "dateFormat"), is(false)); assertThat(hasReadMethodForProperty(ebi, "dateFormat")).isFalse();
assertThat(hasWriteMethodForProperty(ebi, "dateFormat"), is(true)); assertThat(hasWriteMethodForProperty(ebi, "dateFormat")).isTrue();
assertThat(hasIndexedReadMethodForProperty(ebi, "dateFormat"), is(false)); assertThat(hasIndexedReadMethodForProperty(ebi, "dateFormat")).isFalse();
assertThat(hasIndexedWriteMethodForProperty(ebi, "dateFormat"), is(false)); assertThat(hasIndexedWriteMethodForProperty(ebi, "dateFormat")).isFalse();
} }
@Test @Test
@ -740,7 +736,7 @@ public class ExtendedBeanInfoTests {
BeanInfo bi = Introspector.getBeanInfo(TestBean.class); BeanInfo bi = Introspector.getBeanInfo(TestBean.class);
BeanInfo ebi = new ExtendedBeanInfo(bi); BeanInfo ebi = new ExtendedBeanInfo(bi);
assertThat(ebi.getPropertyDescriptors().length, equalTo(bi.getPropertyDescriptors().length)); assertThat(ebi.getPropertyDescriptors().length).isEqualTo(bi.getPropertyDescriptors().length);
} }
@Test @Test
@ -759,8 +755,8 @@ public class ExtendedBeanInfoTests {
break; break;
} }
} }
assertThat(found, is(true)); assertThat(found).isTrue();
assertThat(ebi.getPropertyDescriptors().length, equalTo(bi.getPropertyDescriptors().length+1)); assertThat(ebi.getPropertyDescriptors().length).isEqualTo(bi.getPropertyDescriptors().length+1);
} }
/** /**
@ -773,8 +769,7 @@ public class ExtendedBeanInfoTests {
BeanInfo ebi = new ExtendedBeanInfo(bi); BeanInfo ebi = new ExtendedBeanInfo(bi);
for (int i = 0; i < bi.getPropertyDescriptors().length; i++) { for (int i = 0; i < bi.getPropertyDescriptors().length; i++) {
assertThat("element " + i + " in BeanInfo and ExtendedBeanInfo propertyDescriptor arrays do not match", assertThat(ebi.getPropertyDescriptors()[i].getName()).isEqualTo(bi.getPropertyDescriptors()[i].getName());
ebi.getPropertyDescriptors()[i].getName(), equalTo(bi.getPropertyDescriptors()[i].getName()));
} }
} }
@ -782,19 +777,19 @@ public class ExtendedBeanInfoTests {
public void propertyDescriptorComparator() throws IntrospectionException { public void propertyDescriptorComparator() throws IntrospectionException {
ExtendedBeanInfo.PropertyDescriptorComparator c = new ExtendedBeanInfo.PropertyDescriptorComparator(); ExtendedBeanInfo.PropertyDescriptorComparator c = new ExtendedBeanInfo.PropertyDescriptorComparator();
assertThat(c.compare(new PropertyDescriptor("a", null, null), new PropertyDescriptor("a", null, null)), equalTo(0)); assertThat(c.compare(new PropertyDescriptor("a", null, null), new PropertyDescriptor("a", null, null))).isEqualTo(0);
assertThat(c.compare(new PropertyDescriptor("abc", null, null), new PropertyDescriptor("abc", null, null)), equalTo(0)); assertThat(c.compare(new PropertyDescriptor("abc", null, null), new PropertyDescriptor("abc", null, null))).isEqualTo(0);
assertThat(c.compare(new PropertyDescriptor("a", null, null), new PropertyDescriptor("b", null, null)), lessThan(0)); assertThat(c.compare(new PropertyDescriptor("a", null, null), new PropertyDescriptor("b", null, null))).isLessThan(0);
assertThat(c.compare(new PropertyDescriptor("b", null, null), new PropertyDescriptor("a", null, null)), greaterThan(0)); assertThat(c.compare(new PropertyDescriptor("b", null, null), new PropertyDescriptor("a", null, null))).isGreaterThan(0);
assertThat(c.compare(new PropertyDescriptor("abc", null, null), new PropertyDescriptor("abd", null, null)), lessThan(0)); assertThat(c.compare(new PropertyDescriptor("abc", null, null), new PropertyDescriptor("abd", null, null))).isLessThan(0);
assertThat(c.compare(new PropertyDescriptor("xyz", null, null), new PropertyDescriptor("123", null, null)), greaterThan(0)); assertThat(c.compare(new PropertyDescriptor("xyz", null, null), new PropertyDescriptor("123", null, null))).isGreaterThan(0);
assertThat(c.compare(new PropertyDescriptor("a", null, null), new PropertyDescriptor("abc", null, null)), lessThan(0)); assertThat(c.compare(new PropertyDescriptor("a", null, null), new PropertyDescriptor("abc", null, null))).isLessThan(0);
assertThat(c.compare(new PropertyDescriptor("abc", null, null), new PropertyDescriptor("a", null, null)), greaterThan(0)); assertThat(c.compare(new PropertyDescriptor("abc", null, null), new PropertyDescriptor("a", null, null))).isGreaterThan(0);
assertThat(c.compare(new PropertyDescriptor("abc", null, null), new PropertyDescriptor("b", null, null)), lessThan(0)); assertThat(c.compare(new PropertyDescriptor("abc", null, null), new PropertyDescriptor("b", null, null))).isLessThan(0);
assertThat(c.compare(new PropertyDescriptor(" ", null, null), new PropertyDescriptor("a", null, null)), lessThan(0)); assertThat(c.compare(new PropertyDescriptor(" ", null, null), new PropertyDescriptor("a", null, null))).isLessThan(0);
assertThat(c.compare(new PropertyDescriptor("1", null, null), new PropertyDescriptor("a", null, null)), lessThan(0)); assertThat(c.compare(new PropertyDescriptor("1", null, null), new PropertyDescriptor("a", null, null))).isLessThan(0);
assertThat(c.compare(new PropertyDescriptor("a", null, null), new PropertyDescriptor("A", null, null)), greaterThan(0)); assertThat(c.compare(new PropertyDescriptor("a", null, null), new PropertyDescriptor("A", null, null))).isGreaterThan(0);
} }
@Test @Test
@ -830,11 +825,11 @@ public class ExtendedBeanInfoTests {
// helps out here, and is now put into use in ExtendedBeanInfo as well. // helps out here, and is now put into use in ExtendedBeanInfo as well.
BeanInfo ebi = new ExtendedBeanInfo(bi); BeanInfo ebi = new ExtendedBeanInfo(bi);
assertThat(hasReadMethodForProperty(bi, "targetMethod"), is(true)); assertThat(hasReadMethodForProperty(bi, "targetMethod")).isTrue();
assertThat(hasWriteMethodForProperty(bi, "targetMethod"), is(false)); assertThat(hasWriteMethodForProperty(bi, "targetMethod")).isFalse();
assertThat(hasReadMethodForProperty(ebi, "targetMethod"), is(true)); assertThat(hasReadMethodForProperty(ebi, "targetMethod")).isTrue();
assertThat(hasWriteMethodForProperty(ebi, "targetMethod"), is(false)); assertThat(hasWriteMethodForProperty(ebi, "targetMethod")).isFalse();
} }
@Test @Test
@ -864,27 +859,27 @@ public class ExtendedBeanInfoTests {
public void shouldSupportStaticWriteMethod() throws IntrospectionException { public void shouldSupportStaticWriteMethod() throws IntrospectionException {
{ {
BeanInfo bi = Introspector.getBeanInfo(WithStaticWriteMethod.class); BeanInfo bi = Introspector.getBeanInfo(WithStaticWriteMethod.class);
assertThat(hasReadMethodForProperty(bi, "prop1"), is(false)); assertThat(hasReadMethodForProperty(bi, "prop1")).isFalse();
assertThat(hasWriteMethodForProperty(bi, "prop1"), is(false)); assertThat(hasWriteMethodForProperty(bi, "prop1")).isFalse();
assertThat(hasIndexedReadMethodForProperty(bi, "prop1"), is(false)); assertThat(hasIndexedReadMethodForProperty(bi, "prop1")).isFalse();
assertThat(hasIndexedWriteMethodForProperty(bi, "prop1"), is(false)); assertThat(hasIndexedWriteMethodForProperty(bi, "prop1")).isFalse();
} }
{ {
BeanInfo bi = new ExtendedBeanInfo(Introspector.getBeanInfo(WithStaticWriteMethod.class)); BeanInfo bi = new ExtendedBeanInfo(Introspector.getBeanInfo(WithStaticWriteMethod.class));
assertThat(hasReadMethodForProperty(bi, "prop1"), is(false)); assertThat(hasReadMethodForProperty(bi, "prop1")).isFalse();
assertThat(hasWriteMethodForProperty(bi, "prop1"), is(true)); assertThat(hasWriteMethodForProperty(bi, "prop1")).isTrue();
assertThat(hasIndexedReadMethodForProperty(bi, "prop1"), is(false)); assertThat(hasIndexedReadMethodForProperty(bi, "prop1")).isFalse();
assertThat(hasIndexedWriteMethodForProperty(bi, "prop1"), is(false)); assertThat(hasIndexedWriteMethodForProperty(bi, "prop1")).isFalse();
} }
} }
@Test // SPR-12434 @Test // SPR-12434
public void shouldDetectValidPropertiesAndIgnoreInvalidProperties() throws IntrospectionException { public void shouldDetectValidPropertiesAndIgnoreInvalidProperties() throws IntrospectionException {
BeanInfo bi = new ExtendedBeanInfo(Introspector.getBeanInfo(java.awt.Window.class)); BeanInfo bi = new ExtendedBeanInfo(Introspector.getBeanInfo(java.awt.Window.class));
assertThat(hasReadMethodForProperty(bi, "locationByPlatform"), is(true)); assertThat(hasReadMethodForProperty(bi, "locationByPlatform")).isTrue();
assertThat(hasWriteMethodForProperty(bi, "locationByPlatform"), is(true)); assertThat(hasWriteMethodForProperty(bi, "locationByPlatform")).isTrue();
assertThat(hasIndexedReadMethodForProperty(bi, "locationByPlatform"), is(false)); assertThat(hasIndexedReadMethodForProperty(bi, "locationByPlatform")).isFalse();
assertThat(hasIndexedWriteMethodForProperty(bi, "locationByPlatform"), is(false)); assertThat(hasIndexedWriteMethodForProperty(bi, "locationByPlatform")).isFalse();
} }

View File

@ -20,10 +20,8 @@ import java.util.Iterator;
import org.junit.Test; import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.notNullValue;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertTrue;
@ -138,17 +136,17 @@ public class MutablePropertyValuesTests extends AbstractPropertyValuesTests {
MutablePropertyValues pvs = new MutablePropertyValues(); MutablePropertyValues pvs = new MutablePropertyValues();
pvs.add("foo", "bar"); pvs.add("foo", "bar");
assertThat(pvs.stream(), notNullValue()); assertThat(pvs.stream()).isNotNull();
assertThat(pvs.stream().count(), is(1L)); assertThat(pvs.stream().count()).isEqualTo(1L);
assertThat(pvs.stream().anyMatch(pv -> "foo".equals(pv.getName()) && "bar".equals(pv.getValue())), is(true)); assertThat(pvs.stream().anyMatch(pv -> "foo".equals(pv.getName()) && "bar".equals(pv.getValue()))).isTrue();
assertThat(pvs.stream().anyMatch(pv -> "bar".equals(pv.getName()) && "foo".equals(pv.getValue())), is(false)); assertThat(pvs.stream().anyMatch(pv -> "bar".equals(pv.getName()) && "foo".equals(pv.getValue()))).isFalse();
} }
@Test @Test
public void streamIsEmptyForEmptyValues() { public void streamIsEmptyForEmptyValues() {
MutablePropertyValues pvs = new MutablePropertyValues(); MutablePropertyValues pvs = new MutablePropertyValues();
assertThat(pvs.stream(), notNullValue()); assertThat(pvs.stream()).isNotNull();
assertThat(pvs.stream().count(), is(0L)); assertThat(pvs.stream().count()).isEqualTo(0L);
} }
} }

View File

@ -18,11 +18,12 @@ package org.springframework.beans;
import org.junit.Test; import org.junit.Test;
import static org.hamcrest.MatcherAssert.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.emptyArray;
import static org.hamcrest.Matchers.hasItemInArray;
import static org.hamcrest.Matchers.not;
/** /**
* Tests for {@link PropertyMatches}. * Tests for {@link PropertyMatches}.
@ -34,93 +35,93 @@ public class PropertyMatchesTests {
@Test @Test
public void simpleBeanPropertyTypo() { public void simpleBeanPropertyTypo() {
PropertyMatches matches = PropertyMatches.forProperty("naem", SampleBeanProperties.class); PropertyMatches matches = PropertyMatches.forProperty("naem", SampleBeanProperties.class);
assertThat(matches.getPossibleMatches(), hasItemInArray("name")); assertThat(matches.getPossibleMatches()).contains("name");
} }
@Test @Test
public void complexBeanPropertyTypo() { public void complexBeanPropertyTypo() {
PropertyMatches matches = PropertyMatches.forProperty("desriptn", SampleBeanProperties.class); PropertyMatches matches = PropertyMatches.forProperty("desriptn", SampleBeanProperties.class);
assertThat(matches.getPossibleMatches(), emptyArray()); assertThat(matches.getPossibleMatches()).isEmpty();
} }
@Test @Test
public void unknownBeanProperty() { public void unknownBeanProperty() {
PropertyMatches matches = PropertyMatches.forProperty("unknown", SampleBeanProperties.class); PropertyMatches matches = PropertyMatches.forProperty("unknown", SampleBeanProperties.class);
assertThat(matches.getPossibleMatches(), emptyArray()); assertThat(matches.getPossibleMatches()).isEmpty();
} }
@Test @Test
public void severalMatchesBeanProperty() { public void severalMatchesBeanProperty() {
PropertyMatches matches = PropertyMatches.forProperty("counter", SampleBeanProperties.class); PropertyMatches matches = PropertyMatches.forProperty("counter", SampleBeanProperties.class);
assertThat(matches.getPossibleMatches(), hasItemInArray("counter1")); assertThat(matches.getPossibleMatches()).contains("counter1");
assertThat(matches.getPossibleMatches(), hasItemInArray("counter2")); assertThat(matches.getPossibleMatches()).contains("counter2");
assertThat(matches.getPossibleMatches(), hasItemInArray("counter3")); assertThat(matches.getPossibleMatches()).contains("counter3");
} }
@Test @Test
public void simpleBeanPropertyErrorMessage() { public void simpleBeanPropertyErrorMessage() {
PropertyMatches matches = PropertyMatches.forProperty("naem", SampleBeanProperties.class); PropertyMatches matches = PropertyMatches.forProperty("naem", SampleBeanProperties.class);
String msg = matches.buildErrorMessage(); String msg = matches.buildErrorMessage();
assertThat(msg, containsString("naem")); assertThat(msg).contains("naem");
assertThat(msg, containsString("name")); assertThat(msg).contains("name");
assertThat(msg, containsString("setter")); assertThat(msg).contains("setter");
assertThat(msg, not(containsString("field"))); assertThat(msg).doesNotContain("field");
} }
@Test @Test
public void complexBeanPropertyErrorMessage() { public void complexBeanPropertyErrorMessage() {
PropertyMatches matches = PropertyMatches.forProperty("counter", SampleBeanProperties.class); PropertyMatches matches = PropertyMatches.forProperty("counter", SampleBeanProperties.class);
String msg = matches.buildErrorMessage(); String msg = matches.buildErrorMessage();
assertThat(msg, containsString("counter")); assertThat(msg).contains("counter");
assertThat(msg, containsString("counter1")); assertThat(msg).contains("counter1");
assertThat(msg, containsString("counter2")); assertThat(msg).contains("counter2");
assertThat(msg, containsString("counter3")); assertThat(msg).contains("counter3");
} }
@Test @Test
public void simpleFieldPropertyTypo() { public void simpleFieldPropertyTypo() {
PropertyMatches matches = PropertyMatches.forField("naem", SampleFieldProperties.class); PropertyMatches matches = PropertyMatches.forField("naem", SampleFieldProperties.class);
assertThat(matches.getPossibleMatches(), hasItemInArray("name")); assertThat(matches.getPossibleMatches()).contains("name");
} }
@Test @Test
public void complexFieldPropertyTypo() { public void complexFieldPropertyTypo() {
PropertyMatches matches = PropertyMatches.forField("desriptn", SampleFieldProperties.class); PropertyMatches matches = PropertyMatches.forField("desriptn", SampleFieldProperties.class);
assertThat(matches.getPossibleMatches(), emptyArray()); assertThat(matches.getPossibleMatches()).isEmpty();
} }
@Test @Test
public void unknownFieldProperty() { public void unknownFieldProperty() {
PropertyMatches matches = PropertyMatches.forField("unknown", SampleFieldProperties.class); PropertyMatches matches = PropertyMatches.forField("unknown", SampleFieldProperties.class);
assertThat(matches.getPossibleMatches(), emptyArray()); assertThat(matches.getPossibleMatches()).isEmpty();
} }
@Test @Test
public void severalMatchesFieldProperty() { public void severalMatchesFieldProperty() {
PropertyMatches matches = PropertyMatches.forField("counter", SampleFieldProperties.class); PropertyMatches matches = PropertyMatches.forField("counter", SampleFieldProperties.class);
assertThat(matches.getPossibleMatches(), hasItemInArray("counter1")); assertThat(matches.getPossibleMatches()).contains("counter1");
assertThat(matches.getPossibleMatches(), hasItemInArray("counter2")); assertThat(matches.getPossibleMatches()).contains("counter2");
assertThat(matches.getPossibleMatches(), hasItemInArray("counter3")); assertThat(matches.getPossibleMatches()).contains("counter3");
} }
@Test @Test
public void simpleFieldPropertyErrorMessage() { public void simpleFieldPropertyErrorMessage() {
PropertyMatches matches = PropertyMatches.forField("naem", SampleFieldProperties.class); PropertyMatches matches = PropertyMatches.forField("naem", SampleFieldProperties.class);
String msg = matches.buildErrorMessage(); String msg = matches.buildErrorMessage();
assertThat(msg, containsString("naem")); assertThat(msg).contains("naem");
assertThat(msg, containsString("name")); assertThat(msg).contains("name");
assertThat(msg, containsString("field")); assertThat(msg).contains("field");
assertThat(msg, not(containsString("setter"))); assertThat(msg).doesNotContain("setter");
} }
@Test @Test
public void complexFieldPropertyErrorMessage() { public void complexFieldPropertyErrorMessage() {
PropertyMatches matches = PropertyMatches.forField("counter", SampleFieldProperties.class); PropertyMatches matches = PropertyMatches.forField("counter", SampleFieldProperties.class);
String msg = matches.buildErrorMessage(); String msg = matches.buildErrorMessage();
assertThat(msg, containsString("counter")); assertThat(msg).contains("counter");
assertThat(msg, containsString("counter1")); assertThat(msg).contains("counter1");
assertThat(msg, containsString("counter2")); assertThat(msg).contains("counter2");
assertThat(msg, containsString("counter3")); assertThat(msg).contains("counter3");
} }

View File

@ -23,11 +23,8 @@ import java.lang.reflect.Method;
import org.junit.Test; import org.junit.Test;
import static org.hamcrest.CoreMatchers.allOf; import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.not;
import static org.hamcrest.MatcherAssert.assertThat;
/** /**
* @author Chris Beams * @author Chris Beams
@ -39,8 +36,8 @@ public class SimplePropertyDescriptorTests {
public void toStringOutput() throws IntrospectionException, SecurityException, NoSuchMethodException { public void toStringOutput() throws IntrospectionException, SecurityException, NoSuchMethodException {
{ {
Object pd = new ExtendedBeanInfo.SimplePropertyDescriptor("foo", null, null); Object pd = new ExtendedBeanInfo.SimplePropertyDescriptor("foo", null, null);
assertThat(pd.toString(), containsString( assertThat(pd.toString()).contains(
"PropertyDescriptor[name=foo, propertyType=null, readMethod=null")); "PropertyDescriptor[name=foo, propertyType=null, readMethod=null");
} }
{ {
class C { class C {
@ -49,15 +46,15 @@ public class SimplePropertyDescriptorTests {
} }
Method m = C.class.getMethod("setFoo", String.class); Method m = C.class.getMethod("setFoo", String.class);
Object pd = new ExtendedBeanInfo.SimplePropertyDescriptor("foo", null, m); Object pd = new ExtendedBeanInfo.SimplePropertyDescriptor("foo", null, m);
assertThat(pd.toString(), allOf( assertThat(pd.toString()).contains(
containsString("PropertyDescriptor[name=foo"), "PropertyDescriptor[name=foo",
containsString("propertyType=class java.lang.String"), "propertyType=class java.lang.String",
containsString("readMethod=null, writeMethod=public java.lang.Object"))); "readMethod=null, writeMethod=public java.lang.Object");
} }
{ {
Object pd = new ExtendedBeanInfo.SimpleIndexedPropertyDescriptor("foo", null, null, null, null); Object pd = new ExtendedBeanInfo.SimpleIndexedPropertyDescriptor("foo", null, null, null, null);
assertThat(pd.toString(), containsString( assertThat(pd.toString()).contains(
"PropertyDescriptor[name=foo, propertyType=null, indexedPropertyType=null")); "PropertyDescriptor[name=foo, propertyType=null, indexedPropertyType=null");
} }
{ {
class C { class C {
@ -66,21 +63,21 @@ public class SimplePropertyDescriptorTests {
} }
Method m = C.class.getMethod("setFoo", int.class, String.class); Method m = C.class.getMethod("setFoo", int.class, String.class);
Object pd = new ExtendedBeanInfo.SimpleIndexedPropertyDescriptor("foo", null, null, null, m); Object pd = new ExtendedBeanInfo.SimpleIndexedPropertyDescriptor("foo", null, null, null, m);
assertThat(pd.toString(), allOf( assertThat(pd.toString()).contains(
containsString("PropertyDescriptor[name=foo, propertyType=null"), "PropertyDescriptor[name=foo, propertyType=null",
containsString("indexedPropertyType=class java.lang.String"), "indexedPropertyType=class java.lang.String",
containsString("indexedWriteMethod=public java.lang.Object"))); "indexedWriteMethod=public java.lang.Object");
} }
} }
@Test @Test
public void nonIndexedEquality() throws IntrospectionException, SecurityException, NoSuchMethodException { public void nonIndexedEquality() throws IntrospectionException, SecurityException, NoSuchMethodException {
Object pd1 = new ExtendedBeanInfo.SimplePropertyDescriptor("foo", null, null); Object pd1 = new ExtendedBeanInfo.SimplePropertyDescriptor("foo", null, null);
assertThat(pd1, equalTo(pd1)); assertThat(pd1).isEqualTo(pd1);
Object pd2 = new ExtendedBeanInfo.SimplePropertyDescriptor("foo", null, null); Object pd2 = new ExtendedBeanInfo.SimplePropertyDescriptor("foo", null, null);
assertThat(pd1, equalTo(pd2)); assertThat(pd1).isEqualTo(pd2);
assertThat(pd2, equalTo(pd1)); assertThat(pd2).isEqualTo(pd1);
@SuppressWarnings("unused") @SuppressWarnings("unused")
class C { class C {
@ -89,35 +86,35 @@ public class SimplePropertyDescriptorTests {
} }
Method wm1 = C.class.getMethod("setFoo", String.class); Method wm1 = C.class.getMethod("setFoo", String.class);
Object pd3 = new ExtendedBeanInfo.SimplePropertyDescriptor("foo", null, wm1); Object pd3 = new ExtendedBeanInfo.SimplePropertyDescriptor("foo", null, wm1);
assertThat(pd1, not(equalTo(pd3))); assertThat(pd1).isNotEqualTo(pd3);
assertThat(pd3, not(equalTo(pd1))); assertThat(pd3).isNotEqualTo(pd1);
Method rm1 = C.class.getMethod("getFoo"); Method rm1 = C.class.getMethod("getFoo");
Object pd4 = new ExtendedBeanInfo.SimplePropertyDescriptor("foo", rm1, null); Object pd4 = new ExtendedBeanInfo.SimplePropertyDescriptor("foo", rm1, null);
assertThat(pd1, not(equalTo(pd4))); assertThat(pd1).isNotEqualTo(pd4);
assertThat(pd4, not(equalTo(pd1))); assertThat(pd4).isNotEqualTo(pd1);
Object pd5 = new PropertyDescriptor("foo", null, null); Object pd5 = new PropertyDescriptor("foo", null, null);
assertThat(pd1, equalTo(pd5)); assertThat(pd1).isEqualTo(pd5);
assertThat(pd5, equalTo(pd1)); assertThat(pd5).isEqualTo(pd1);
Object pd6 = "not a PD"; Object pd6 = "not a PD";
assertThat(pd1, not(equalTo(pd6))); assertThat(pd1).isNotEqualTo(pd6);
assertThat(pd6, not(equalTo(pd1))); assertThat(pd6).isNotEqualTo(pd1);
Object pd7 = null; Object pd7 = null;
assertThat(pd1, not(equalTo(pd7))); assertThat(pd1).isNotEqualTo(pd7);
assertThat(pd7, not(equalTo(pd1))); assertThat(pd7).isNotEqualTo(pd1);
} }
@Test @Test
public void indexedEquality() throws IntrospectionException, SecurityException, NoSuchMethodException { public void indexedEquality() throws IntrospectionException, SecurityException, NoSuchMethodException {
Object pd1 = new ExtendedBeanInfo.SimpleIndexedPropertyDescriptor("foo", null, null, null, null); Object pd1 = new ExtendedBeanInfo.SimpleIndexedPropertyDescriptor("foo", null, null, null, null);
assertThat(pd1, equalTo(pd1)); assertThat(pd1).isEqualTo(pd1);
Object pd2 = new ExtendedBeanInfo.SimpleIndexedPropertyDescriptor("foo", null, null, null, null); Object pd2 = new ExtendedBeanInfo.SimpleIndexedPropertyDescriptor("foo", null, null, null, null);
assertThat(pd1, equalTo(pd2)); assertThat(pd1).isEqualTo(pd2);
assertThat(pd2, equalTo(pd1)); assertThat(pd2).isEqualTo(pd1);
@SuppressWarnings("unused") @SuppressWarnings("unused")
class C { class C {
@ -126,25 +123,25 @@ public class SimplePropertyDescriptorTests {
} }
Method wm1 = C.class.getMethod("setFoo", int.class, String.class); Method wm1 = C.class.getMethod("setFoo", int.class, String.class);
Object pd3 = new ExtendedBeanInfo.SimpleIndexedPropertyDescriptor("foo", null, null, null, wm1); Object pd3 = new ExtendedBeanInfo.SimpleIndexedPropertyDescriptor("foo", null, null, null, wm1);
assertThat(pd1, not(equalTo(pd3))); assertThat(pd1).isNotEqualTo(pd3);
assertThat(pd3, not(equalTo(pd1))); assertThat(pd3).isNotEqualTo(pd1);
Method rm1 = C.class.getMethod("getFoo", int.class); Method rm1 = C.class.getMethod("getFoo", int.class);
Object pd4 = new ExtendedBeanInfo.SimpleIndexedPropertyDescriptor("foo", null, null, rm1, null); Object pd4 = new ExtendedBeanInfo.SimpleIndexedPropertyDescriptor("foo", null, null, rm1, null);
assertThat(pd1, not(equalTo(pd4))); assertThat(pd1).isNotEqualTo(pd4);
assertThat(pd4, not(equalTo(pd1))); assertThat(pd4).isNotEqualTo(pd1);
Object pd5 = new IndexedPropertyDescriptor("foo", null, null, null, null); Object pd5 = new IndexedPropertyDescriptor("foo", null, null, null, null);
assertThat(pd1, equalTo(pd5)); assertThat(pd1).isEqualTo(pd5);
assertThat(pd5, equalTo(pd1)); assertThat(pd5).isEqualTo(pd1);
Object pd6 = "not a PD"; Object pd6 = "not a PD";
assertThat(pd1, not(equalTo(pd6))); assertThat(pd1).isNotEqualTo(pd6);
assertThat(pd6, not(equalTo(pd1))); assertThat(pd6).isNotEqualTo(pd1);
Object pd7 = null; Object pd7 = null;
assertThat(pd1, not(equalTo(pd7))); assertThat(pd1).isNotEqualTo(pd7);
assertThat(pd7, not(equalTo(pd1))); assertThat(pd7).isNotEqualTo(pd1);
} }
} }

View File

@ -103,8 +103,6 @@ import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.assertj.core.api.Assertions.assertThatIllegalStateException; import static org.assertj.core.api.Assertions.assertThatIllegalStateException;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertNotEquals;
@ -1380,7 +1378,7 @@ public class DefaultListableBeanFactoryTests {
parent.registerBeanDefinition("bd1", bd1); parent.registerBeanDefinition("bd1", bd1);
DefaultListableBeanFactory lbf = new DefaultListableBeanFactory(parent); DefaultListableBeanFactory lbf = new DefaultListableBeanFactory(parent);
TestBean bean = lbf.getBean(TestBean.class); TestBean bean = lbf.getBean(TestBean.class);
assertThat(bean.getBeanName(), equalTo("bd1")); assertThat(bean.getBeanName()).isEqualTo("bd1");
} }
@Test @Test
@ -1404,7 +1402,7 @@ public class DefaultListableBeanFactoryTests {
lbf.registerBeanDefinition("bd1", bd1); lbf.registerBeanDefinition("bd1", bd1);
lbf.registerBeanDefinition("bd2", bd2); lbf.registerBeanDefinition("bd2", bd2);
TestBean bean = lbf.getBean(TestBean.class); TestBean bean = lbf.getBean(TestBean.class);
assertThat(bean.getBeanName(), equalTo("bd2")); assertThat(bean.getBeanName()).isEqualTo("bd2");
assertFalse(lbf.containsSingleton("bd1")); assertFalse(lbf.containsSingleton("bd1"));
} }
@ -1453,7 +1451,7 @@ public class DefaultListableBeanFactoryTests {
lbf.registerBeanDefinition("bd3", bd3); lbf.registerBeanDefinition("bd3", bd3);
lbf.preInstantiateSingletons(); lbf.preInstantiateSingletons();
TestBean bean = lbf.getBean(TestBean.class); TestBean bean = lbf.getBean(TestBean.class);
assertThat(bean.getBeanName(), equalTo("bd1")); assertThat(bean.getBeanName()).isEqualTo("bd1");
} }
@Test @Test
@ -1470,7 +1468,7 @@ public class DefaultListableBeanFactoryTests {
lbf.registerBeanDefinition("bd4", bd4); lbf.registerBeanDefinition("bd4", bd4);
lbf.preInstantiateSingletons(); lbf.preInstantiateSingletons();
TestBean bean = lbf.getBean(TestBeanRecipient.class).testBean; TestBean bean = lbf.getBean(TestBeanRecipient.class).testBean;
assertThat(bean.getBeanName(), equalTo("bd1")); assertThat(bean.getBeanName()).isEqualTo("bd1");
} }
@Test @Test
@ -1496,7 +1494,7 @@ public class DefaultListableBeanFactoryTests {
lbf.registerBeanDefinition("bd1", bd1); lbf.registerBeanDefinition("bd1", bd1);
lbf.registerBeanDefinition("bd2", bd2); lbf.registerBeanDefinition("bd2", bd2);
TestBean bean = lbf.getBean(TestBean.class); TestBean bean = lbf.getBean(TestBean.class);
assertThat(bean.getBeanName(), equalTo("bd1")); assertThat(bean.getBeanName()).isEqualTo("bd1");
} }
@Test @Test
@ -1509,7 +1507,7 @@ public class DefaultListableBeanFactoryTests {
lbf.registerBeanDefinition("bd1", bd1); lbf.registerBeanDefinition("bd1", bd1);
lbf.registerBeanDefinition("bd2", bd2); lbf.registerBeanDefinition("bd2", bd2);
TestBean bean = lbf.getBean(TestBean.class); TestBean bean = lbf.getBean(TestBean.class);
assertThat(bean.getBeanName(), equalTo("bd2")); assertThat(bean.getBeanName()).isEqualTo("bd2");
} }
@Test @Test
@ -1554,25 +1552,25 @@ public class DefaultListableBeanFactoryTests {
DefaultListableBeanFactory lbf = new DefaultListableBeanFactory(parent); DefaultListableBeanFactory lbf = new DefaultListableBeanFactory(parent);
ConstructorDependency bean = lbf.getBean(ConstructorDependency.class); ConstructorDependency bean = lbf.getBean(ConstructorDependency.class);
assertThat(bean.beanName, equalTo("bd1")); assertThat(bean.beanName).isEqualTo("bd1");
assertThat(bean.spouseAge, equalTo(99)); assertThat(bean.spouseAge).isEqualTo(99);
bean = lbf.getBean(ConstructorDependency.class, 42); bean = lbf.getBean(ConstructorDependency.class, 42);
assertThat(bean.beanName, equalTo("bd1")); assertThat(bean.beanName).isEqualTo("bd1");
assertThat(bean.spouseAge, equalTo(42)); assertThat(bean.spouseAge).isEqualTo(42);
ObjectProvider<ConstructorDependency> provider = lbf.getBeanProvider(ConstructorDependency.class); ObjectProvider<ConstructorDependency> provider = lbf.getBeanProvider(ConstructorDependency.class);
bean = provider.getObject(); bean = provider.getObject();
assertThat(bean.beanName, equalTo("bd1")); assertThat(bean.beanName).isEqualTo("bd1");
assertThat(bean.spouseAge, equalTo(99)); assertThat(bean.spouseAge).isEqualTo(99);
bean = provider.getObject(42); bean = provider.getObject(42);
assertThat(bean.beanName, equalTo("bd1")); assertThat(bean.beanName).isEqualTo("bd1");
assertThat(bean.spouseAge, equalTo(42)); assertThat(bean.spouseAge).isEqualTo(42);
bean = provider.getIfAvailable(); bean = provider.getIfAvailable();
assertThat(bean.beanName, equalTo("bd1")); assertThat(bean.beanName).isEqualTo("bd1");
assertThat(bean.spouseAge, equalTo(99)); assertThat(bean.spouseAge).isEqualTo(99);
bean = provider.getIfUnique(); bean = provider.getIfUnique();
assertThat(bean.beanName, equalTo("bd1")); assertThat(bean.beanName).isEqualTo("bd1");
assertThat(bean.spouseAge, equalTo(99)); assertThat(bean.spouseAge).isEqualTo(99);
} }
@Test @Test
@ -1627,25 +1625,25 @@ public class DefaultListableBeanFactoryTests {
lbf.registerBeanDefinition("bd2", bd2); lbf.registerBeanDefinition("bd2", bd2);
ConstructorDependency bean = lbf.getBean(ConstructorDependency.class); ConstructorDependency bean = lbf.getBean(ConstructorDependency.class);
assertThat(bean.beanName, equalTo("bd2")); assertThat(bean.beanName).isEqualTo("bd2");
assertThat(bean.spouseAge, equalTo(43)); assertThat(bean.spouseAge).isEqualTo(43);
bean = lbf.getBean(ConstructorDependency.class, 42); bean = lbf.getBean(ConstructorDependency.class, 42);
assertThat(bean.beanName, equalTo("bd2")); assertThat(bean.beanName).isEqualTo("bd2");
assertThat(bean.spouseAge, equalTo(42)); assertThat(bean.spouseAge).isEqualTo(42);
ObjectProvider<ConstructorDependency> provider = lbf.getBeanProvider(ConstructorDependency.class); ObjectProvider<ConstructorDependency> provider = lbf.getBeanProvider(ConstructorDependency.class);
bean = provider.getObject(); bean = provider.getObject();
assertThat(bean.beanName, equalTo("bd2")); assertThat(bean.beanName).isEqualTo("bd2");
assertThat(bean.spouseAge, equalTo(43)); assertThat(bean.spouseAge).isEqualTo(43);
bean = provider.getObject(42); bean = provider.getObject(42);
assertThat(bean.beanName, equalTo("bd2")); assertThat(bean.beanName).isEqualTo("bd2");
assertThat(bean.spouseAge, equalTo(42)); assertThat(bean.spouseAge).isEqualTo(42);
bean = provider.getIfAvailable(); bean = provider.getIfAvailable();
assertThat(bean.beanName, equalTo("bd2")); assertThat(bean.beanName).isEqualTo("bd2");
assertThat(bean.spouseAge, equalTo(43)); assertThat(bean.spouseAge).isEqualTo(43);
bean = provider.getIfUnique(); bean = provider.getIfUnique();
assertThat(bean.beanName, equalTo("bd2")); assertThat(bean.beanName).isEqualTo("bd2");
assertThat(bean.spouseAge, equalTo(43)); assertThat(bean.spouseAge).isEqualTo(43);
Set<Object> resolved = new HashSet<>(); Set<Object> resolved = new HashSet<>();
for (ConstructorDependency instance : provider) { for (ConstructorDependency instance : provider) {
@ -1693,7 +1691,7 @@ public class DefaultListableBeanFactoryTests {
lbf.registerBeanDefinition("bd1", bd1); lbf.registerBeanDefinition("bd1", bd1);
lbf.registerBeanDefinition("na1", na1); lbf.registerBeanDefinition("na1", na1);
ConstructorDependency actual = lbf.getBean(ConstructorDependency.class, 42); // na1 was filtered ConstructorDependency actual = lbf.getBean(ConstructorDependency.class, 42); // na1 was filtered
assertThat(actual.beanName, equalTo("bd1")); assertThat(actual.beanName).isEqualTo("bd1");
lbf.registerBeanDefinition("bd2", bd2); lbf.registerBeanDefinition("bd2", bd2);
assertThatExceptionOfType(NoSuchBeanDefinitionException.class).isThrownBy(() -> assertThatExceptionOfType(NoSuchBeanDefinitionException.class).isThrownBy(() ->
@ -1727,8 +1725,8 @@ public class DefaultListableBeanFactoryTests {
lbf.registerBeanDefinition("bd2", bd2); lbf.registerBeanDefinition("bd2", bd2);
ConstructorDependency bean = lbf.getBean(ConstructorDependency.class, 42); ConstructorDependency bean = lbf.getBean(ConstructorDependency.class, 42);
assertThat(bean.beanName, equalTo("bd1")); assertThat(bean.beanName).isEqualTo("bd1");
assertThat(bean.spouseAge, equalTo(42)); assertThat(bean.spouseAge).isEqualTo(42);
assertEquals(1, lbf.getBeanNamesForType(ConstructorDependency.class).length); assertEquals(1, lbf.getBeanNamesForType(ConstructorDependency.class).length);
assertEquals(1, lbf.getBeanNamesForType(ConstructorDependencyFactoryBean.class).length); assertEquals(1, lbf.getBeanNamesForType(ConstructorDependencyFactoryBean.class).length);
@ -1902,7 +1900,7 @@ public class DefaultListableBeanFactoryTests {
DependenciesBean bean = (DependenciesBean) DependenciesBean bean = (DependenciesBean)
lbf.autowire(DependenciesBean.class, AutowireCapableBeanFactory.AUTOWIRE_BY_TYPE, true); lbf.autowire(DependenciesBean.class, AutowireCapableBeanFactory.AUTOWIRE_BY_TYPE, true);
assertThat(bean.getSpouse(), equalTo(lbf.getBean("test"))); assertThat(bean.getSpouse()).isEqualTo(lbf.getBean("test"));
} }
@Test @Test
@ -1930,7 +1928,7 @@ public class DefaultListableBeanFactoryTests {
DependenciesBean bean = (DependenciesBean) DependenciesBean bean = (DependenciesBean)
lbf.autowire(DependenciesBean.class, AutowireCapableBeanFactory.AUTOWIRE_BY_TYPE, true); lbf.autowire(DependenciesBean.class, AutowireCapableBeanFactory.AUTOWIRE_BY_TYPE, true);
assertThat(bean.getSpouse(), equalTo(lbf.getBean("test"))); assertThat(bean.getSpouse()).isEqualTo(lbf.getBean("test"));
} }
@Test @Test
@ -1959,7 +1957,7 @@ public class DefaultListableBeanFactoryTests {
DependenciesBean bean = (DependenciesBean) DependenciesBean bean = (DependenciesBean)
lbf.autowire(DependenciesBean.class, AutowireCapableBeanFactory.AUTOWIRE_BY_TYPE, true); lbf.autowire(DependenciesBean.class, AutowireCapableBeanFactory.AUTOWIRE_BY_TYPE, true);
assertThat(bean.getSpouse(), equalTo(lbf.getBean("spouse"))); assertThat(bean.getSpouse()).isEqualTo(lbf.getBean("spouse"));
} }
@Test @Test
@ -2768,8 +2766,8 @@ public class DefaultListableBeanFactoryTests {
DefaultListableBeanFactory bf = new DefaultListableBeanFactory(); DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
bf.registerBeanDefinition("abs", BeanDefinitionBuilder bf.registerBeanDefinition("abs", BeanDefinitionBuilder
.rootBeanDefinition(TestBean.class).setAbstract(true).getBeanDefinition()); .rootBeanDefinition(TestBean.class).setAbstract(true).getBeanDefinition());
assertThat(bf.containsBean("abs"), equalTo(true)); assertThat(bf.containsBean("abs")).isEqualTo(true);
assertThat(bf.containsBean("bogus"), equalTo(false)); assertThat(bf.containsBean("bogus")).isEqualTo(false);
} }
@Test @Test

View File

@ -25,8 +25,7 @@ import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.beans.factory.xml.XmlBeanDefinitionReader; import org.springframework.beans.factory.xml.XmlBeanDefinitionReader;
import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.ClassPathResource;
import static org.hamcrest.CoreMatchers.instanceOf; import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNotNull;
/** /**
@ -47,7 +46,7 @@ public class FactoryBeanLookupTests {
@Test @Test
public void factoryBeanLookupByNameDereferencing() { public void factoryBeanLookupByNameDereferencing() {
Object fooFactory = beanFactory.getBean("&fooFactory"); Object fooFactory = beanFactory.getBean("&fooFactory");
assertThat(fooFactory, instanceOf(FooFactoryBean.class)); assertThat(fooFactory).isInstanceOf(FooFactoryBean.class);
} }
@Test @Test
@ -65,7 +64,7 @@ public class FactoryBeanLookupTests {
@Test @Test
public void factoryBeanObjectLookupByName() { public void factoryBeanObjectLookupByName() {
Object fooFactory = beanFactory.getBean("fooFactory"); Object fooFactory = beanFactory.getBean("fooFactory");
assertThat(fooFactory, instanceOf(Foo.class)); assertThat(fooFactory).isInstanceOf(Foo.class);
} }
@Test @Test

View File

@ -28,10 +28,7 @@ import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource; import org.springframework.core.io.Resource;
import org.springframework.tests.sample.beans.TestBean; import org.springframework.tests.sample.beans.TestBean;
import static org.hamcrest.CoreMatchers.equalTo; import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.nullValue;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.springframework.beans.factory.support.BeanDefinitionBuilder.genericBeanDefinition; import static org.springframework.beans.factory.support.BeanDefinitionBuilder.genericBeanDefinition;
import static org.springframework.beans.factory.support.BeanDefinitionBuilder.rootBeanDefinition; import static org.springframework.beans.factory.support.BeanDefinitionBuilder.rootBeanDefinition;
import static org.springframework.beans.factory.support.BeanDefinitionReaderUtils.registerWithGeneratedName; import static org.springframework.beans.factory.support.BeanDefinitionReaderUtils.registerWithGeneratedName;
@ -101,8 +98,8 @@ public class PropertyPlaceholderConfigurerTests {
registerWithGeneratedName(p1BeanDef, bf); registerWithGeneratedName(p1BeanDef, bf);
ppc.postProcessBeanFactory(bf); ppc.postProcessBeanFactory(bf);
TestBean bean = bf.getBean(TestBean.class); TestBean bean = bf.getBean(TestBean.class);
assertThat(bean.getName(), equalTo(P1_LOCAL_PROPS_VAL)); assertThat(bean.getName()).isEqualTo(P1_LOCAL_PROPS_VAL);
assertThat(bean.getSex(), equalTo("systemValue")); assertThat(bean.getSex()).isEqualTo("systemValue");
System.clearProperty("otherKey"); System.clearProperty("otherKey");
} }
@ -112,7 +109,7 @@ public class PropertyPlaceholderConfigurerTests {
registerWithGeneratedName(p1BeanDef, bf); registerWithGeneratedName(p1BeanDef, bf);
ppc.postProcessBeanFactory(bf); ppc.postProcessBeanFactory(bf);
TestBean bean = bf.getBean(TestBean.class); TestBean bean = bf.getBean(TestBean.class);
assertThat(bean.getName(), equalTo(P1_LOCAL_PROPS_VAL)); assertThat(bean.getName()).isEqualTo(P1_LOCAL_PROPS_VAL);
} }
@Test @Test
@ -120,7 +117,7 @@ public class PropertyPlaceholderConfigurerTests {
registerWithGeneratedName(p1BeanDef, bf); registerWithGeneratedName(p1BeanDef, bf);
ppc.postProcessBeanFactory(bf); ppc.postProcessBeanFactory(bf);
TestBean bean = bf.getBean(TestBean.class); TestBean bean = bf.getBean(TestBean.class);
assertThat(bean.getName(), equalTo(P1_LOCAL_PROPS_VAL)); assertThat(bean.getName()).isEqualTo(P1_LOCAL_PROPS_VAL);
} }
@Test @Test
@ -129,7 +126,7 @@ public class PropertyPlaceholderConfigurerTests {
ppc.setSystemPropertiesMode(PropertyPlaceholderConfigurer.SYSTEM_PROPERTIES_MODE_OVERRIDE); ppc.setSystemPropertiesMode(PropertyPlaceholderConfigurer.SYSTEM_PROPERTIES_MODE_OVERRIDE);
ppc.postProcessBeanFactory(bf); ppc.postProcessBeanFactory(bf);
TestBean bean = bf.getBean(TestBean.class); TestBean bean = bf.getBean(TestBean.class);
assertThat(bean.getName(), equalTo(P1_SYSTEM_PROPS_VAL)); assertThat(bean.getName()).isEqualTo(P1_SYSTEM_PROPS_VAL);
} }
@Test @Test
@ -140,7 +137,7 @@ public class PropertyPlaceholderConfigurerTests {
ppc.setSystemPropertiesMode(PropertyPlaceholderConfigurer.SYSTEM_PROPERTIES_MODE_OVERRIDE); ppc.setSystemPropertiesMode(PropertyPlaceholderConfigurer.SYSTEM_PROPERTIES_MODE_OVERRIDE);
ppc.postProcessBeanFactory(bf); ppc.postProcessBeanFactory(bf);
TestBean bean = bf.getBean(TestBean.class); TestBean bean = bf.getBean(TestBean.class);
assertThat(bean.getName(), equalTo(P1_LOCAL_PROPS_VAL)); // has to resort to local props assertThat(bean.getName()).isEqualTo(P1_LOCAL_PROPS_VAL); // has to resort to local props
} }
/** /**
@ -177,11 +174,11 @@ public class PropertyPlaceholderConfigurerTests {
ppc2.postProcessBeanFactory(bf); ppc2.postProcessBeanFactory(bf);
TestBean p1Bean = bf.getBean("p1Bean", TestBean.class); TestBean p1Bean = bf.getBean("p1Bean", TestBean.class);
assertThat(p1Bean.getName(), equalTo(P1_LOCAL_PROPS_VAL)); assertThat(p1Bean.getName()).isEqualTo(P1_LOCAL_PROPS_VAL);
TestBean p2Bean = bf.getBean("p2Bean", TestBean.class); TestBean p2Bean = bf.getBean("p2Bean", TestBean.class);
assertThat(p2Bean.getName(), equalTo(P1_LOCAL_PROPS_VAL)); assertThat(p2Bean.getName()).isEqualTo(P1_LOCAL_PROPS_VAL);
assertThat(p2Bean.getCountry(), equalTo(P2_SYSTEM_PROPS_VAL)); assertThat(p2Bean.getCountry()).isEqualTo(P2_SYSTEM_PROPS_VAL);
System.clearProperty(P2); System.clearProperty(P2);
} }
@ -205,8 +202,8 @@ public class PropertyPlaceholderConfigurerTests {
System.clearProperty("key1"); System.clearProperty("key1");
System.clearProperty("key2"); System.clearProperty("key2");
assertThat(bf.getBean(TestBean.class).getName(), is("systemKey1Value")); assertThat(bf.getBean(TestBean.class).getName()).isEqualTo("systemKey1Value");
assertThat(bf.getBean(TestBean.class).getSex(), is("${key2}")); assertThat(bf.getBean(TestBean.class).getSex()).isEqualTo("${key2}");
} }
@Test @Test
@ -219,7 +216,7 @@ public class PropertyPlaceholderConfigurerTests {
.addPropertyValue("name", "${my.name}") .addPropertyValue("name", "${my.name}")
.getBeanDefinition()); .getBeanDefinition());
ppc.postProcessBeanFactory(bf); ppc.postProcessBeanFactory(bf);
assertThat(bf.getBean(TestBean.class).getName(), nullValue()); assertThat(bf.getBean(TestBean.class).getName()).isNull();
System.clearProperty("my.name"); System.clearProperty("my.name");
} }
@ -232,7 +229,7 @@ public class PropertyPlaceholderConfigurerTests {
.addPropertyValue("name", "${my.name}") .addPropertyValue("name", "${my.name}")
.getBeanDefinition()); .getBeanDefinition());
ppc.postProcessBeanFactory(bf); ppc.postProcessBeanFactory(bf);
assertThat(bf.getBean(TestBean.class).getName(), equalTo(" myValue ")); assertThat(bf.getBean(TestBean.class).getName()).isEqualTo(" myValue ");
System.clearProperty("my.name"); System.clearProperty("my.name");
} }
@ -246,7 +243,7 @@ public class PropertyPlaceholderConfigurerTests {
.addPropertyValue("name", "${my.name}") .addPropertyValue("name", "${my.name}")
.getBeanDefinition()); .getBeanDefinition());
ppc.postProcessBeanFactory(bf); ppc.postProcessBeanFactory(bf);
assertThat(bf.getBean(TestBean.class).getName(), equalTo("myValue")); assertThat(bf.getBean(TestBean.class).getName()).isEqualTo("myValue");
System.clearProperty("my.name"); System.clearProperty("my.name");
} }

View File

@ -30,11 +30,12 @@ import org.springframework.beans.factory.config.YamlProcessor.ResolutionMethod;
import org.springframework.core.io.ByteArrayResource; import org.springframework.core.io.ByteArrayResource;
import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.ClassPathResource;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.nullValue;
/** /**
* Tests for {@link YamlPropertiesFactoryBean}. * Tests for {@link YamlPropertiesFactoryBean}.
@ -50,8 +51,8 @@ public class YamlPropertiesFactoryBeanTests {
YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean(); YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean();
factory.setResources(new ByteArrayResource("foo: bar\nspam:\n foo: baz".getBytes())); factory.setResources(new ByteArrayResource("foo: bar\nspam:\n foo: baz".getBytes()));
Properties properties = factory.getObject(); Properties properties = factory.getObject();
assertThat(properties.getProperty("foo"), equalTo("bar")); assertThat(properties.getProperty("foo")).isEqualTo("bar");
assertThat(properties.getProperty("spam.foo"), equalTo("baz")); assertThat(properties.getProperty("spam.foo")).isEqualTo("baz");
} }
@Test @Test
@ -71,9 +72,9 @@ public class YamlPropertiesFactoryBeanTests {
new ByteArrayResource("foo: bar\nspam:\n foo: baz".getBytes()), new ByteArrayResource("foo: bar\nspam:\n foo: baz".getBytes()),
new ByteArrayResource("foo:\n bar: spam".getBytes())); new ByteArrayResource("foo:\n bar: spam".getBytes()));
Properties properties = factory.getObject(); Properties properties = factory.getObject();
assertThat(properties.getProperty("foo"), equalTo("bar")); assertThat(properties.getProperty("foo")).isEqualTo("bar");
assertThat(properties.getProperty("spam.foo"), equalTo("baz")); assertThat(properties.getProperty("spam.foo")).isEqualTo("baz");
assertThat(properties.getProperty("foo.bar"), equalTo("spam")); assertThat(properties.getProperty("foo.bar")).isEqualTo("spam");
} }
@Test @Test
@ -100,8 +101,8 @@ public class YamlPropertiesFactoryBeanTests {
factory.setResources(new ByteArrayResource( factory.setResources(new ByteArrayResource(
"foo: bar\nspam: baz\n---\nfoo: bag".getBytes())); "foo: bar\nspam: baz\n---\nfoo: bag".getBytes()));
Properties properties = factory.getObject(); Properties properties = factory.getObject();
assertThat(properties.getProperty("foo"), equalTo("bag")); assertThat(properties.getProperty("foo")).isEqualTo("bag");
assertThat(properties.getProperty("spam"), equalTo("baz")); assertThat(properties.getProperty("spam")).isEqualTo("baz");
} }
@Test @Test
@ -112,8 +113,8 @@ public class YamlPropertiesFactoryBeanTests {
factory.setDocumentMatchers(properties -> ("bag".equals(properties.getProperty("foo")) ? factory.setDocumentMatchers(properties -> ("bag".equals(properties.getProperty("foo")) ?
MatchStatus.FOUND : MatchStatus.NOT_FOUND)); MatchStatus.FOUND : MatchStatus.NOT_FOUND));
Properties properties = factory.getObject(); Properties properties = factory.getObject();
assertThat(properties.getProperty("foo"), equalTo("bag")); assertThat(properties.getProperty("foo")).isEqualTo("bag");
assertThat(properties.getProperty("spam"), equalTo("bad")); assertThat(properties.getProperty("spam")).isEqualTo("bad");
} }
@Test @Test
@ -130,9 +131,9 @@ public class YamlPropertiesFactoryBeanTests {
MatchStatus.FOUND : MatchStatus.NOT_FOUND); MatchStatus.FOUND : MatchStatus.NOT_FOUND);
}); });
Properties properties = factory.getObject(); Properties properties = factory.getObject();
assertThat(properties.getProperty("foo"), equalTo("bag")); assertThat(properties.getProperty("foo")).isEqualTo("bag");
assertThat(properties.getProperty("spam"), equalTo("bad")); assertThat(properties.getProperty("spam")).isEqualTo("bad");
assertThat(properties.getProperty("one"), equalTo("two")); assertThat(properties.getProperty("one")).isEqualTo("two");
} }
@Test @Test
@ -152,9 +153,9 @@ public class YamlPropertiesFactoryBeanTests {
} }
}); });
Properties properties = factory.getObject(); Properties properties = factory.getObject();
assertThat(properties.getProperty("foo"), equalTo("bag")); assertThat(properties.getProperty("foo")).isEqualTo("bag");
assertThat(properties.getProperty("spam"), equalTo("bad")); assertThat(properties.getProperty("spam")).isEqualTo("bad");
assertThat(properties.getProperty("one"), nullValue()); assertThat(properties.getProperty("one")).isNull();
} }
@Test @Test
@ -171,9 +172,9 @@ public class YamlPropertiesFactoryBeanTests {
MatchStatus.FOUND : MatchStatus.NOT_FOUND); MatchStatus.FOUND : MatchStatus.NOT_FOUND);
}); });
Properties properties = factory.getObject(); Properties properties = factory.getObject();
assertThat(properties.getProperty("foo"), equalTo("bag")); assertThat(properties.getProperty("foo")).isEqualTo("bag");
assertThat(properties.getProperty("spam"), equalTo("bad")); assertThat(properties.getProperty("spam")).isEqualTo("bad");
assertThat(properties.getProperty("one"), equalTo("two")); assertThat(properties.getProperty("one")).isEqualTo("two");
} }
@Test @Test
@ -182,7 +183,7 @@ public class YamlPropertiesFactoryBeanTests {
factory.setResolutionMethod(ResolutionMethod.OVERRIDE_AND_IGNORE); factory.setResolutionMethod(ResolutionMethod.OVERRIDE_AND_IGNORE);
factory.setResources(new ClassPathResource("no-such-file.yml")); factory.setResources(new ClassPathResource("no-such-file.yml"));
Properties properties = factory.getObject(); Properties properties = factory.getObject();
assertThat(properties.size(), equalTo(0)); assertThat(properties.size()).isEqualTo(0);
} }
@Test @Test
@ -190,8 +191,8 @@ public class YamlPropertiesFactoryBeanTests {
YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean(); YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean();
factory.setResources(new ByteArrayResource("foo: bar\nspam:".getBytes())); factory.setResources(new ByteArrayResource("foo: bar\nspam:".getBytes()));
Properties properties = factory.getObject(); Properties properties = factory.getObject();
assertThat(properties.getProperty("foo"), equalTo("bar")); assertThat(properties.getProperty("foo")).isEqualTo("bar");
assertThat(properties.getProperty("spam"), equalTo("")); assertThat(properties.getProperty("spam")).isEqualTo("");
} }
@Test @Test
@ -199,8 +200,8 @@ public class YamlPropertiesFactoryBeanTests {
YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean(); YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean();
factory.setResources(new ByteArrayResource("a: alpha\ntest: []".getBytes())); factory.setResources(new ByteArrayResource("a: alpha\ntest: []".getBytes()));
Properties properties = factory.getObject(); Properties properties = factory.getObject();
assertThat(properties.getProperty("a"), equalTo("alpha")); assertThat(properties.getProperty("a")).isEqualTo("alpha");
assertThat(properties.getProperty("test"), equalTo("")); assertThat(properties.getProperty("test")).isEqualTo("");
} }
@Test @Test
@ -208,9 +209,9 @@ public class YamlPropertiesFactoryBeanTests {
YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean(); YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean();
factory.setResources(new ByteArrayResource("foo:\n- bar\n- baz".getBytes())); factory.setResources(new ByteArrayResource("foo:\n- bar\n- baz".getBytes()));
Properties properties = factory.getObject(); Properties properties = factory.getObject();
assertThat(properties.getProperty("foo[0]"), equalTo("bar")); assertThat(properties.getProperty("foo[0]")).isEqualTo("bar");
assertThat(properties.getProperty("foo[1]"), equalTo("baz")); assertThat(properties.getProperty("foo[1]")).isEqualTo("baz");
assertThat(properties.get("foo"), is(nullValue())); assertThat(properties.get("foo")).isNull();
} }
@Test @Test
@ -218,9 +219,9 @@ public class YamlPropertiesFactoryBeanTests {
YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean(); YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean();
factory.setResources(new ByteArrayResource("foo:\n- 1\n- 2".getBytes())); factory.setResources(new ByteArrayResource("foo:\n- 1\n- 2".getBytes()));
Properties properties = factory.getObject(); Properties properties = factory.getObject();
assertThat(properties.getProperty("foo[0]"), equalTo("1")); assertThat(properties.getProperty("foo[0]")).isEqualTo("1");
assertThat(properties.getProperty("foo[1]"), equalTo("2")); assertThat(properties.getProperty("foo[1]")).isEqualTo("2");
assertThat(properties.get("foo"), is(nullValue())); assertThat(properties.get("foo")).isNull();
} }
@Test @Test
@ -230,11 +231,11 @@ public class YamlPropertiesFactoryBeanTests {
"foo:\n- bar:\n spam: crap\n- baz\n- one: two\n three: four".getBytes() "foo:\n- bar:\n spam: crap\n- baz\n- one: two\n three: four".getBytes()
)); ));
Properties properties = factory.getObject(); Properties properties = factory.getObject();
assertThat(properties.getProperty("foo[0].bar.spam"), equalTo("crap")); assertThat(properties.getProperty("foo[0].bar.spam")).isEqualTo("crap");
assertThat(properties.getProperty("foo[1]"), equalTo("baz")); assertThat(properties.getProperty("foo[1]")).isEqualTo("baz");
assertThat(properties.getProperty("foo[2].one"), equalTo("two")); assertThat(properties.getProperty("foo[2].one")).isEqualTo("two");
assertThat(properties.getProperty("foo[2].three"), equalTo("four")); assertThat(properties.getProperty("foo[2].three")).isEqualTo("four");
assertThat(properties.get("foo"), is(nullValue())); assertThat(properties.get("foo")).isNull();
} }
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
@ -242,8 +243,8 @@ public class YamlPropertiesFactoryBeanTests {
public void testYaml() { public void testYaml() {
Yaml yaml = new Yaml(); Yaml yaml = new Yaml();
Map<String, ?> map = yaml.loadAs("foo: bar\nspam:\n foo: baz", Map.class); Map<String, ?> map = yaml.loadAs("foo: bar\nspam:\n foo: baz", Map.class);
assertThat(map.get("foo"), equalTo("bar")); assertThat(map.get("foo")).isEqualTo("bar");
assertThat(((Map<String, Object>) map.get("spam")).get("foo"), equalTo("baz")); assertThat(((Map<String, Object>) map.get("spam")).get("foo")).isEqualTo("baz");
} }
} }

View File

@ -26,11 +26,8 @@ import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.config.InstantiationAwareBeanPostProcessor; import org.springframework.beans.factory.config.InstantiationAwareBeanPostProcessor;
import org.springframework.beans.factory.config.InstantiationAwareBeanPostProcessorAdapter; import org.springframework.beans.factory.config.InstantiationAwareBeanPostProcessorAdapter;
import static org.hamcrest.CoreMatchers.equalTo; import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.CoreMatchers.hasItem;
import static org.hamcrest.CoreMatchers.instanceOf;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
/** /**
* Unit tests for SPR-8954, in which a custom {@link InstantiationAwareBeanPostProcessor} * Unit tests for SPR-8954, in which a custom {@link InstantiationAwareBeanPostProcessor}
@ -56,32 +53,32 @@ public class Spr8954Tests {
@Test @Test
public void repro() { public void repro() {
assertThat(bf.getBean("foo"), instanceOf(Foo.class)); assertThat(bf.getBean("foo")).isInstanceOf(Foo.class);
assertThat(bf.getBean("&foo"), instanceOf(FooFactoryBean.class)); assertThat(bf.getBean("&foo")).isInstanceOf(FooFactoryBean.class);
assertThat(bf.isTypeMatch("&foo", FactoryBean.class), is(true)); assertThat(bf.isTypeMatch("&foo", FactoryBean.class)).isTrue();
@SuppressWarnings("rawtypes") @SuppressWarnings("rawtypes")
Map<String, FactoryBean> fbBeans = bf.getBeansOfType(FactoryBean.class); Map<String, FactoryBean> fbBeans = bf.getBeansOfType(FactoryBean.class);
assertThat(fbBeans.size(), is(1)); assertThat(fbBeans).hasSize(1);
assertThat(fbBeans.keySet(), hasItem("&foo")); assertThat(fbBeans.keySet()).contains("&foo");
Map<String, AnInterface> aiBeans = bf.getBeansOfType(AnInterface.class); Map<String, AnInterface> aiBeans = bf.getBeansOfType(AnInterface.class);
assertThat(aiBeans.size(), is(1)); assertThat(aiBeans).hasSize(1);
assertThat(aiBeans.keySet(), hasItem("&foo")); assertThat(aiBeans.keySet()).contains("&foo");
} }
@Test @Test
public void findsBeansByTypeIfNotInstantiated() { public void findsBeansByTypeIfNotInstantiated() {
assertThat(bf.isTypeMatch("&foo", FactoryBean.class), is(true)); assertThat(bf.isTypeMatch("&foo", FactoryBean.class)).isTrue();
@SuppressWarnings("rawtypes") @SuppressWarnings("rawtypes")
Map<String, FactoryBean> fbBeans = bf.getBeansOfType(FactoryBean.class); Map<String, FactoryBean> fbBeans = bf.getBeansOfType(FactoryBean.class);
assertThat(1, equalTo(fbBeans.size())); assertThat(1).isEqualTo(fbBeans.size());
assertThat("&foo", equalTo(fbBeans.keySet().iterator().next())); assertThat("&foo").isEqualTo(fbBeans.keySet().iterator().next());
Map<String, AnInterface> aiBeans = bf.getBeansOfType(AnInterface.class); Map<String, AnInterface> aiBeans = bf.getBeansOfType(AnInterface.class);
assertThat(aiBeans.size(), is(1)); assertThat(aiBeans).hasSize(1);
assertThat(aiBeans.keySet(), hasItem("&foo")); assertThat(aiBeans.keySet()).contains("&foo");
} }
/** /**
@ -90,11 +87,11 @@ public class Spr8954Tests {
@Test @Test
public void findsFactoryBeanNameByTypeWithoutInstantiation() { public void findsFactoryBeanNameByTypeWithoutInstantiation() {
String[] names = bf.getBeanNamesForType(AnInterface.class, false, false); String[] names = bf.getBeanNamesForType(AnInterface.class, false, false);
assertThat(Arrays.asList(names), hasItem("&foo")); assertThat(Arrays.asList(names)).contains("&foo");
Map<String, AnInterface> beans = bf.getBeansOfType(AnInterface.class, false, false); Map<String, AnInterface> beans = bf.getBeansOfType(AnInterface.class, false, false);
assertThat(beans.size(), is(1)); assertThat(beans).hasSize(1);
assertThat(beans.keySet(), hasItem("&foo")); assertThat(beans.keySet()).contains("&foo");
} }

View File

@ -22,9 +22,9 @@ import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.ClassPathResource;
import org.springframework.tests.sample.beans.TestBean; import org.springframework.tests.sample.beans.TestBean;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.MatcherAssert.assertThat;
/** /**
* With Spring 3.1, bean id attributes (and all other id attributes across the * With Spring 3.1, bean id attributes (and all other id attributes across the
@ -56,6 +56,6 @@ public class DuplicateBeanIdTests {
XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(bf); XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(bf);
reader.loadBeanDefinitions(new ClassPathResource("DuplicateBeanIdTests-multiLevel-context.xml", this.getClass())); reader.loadBeanDefinitions(new ClassPathResource("DuplicateBeanIdTests-multiLevel-context.xml", this.getClass()));
TestBean testBean = bf.getBean(TestBean.class); // there should be only one TestBean testBean = bf.getBean(TestBean.class); // there should be only one
assertThat(testBean.getName(), equalTo("nested")); assertThat(testBean.getName()).isEqualTo("nested");
} }
} }

View File

@ -23,10 +23,9 @@ import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.ClassPathResource;
import org.springframework.tests.sample.beans.TestBean; import org.springframework.tests.sample.beans.TestBean;
import static org.hamcrest.CoreMatchers.is; import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.CoreMatchers.not;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.hasItems;
/** /**
* Tests for propagating enclosing beans element defaults to nested beans elements. * Tests for propagating enclosing beans element defaults to nested beans elements.
@ -62,11 +61,11 @@ public class NestedBeansElementAttributeRecursionTests {
BeanDefinition biz = bf.getBeanDefinition("biz"); BeanDefinition biz = bf.getBeanDefinition("biz");
BeanDefinition buz = bf.getBeanDefinition("buz"); BeanDefinition buz = bf.getBeanDefinition("buz");
assertThat(foo.isLazyInit(), is(false)); assertThat(foo.isLazyInit()).isFalse();
assertThat(bar.isLazyInit(), is(true)); assertThat(bar.isLazyInit()).isTrue();
assertThat(baz.isLazyInit(), is(false)); assertThat(baz.isLazyInit()).isFalse();
assertThat(biz.isLazyInit(), is(true)); assertThat(biz.isLazyInit()).isTrue();
assertThat(buz.isLazyInit(), is(true)); assertThat(buz.isLazyInit()).isTrue();
} }
@Test @Test
@ -95,19 +94,19 @@ public class NestedBeansElementAttributeRecursionTests {
private void assertMerge(DefaultListableBeanFactory bf) { private void assertMerge(DefaultListableBeanFactory bf) {
TestBean topLevel = bf.getBean("topLevelConcreteTestBean", TestBean.class); TestBean topLevel = bf.getBean("topLevelConcreteTestBean", TestBean.class);
// has the concrete child bean values // has the concrete child bean values
assertThat((Iterable<String>) topLevel.getSomeList(), hasItems("charlie", "delta")); assertThat((Iterable<String>) topLevel.getSomeList()).contains("charlie", "delta");
// but does not merge the parent values // but does not merge the parent values
assertThat((Iterable<String>) topLevel.getSomeList(), not(hasItems("alpha", "bravo"))); assertThat((Iterable<String>) topLevel.getSomeList()).doesNotContain("alpha", "bravo");
TestBean firstLevel = bf.getBean("firstLevelNestedTestBean", TestBean.class); TestBean firstLevel = bf.getBean("firstLevelNestedTestBean", TestBean.class);
// merges all values // merges all values
assertThat((Iterable<String>) firstLevel.getSomeList(), assertThat((Iterable<String>) firstLevel.getSomeList()).contains(
hasItems("charlie", "delta", "echo", "foxtrot")); "charlie", "delta", "echo", "foxtrot");
TestBean secondLevel = bf.getBean("secondLevelNestedTestBean", TestBean.class); TestBean secondLevel = bf.getBean("secondLevelNestedTestBean", TestBean.class);
// merges all values // merges all values
assertThat((Iterable<String>)secondLevel.getSomeList(), assertThat((Iterable<String>)secondLevel.getSomeList()).contains(
hasItems("charlie", "delta", "echo", "foxtrot", "golf", "hotel")); "charlie", "delta", "echo", "foxtrot", "golf", "hotel");
} }
@Test @Test
@ -131,23 +130,23 @@ public class NestedBeansElementAttributeRecursionTests {
} }
private void assertAutowireCandidates(DefaultListableBeanFactory bf) { private void assertAutowireCandidates(DefaultListableBeanFactory bf) {
assertThat(bf.getBeanDefinition("fooService").isAutowireCandidate(), is(true)); assertThat(bf.getBeanDefinition("fooService").isAutowireCandidate()).isTrue();
assertThat(bf.getBeanDefinition("fooRepository").isAutowireCandidate(), is(true)); assertThat(bf.getBeanDefinition("fooRepository").isAutowireCandidate()).isTrue();
assertThat(bf.getBeanDefinition("other").isAutowireCandidate(), is(false)); assertThat(bf.getBeanDefinition("other").isAutowireCandidate()).isFalse();
assertThat(bf.getBeanDefinition("barService").isAutowireCandidate(), is(true)); assertThat(bf.getBeanDefinition("barService").isAutowireCandidate()).isTrue();
assertThat(bf.getBeanDefinition("fooController").isAutowireCandidate(), is(false)); assertThat(bf.getBeanDefinition("fooController").isAutowireCandidate()).isFalse();
assertThat(bf.getBeanDefinition("bizRepository").isAutowireCandidate(), is(true)); assertThat(bf.getBeanDefinition("bizRepository").isAutowireCandidate()).isTrue();
assertThat(bf.getBeanDefinition("bizService").isAutowireCandidate(), is(false)); assertThat(bf.getBeanDefinition("bizService").isAutowireCandidate()).isFalse();
assertThat(bf.getBeanDefinition("bazService").isAutowireCandidate(), is(true)); assertThat(bf.getBeanDefinition("bazService").isAutowireCandidate()).isTrue();
assertThat(bf.getBeanDefinition("random").isAutowireCandidate(), is(false)); assertThat(bf.getBeanDefinition("random").isAutowireCandidate()).isFalse();
assertThat(bf.getBeanDefinition("fooComponent").isAutowireCandidate(), is(false)); assertThat(bf.getBeanDefinition("fooComponent").isAutowireCandidate()).isFalse();
assertThat(bf.getBeanDefinition("fRepository").isAutowireCandidate(), is(false)); assertThat(bf.getBeanDefinition("fRepository").isAutowireCandidate()).isFalse();
assertThat(bf.getBeanDefinition("aComponent").isAutowireCandidate(), is(true)); assertThat(bf.getBeanDefinition("aComponent").isAutowireCandidate()).isTrue();
assertThat(bf.getBeanDefinition("someService").isAutowireCandidate(), is(false)); assertThat(bf.getBeanDefinition("someService").isAutowireCandidate()).isFalse();
} }
@Test @Test
@ -161,17 +160,17 @@ public class NestedBeansElementAttributeRecursionTests {
InitDestroyBean beanC = bf.getBean("beanC", InitDestroyBean.class); InitDestroyBean beanC = bf.getBean("beanC", InitDestroyBean.class);
InitDestroyBean beanD = bf.getBean("beanD", InitDestroyBean.class); InitDestroyBean beanD = bf.getBean("beanD", InitDestroyBean.class);
assertThat(beanA.initMethod1Called, is(true)); assertThat(beanA.initMethod1Called).isTrue();
assertThat(beanB.initMethod2Called, is(true)); assertThat(beanB.initMethod2Called).isTrue();
assertThat(beanC.initMethod3Called, is(true)); assertThat(beanC.initMethod3Called).isTrue();
assertThat(beanD.initMethod2Called, is(true)); assertThat(beanD.initMethod2Called).isTrue();
bf.destroySingletons(); bf.destroySingletons();
assertThat(beanA.destroyMethod1Called, is(true)); assertThat(beanA.destroyMethod1Called).isTrue();
assertThat(beanB.destroyMethod2Called, is(true)); assertThat(beanB.destroyMethod2Called).isTrue();
assertThat(beanC.destroyMethod3Called, is(true)); assertThat(beanC.destroyMethod3Called).isTrue();
assertThat(beanD.destroyMethod2Called, is(true)); assertThat(beanD.destroyMethod2Called).isTrue();
} }
} }

View File

@ -24,8 +24,8 @@ import org.springframework.core.env.StandardEnvironment;
import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource; import org.springframework.core.io.Resource;
import static org.hamcrest.CoreMatchers.instanceOf; import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.MatcherAssert.assertThat;
/** /**
* Tests for new nested beans element support in Spring XML * Tests for new nested beans element support in Spring XML
@ -42,7 +42,7 @@ public class NestedBeansElementTests {
new XmlBeanDefinitionReader(bf).loadBeanDefinitions(XML); new XmlBeanDefinitionReader(bf).loadBeanDefinitions(XML);
Object foo = bf.getBean("foo"); Object foo = bf.getBean("foo");
assertThat(foo, instanceOf(String.class)); assertThat(foo).isInstanceOf(String.class);
} }
@Test @Test
@ -58,7 +58,7 @@ public class NestedBeansElementTests {
bf.getBean("devOnlyBean"); // should not throw NSBDE bf.getBean("devOnlyBean"); // should not throw NSBDE
Object foo = bf.getBean("foo"); Object foo = bf.getBean("foo");
assertThat(foo, instanceOf(Integer.class)); assertThat(foo).isInstanceOf(Integer.class);
bf.getBean("devOnlyBean"); bf.getBean("devOnlyBean");
} }

View File

@ -16,9 +16,7 @@
package org.springframework.beans.factory.xml; package org.springframework.beans.factory.xml;
import org.hamcrest.Description; import org.assertj.core.api.Condition;
import org.hamcrest.Matcher;
import org.hamcrest.TypeSafeMatcher;
import org.junit.Test; import org.junit.Test;
import org.springframework.beans.factory.support.BeanDefinitionRegistry; import org.springframework.beans.factory.support.BeanDefinitionRegistry;
@ -27,9 +25,8 @@ import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.StandardEnvironment; import org.springframework.core.env.StandardEnvironment;
import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.ClassPathResource;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.hamcrest.CoreMatchers.not;
import static org.hamcrest.MatcherAssert.assertThat;
/** /**
* Tests various combinations of profile declarations against various profile * Tests various combinations of profile declarations against various profile
@ -71,51 +68,51 @@ public class ProfileXmlBeanDefinitionTests {
@Test @Test
public void testProfilePermutations() { public void testProfilePermutations() {
assertThat(beanFactoryFor(PROD_ELIGIBLE_XML, NONE_ACTIVE), not(containsTargetBean())); assertThat(beanFactoryFor(PROD_ELIGIBLE_XML, NONE_ACTIVE)).isNot(containingTarget());
assertThat(beanFactoryFor(PROD_ELIGIBLE_XML, DEV_ACTIVE), not(containsTargetBean())); assertThat(beanFactoryFor(PROD_ELIGIBLE_XML, DEV_ACTIVE)).isNot(containingTarget());
assertThat(beanFactoryFor(PROD_ELIGIBLE_XML, PROD_ACTIVE), containsTargetBean()); assertThat(beanFactoryFor(PROD_ELIGIBLE_XML, PROD_ACTIVE)).is(containingTarget());
assertThat(beanFactoryFor(PROD_ELIGIBLE_XML, MULTI_ACTIVE), containsTargetBean()); assertThat(beanFactoryFor(PROD_ELIGIBLE_XML, MULTI_ACTIVE)).is(containingTarget());
assertThat(beanFactoryFor(DEV_ELIGIBLE_XML, NONE_ACTIVE), not(containsTargetBean())); assertThat(beanFactoryFor(DEV_ELIGIBLE_XML, NONE_ACTIVE)).isNot(containingTarget());
assertThat(beanFactoryFor(DEV_ELIGIBLE_XML, DEV_ACTIVE), containsTargetBean()); assertThat(beanFactoryFor(DEV_ELIGIBLE_XML, DEV_ACTIVE)).is(containingTarget());
assertThat(beanFactoryFor(DEV_ELIGIBLE_XML, PROD_ACTIVE), not(containsTargetBean())); assertThat(beanFactoryFor(DEV_ELIGIBLE_XML, PROD_ACTIVE)).isNot(containingTarget());
assertThat(beanFactoryFor(DEV_ELIGIBLE_XML, MULTI_ACTIVE), containsTargetBean()); assertThat(beanFactoryFor(DEV_ELIGIBLE_XML, MULTI_ACTIVE)).is(containingTarget());
assertThat(beanFactoryFor(NOT_DEV_ELIGIBLE_XML, NONE_ACTIVE), containsTargetBean()); assertThat(beanFactoryFor(NOT_DEV_ELIGIBLE_XML, NONE_ACTIVE)).is(containingTarget());
assertThat(beanFactoryFor(NOT_DEV_ELIGIBLE_XML, DEV_ACTIVE), not(containsTargetBean())); assertThat(beanFactoryFor(NOT_DEV_ELIGIBLE_XML, DEV_ACTIVE)).isNot(containingTarget());
assertThat(beanFactoryFor(NOT_DEV_ELIGIBLE_XML, PROD_ACTIVE), containsTargetBean()); assertThat(beanFactoryFor(NOT_DEV_ELIGIBLE_XML, PROD_ACTIVE)).is(containingTarget());
assertThat(beanFactoryFor(NOT_DEV_ELIGIBLE_XML, MULTI_ACTIVE), not(containsTargetBean())); assertThat(beanFactoryFor(NOT_DEV_ELIGIBLE_XML, MULTI_ACTIVE)).isNot(containingTarget());
assertThat(beanFactoryFor(ALL_ELIGIBLE_XML, NONE_ACTIVE), containsTargetBean()); assertThat(beanFactoryFor(ALL_ELIGIBLE_XML, NONE_ACTIVE)).is(containingTarget());
assertThat(beanFactoryFor(ALL_ELIGIBLE_XML, DEV_ACTIVE), containsTargetBean()); assertThat(beanFactoryFor(ALL_ELIGIBLE_XML, DEV_ACTIVE)).is(containingTarget());
assertThat(beanFactoryFor(ALL_ELIGIBLE_XML, PROD_ACTIVE), containsTargetBean()); assertThat(beanFactoryFor(ALL_ELIGIBLE_XML, PROD_ACTIVE)).is(containingTarget());
assertThat(beanFactoryFor(ALL_ELIGIBLE_XML, MULTI_ACTIVE), containsTargetBean()); assertThat(beanFactoryFor(ALL_ELIGIBLE_XML, MULTI_ACTIVE)).is(containingTarget());
assertThat(beanFactoryFor(MULTI_ELIGIBLE_XML, NONE_ACTIVE), not(containsTargetBean())); assertThat(beanFactoryFor(MULTI_ELIGIBLE_XML, NONE_ACTIVE)).isNot(containingTarget());
assertThat(beanFactoryFor(MULTI_ELIGIBLE_XML, UNKNOWN_ACTIVE), not(containsTargetBean())); assertThat(beanFactoryFor(MULTI_ELIGIBLE_XML, UNKNOWN_ACTIVE)).isNot(containingTarget());
assertThat(beanFactoryFor(MULTI_ELIGIBLE_XML, DEV_ACTIVE), containsTargetBean()); assertThat(beanFactoryFor(MULTI_ELIGIBLE_XML, DEV_ACTIVE)).is(containingTarget());
assertThat(beanFactoryFor(MULTI_ELIGIBLE_XML, PROD_ACTIVE), containsTargetBean()); assertThat(beanFactoryFor(MULTI_ELIGIBLE_XML, PROD_ACTIVE)).is(containingTarget());
assertThat(beanFactoryFor(MULTI_ELIGIBLE_XML, MULTI_ACTIVE), containsTargetBean()); assertThat(beanFactoryFor(MULTI_ELIGIBLE_XML, MULTI_ACTIVE)).is(containingTarget());
assertThat(beanFactoryFor(MULTI_NEGATED_XML, NONE_ACTIVE), containsTargetBean()); assertThat(beanFactoryFor(MULTI_NEGATED_XML, NONE_ACTIVE)).is(containingTarget());
assertThat(beanFactoryFor(MULTI_NEGATED_XML, UNKNOWN_ACTIVE), containsTargetBean()); assertThat(beanFactoryFor(MULTI_NEGATED_XML, UNKNOWN_ACTIVE)).is(containingTarget());
assertThat(beanFactoryFor(MULTI_NEGATED_XML, DEV_ACTIVE), containsTargetBean()); assertThat(beanFactoryFor(MULTI_NEGATED_XML, DEV_ACTIVE)).is(containingTarget());
assertThat(beanFactoryFor(MULTI_NEGATED_XML, PROD_ACTIVE), containsTargetBean()); assertThat(beanFactoryFor(MULTI_NEGATED_XML, PROD_ACTIVE)).is(containingTarget());
assertThat(beanFactoryFor(MULTI_NEGATED_XML, MULTI_ACTIVE), not(containsTargetBean())); assertThat(beanFactoryFor(MULTI_NEGATED_XML, MULTI_ACTIVE)).isNot(containingTarget());
assertThat(beanFactoryFor(MULTI_NOT_DEV_ELIGIBLE_XML, NONE_ACTIVE), containsTargetBean()); assertThat(beanFactoryFor(MULTI_NOT_DEV_ELIGIBLE_XML, NONE_ACTIVE)).is(containingTarget());
assertThat(beanFactoryFor(MULTI_NOT_DEV_ELIGIBLE_XML, UNKNOWN_ACTIVE), containsTargetBean()); assertThat(beanFactoryFor(MULTI_NOT_DEV_ELIGIBLE_XML, UNKNOWN_ACTIVE)).is(containingTarget());
assertThat(beanFactoryFor(MULTI_NOT_DEV_ELIGIBLE_XML, DEV_ACTIVE), not(containsTargetBean())); assertThat(beanFactoryFor(MULTI_NOT_DEV_ELIGIBLE_XML, DEV_ACTIVE)).isNot(containingTarget());
assertThat(beanFactoryFor(MULTI_NOT_DEV_ELIGIBLE_XML, PROD_ACTIVE), containsTargetBean()); assertThat(beanFactoryFor(MULTI_NOT_DEV_ELIGIBLE_XML, PROD_ACTIVE)).is(containingTarget());
assertThat(beanFactoryFor(MULTI_NOT_DEV_ELIGIBLE_XML, MULTI_ACTIVE), containsTargetBean()); assertThat(beanFactoryFor(MULTI_NOT_DEV_ELIGIBLE_XML, MULTI_ACTIVE)).is(containingTarget());
assertThat(beanFactoryFor(MULTI_ELIGIBLE_SPACE_DELIMITED_XML, NONE_ACTIVE), not(containsTargetBean())); assertThat(beanFactoryFor(MULTI_ELIGIBLE_SPACE_DELIMITED_XML, NONE_ACTIVE)).isNot(containingTarget());
assertThat(beanFactoryFor(MULTI_ELIGIBLE_SPACE_DELIMITED_XML, UNKNOWN_ACTIVE), not(containsTargetBean())); assertThat(beanFactoryFor(MULTI_ELIGIBLE_SPACE_DELIMITED_XML, UNKNOWN_ACTIVE)).isNot(containingTarget());
assertThat(beanFactoryFor(MULTI_ELIGIBLE_SPACE_DELIMITED_XML, DEV_ACTIVE), containsTargetBean()); assertThat(beanFactoryFor(MULTI_ELIGIBLE_SPACE_DELIMITED_XML, DEV_ACTIVE)).is(containingTarget());
assertThat(beanFactoryFor(MULTI_ELIGIBLE_SPACE_DELIMITED_XML, PROD_ACTIVE), containsTargetBean()); assertThat(beanFactoryFor(MULTI_ELIGIBLE_SPACE_DELIMITED_XML, PROD_ACTIVE)).is(containingTarget());
assertThat(beanFactoryFor(MULTI_ELIGIBLE_SPACE_DELIMITED_XML, MULTI_ACTIVE), containsTargetBean()); assertThat(beanFactoryFor(MULTI_ELIGIBLE_SPACE_DELIMITED_XML, MULTI_ACTIVE)).is(containingTarget());
assertThat(beanFactoryFor(UNKNOWN_ELIGIBLE_XML, MULTI_ACTIVE), not(containsTargetBean())); assertThat(beanFactoryFor(UNKNOWN_ELIGIBLE_XML, MULTI_ACTIVE)).isNot(containingTarget());
} }
@Test @Test
@ -128,7 +125,7 @@ public class ProfileXmlBeanDefinitionTests {
reader.setEnvironment(env); reader.setEnvironment(env);
reader.loadBeanDefinitions(new ClassPathResource(DEFAULT_ELIGIBLE_XML, getClass())); reader.loadBeanDefinitions(new ClassPathResource(DEFAULT_ELIGIBLE_XML, getClass()));
assertThat(beanFactory, not(containsTargetBean())); assertThat(beanFactory).isNot(containingTarget());
} }
{ {
DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory(); DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory();
@ -138,14 +135,14 @@ public class ProfileXmlBeanDefinitionTests {
reader.setEnvironment(env); reader.setEnvironment(env);
reader.loadBeanDefinitions(new ClassPathResource(CUSTOM_DEFAULT_ELIGIBLE_XML, getClass())); reader.loadBeanDefinitions(new ClassPathResource(CUSTOM_DEFAULT_ELIGIBLE_XML, getClass()));
assertThat(beanFactory, containsTargetBean()); assertThat(beanFactory).is(containingTarget());
} }
} }
@Test @Test
public void testDefaultAndNonDefaultProfile() { public void testDefaultAndNonDefaultProfile() {
assertThat(beanFactoryFor(DEFAULT_ELIGIBLE_XML, NONE_ACTIVE), containsTargetBean()); assertThat(beanFactoryFor(DEFAULT_ELIGIBLE_XML, NONE_ACTIVE)).is(containingTarget());
assertThat(beanFactoryFor(DEFAULT_ELIGIBLE_XML, "other"), not(containsTargetBean())); assertThat(beanFactoryFor(DEFAULT_ELIGIBLE_XML, "other")).isNot(containingTarget());
{ {
DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory(); DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory();
@ -155,7 +152,7 @@ public class ProfileXmlBeanDefinitionTests {
env.setDefaultProfiles("default"); env.setDefaultProfiles("default");
reader.setEnvironment(env); reader.setEnvironment(env);
reader.loadBeanDefinitions(new ClassPathResource(DEFAULT_AND_DEV_ELIGIBLE_XML, getClass())); reader.loadBeanDefinitions(new ClassPathResource(DEFAULT_AND_DEV_ELIGIBLE_XML, getClass()));
assertThat(beanFactory, containsTargetBean()); assertThat(beanFactory).is(containingTarget());
} }
{ {
DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory(); DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory();
@ -165,7 +162,7 @@ public class ProfileXmlBeanDefinitionTests {
env.setDefaultProfiles("default"); env.setDefaultProfiles("default");
reader.setEnvironment(env); reader.setEnvironment(env);
reader.loadBeanDefinitions(new ClassPathResource(DEFAULT_AND_DEV_ELIGIBLE_XML, getClass())); reader.loadBeanDefinitions(new ClassPathResource(DEFAULT_AND_DEV_ELIGIBLE_XML, getClass()));
assertThat(beanFactory, containsTargetBean()); assertThat(beanFactory).is(containingTarget());
} }
{ {
DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory(); DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory();
@ -175,7 +172,7 @@ public class ProfileXmlBeanDefinitionTests {
//env.setDefaultProfiles("default"); //env.setDefaultProfiles("default");
reader.setEnvironment(env); reader.setEnvironment(env);
reader.loadBeanDefinitions(new ClassPathResource(DEFAULT_AND_DEV_ELIGIBLE_XML, getClass())); reader.loadBeanDefinitions(new ClassPathResource(DEFAULT_AND_DEV_ELIGIBLE_XML, getClass()));
assertThat(beanFactory, containsTargetBean()); assertThat(beanFactory).is(containingTarget());
} }
} }
@ -190,25 +187,8 @@ public class ProfileXmlBeanDefinitionTests {
return beanFactory; return beanFactory;
} }
private Condition<BeanDefinitionRegistry> containingTarget() {
private static Matcher<BeanDefinitionRegistry> containsBeanDefinition(final String beanName) { return new Condition<>(registry -> registry.containsBeanDefinition(TARGET_BEAN), "contains target");
return new TypeSafeMatcher<BeanDefinitionRegistry>() {
@Override
public void describeTo(Description desc) {
desc.appendText("a BeanDefinitionRegistry containing bean named ")
.appendValue(beanName);
}
@Override
public boolean matchesSafely(BeanDefinitionRegistry beanFactory) {
return beanFactory.containsBeanDefinition(beanName);
}
};
} }
private static Matcher<BeanDefinitionRegistry> containsTargetBean() {
return containsBeanDefinition(TARGET_BEAN);
}
} }

View File

@ -60,10 +60,10 @@ import org.springframework.context.index.test.TestCompiler;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import org.springframework.util.ClassUtils; import org.springframework.util.ClassUtils;
import static org.hamcrest.MatcherAssert.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.sameInstance;
import static org.springframework.context.index.processor.Metadata.hasComponent;
/** /**
* Tests for {@link CandidateComponentsIndexer}. * Tests for {@link CandidateComponentsIndexer}.
@ -87,13 +87,13 @@ public class CandidateComponentsIndexerTests {
@Test @Test
public void noCandidate() { public void noCandidate() {
CandidateComponentsMetadata metadata = compile(SampleNone.class); CandidateComponentsMetadata metadata = compile(SampleNone.class);
assertThat(metadata.getItems(), hasSize(0)); assertThat(metadata.getItems()).hasSize(0);
} }
@Test @Test
public void noAnnotation() { public void noAnnotation() {
CandidateComponentsMetadata metadata = compile(CandidateComponentsIndexerTests.class); CandidateComponentsMetadata metadata = compile(CandidateComponentsIndexerTests.class);
assertThat(metadata.getItems(), hasSize(0)); assertThat(metadata.getItems()).hasSize(0);
} }
@Test @Test
@ -171,7 +171,7 @@ public class CandidateComponentsIndexerTests {
public void packageInfo() { public void packageInfo() {
CandidateComponentsMetadata metadata = compile( CandidateComponentsMetadata metadata = compile(
"org/springframework/context/index/sample/jpa/package-info"); "org/springframework/context/index/sample/jpa/package-info");
assertThat(metadata, hasComponent( assertThat(metadata).has(Metadata.of(
"org.springframework.context.index.sample.jpa", "package-info")); "org.springframework.context.index.sample.jpa", "package-info"));
} }
@ -211,33 +211,33 @@ public class CandidateComponentsIndexerTests {
// Validate nested type structure // Validate nested type structure
String nestedType = "org.springframework.context.index.sample.SampleEmbedded.Another$AnotherPublicCandidate"; String nestedType = "org.springframework.context.index.sample.SampleEmbedded.Another$AnotherPublicCandidate";
Class<?> type = ClassUtils.forName(nestedType, getClass().getClassLoader()); Class<?> type = ClassUtils.forName(nestedType, getClass().getClassLoader());
assertThat(type, sameInstance(SampleEmbedded.Another.AnotherPublicCandidate.class)); assertThat(type).isSameAs(SampleEmbedded.Another.AnotherPublicCandidate.class);
CandidateComponentsMetadata metadata = compile(SampleEmbedded.class); CandidateComponentsMetadata metadata = compile(SampleEmbedded.class);
assertThat(metadata, hasComponent( assertThat(metadata).has(Metadata.of(
SampleEmbedded.PublicCandidate.class, Component.class)); SampleEmbedded.PublicCandidate.class, Component.class));
assertThat(metadata, hasComponent(nestedType, Component.class.getName())); assertThat(metadata).has(Metadata.of(nestedType, Component.class.getName()));
assertThat(metadata.getItems(), hasSize(2)); assertThat(metadata.getItems()).hasSize(2);
} }
@Test @Test
public void embeddedNonStaticCandidateAreIgnored() { public void embeddedNonStaticCandidateAreIgnored() {
CandidateComponentsMetadata metadata = compile(SampleNonStaticEmbedded.class); CandidateComponentsMetadata metadata = compile(SampleNonStaticEmbedded.class);
assertThat(metadata.getItems(), hasSize(0)); assertThat(metadata.getItems()).hasSize(0);
} }
private void testComponent(Class<?>... classes) { private void testComponent(Class<?>... classes) {
CandidateComponentsMetadata metadata = compile(classes); CandidateComponentsMetadata metadata = compile(classes);
for (Class<?> c : classes) { for (Class<?> c : classes) {
assertThat(metadata, hasComponent(c, Component.class)); assertThat(metadata).has(Metadata.of(c, Component.class));
} }
assertThat(metadata.getItems(), hasSize(classes.length)); assertThat(metadata.getItems()).hasSize(classes.length);
} }
private void testSingleComponent(Class<?> target, Class<?>... stereotypes) { private void testSingleComponent(Class<?> target, Class<?>... stereotypes) {
CandidateComponentsMetadata metadata = compile(target); CandidateComponentsMetadata metadata = compile(target);
assertThat(metadata, hasComponent(target, stereotypes)); assertThat(metadata).has(Metadata.of(target, stereotypes));
assertThat(metadata.getItems(), hasSize(1)); assertThat(metadata.getItems()).hasSize(1);
} }
private CandidateComponentsMetadata compile(Class<?>... types) { private CandidateComponentsMetadata compile(Class<?>... types) {

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2018 the original author or authors. * Copyright 2002-2019 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -20,84 +20,32 @@ import java.util.Arrays;
import java.util.List; import java.util.List;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import org.hamcrest.BaseMatcher; import org.assertj.core.api.Condition;
import org.hamcrest.Description;
/** /**
* Hamcrest {@link org.hamcrest.Matcher Matcher} to help test {@link CandidateComponentsMetadata}. * AssertJ {@link Condition} to help test {@link CandidateComponentsMetadata}.
* *
* @author Stephane Nicoll * @author Stephane Nicoll
*/ */
public class Metadata { class Metadata {
public static ItemMetadataMatcher hasComponent(Class<?> type, Class<?>... stereotypes) { public static Condition<CandidateComponentsMetadata> of(Class<?> type, Class<?>... stereotypes) {
return new ItemMetadataMatcher(type.getName(), stereotypes); return of(type.getName(), Arrays.stream(stereotypes).map(Class::getName).collect(Collectors.toList()));
} }
public static ItemMetadataMatcher hasComponent(String type, String... stereotypes) { public static Condition<CandidateComponentsMetadata> of(String type, String... stereotypes) {
return new ItemMetadataMatcher(type, stereotypes); return of(type, Arrays.asList(stereotypes));
} }
public static Condition<CandidateComponentsMetadata> of(String type,
private static class ItemMetadataMatcher extends BaseMatcher<CandidateComponentsMetadata> { List<String> stereotypes) {
return new Condition<>(metadata -> {
private final String type; ItemMetadata itemMetadata = metadata.getItems().stream()
.filter(item -> item.getType().equals(type))
private final List<String> stereotypes; .findFirst().orElse(null);
return itemMetadata != null && itemMetadata.getStereotypes().size() == stereotypes.size()
private ItemMetadataMatcher(String type, List<String> stereotypes) { && itemMetadata.getStereotypes().containsAll(stereotypes);
this.type = type; }, "Candidates with type %s and stereotypes %s", type, stereotypes);
this.stereotypes = stereotypes;
}
public ItemMetadataMatcher(String type, String... stereotypes) {
this(type, Arrays.asList(stereotypes));
}
public ItemMetadataMatcher(String type, Class<?>... stereotypes) {
this(type, Arrays.stream(stereotypes)
.map(Class::getName).collect(Collectors.toList()));
}
@Override
public boolean matches(Object value) {
if (!(value instanceof CandidateComponentsMetadata)) {
return false;
}
ItemMetadata itemMetadata = getFirstItemWithType((CandidateComponentsMetadata) value, this.type);
if (itemMetadata == null) {
return false;
}
if (this.type != null && !this.type.equals(itemMetadata.getType())) {
return false;
}
if (this.stereotypes != null) {
for (String stereotype : this.stereotypes) {
if (!itemMetadata.getStereotypes().contains(stereotype)) {
return false;
}
}
if (this.stereotypes.size() != itemMetadata.getStereotypes().size()) {
return false;
}
}
return true;
}
private ItemMetadata getFirstItemWithType(CandidateComponentsMetadata metadata, String type) {
for (ItemMetadata item : metadata.getItems()) {
if (item.getType().equals(type)) {
return item;
}
}
return null;
}
@Override
public void describeTo(Description description) {
description.appendText("Candidates with type ").appendValue(this.type);
description.appendText(" and stereotypes ").appendValue(this.stereotypes);
}
} }
} }

View File

@ -24,9 +24,9 @@ import java.util.HashSet;
import org.junit.Test; import org.junit.Test;
import static org.hamcrest.MatcherAssert.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.hasSize;
import static org.springframework.context.index.processor.Metadata.hasComponent;
/** /**
* Tests for {@link PropertiesMarshaller}. * Tests for {@link PropertiesMarshaller}.
@ -45,9 +45,9 @@ public class PropertiesMarshallerTests {
PropertiesMarshaller.write(metadata, outputStream); PropertiesMarshaller.write(metadata, outputStream);
CandidateComponentsMetadata readMetadata = PropertiesMarshaller.read( CandidateComponentsMetadata readMetadata = PropertiesMarshaller.read(
new ByteArrayInputStream(outputStream.toByteArray())); new ByteArrayInputStream(outputStream.toByteArray()));
assertThat(readMetadata, hasComponent("com.foo", "first", "second")); assertThat(readMetadata).has(Metadata.of("com.foo", "first", "second"));
assertThat(readMetadata, hasComponent("com.bar", "first")); assertThat(readMetadata).has(Metadata.of("com.bar", "first"));
assertThat(readMetadata.getItems(), hasSize(2)); assertThat(readMetadata.getItems()).hasSize(2);
} }
private static ItemMetadata createItem(String type, String... stereotypes) { private static ItemMetadata createItem(String type, String... stereotypes) {

View File

@ -23,10 +23,7 @@ import org.junit.rules.TestName;
import org.springframework.cache.Cache; import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager; import org.springframework.cache.CacheManager;
import static org.hamcrest.MatcherAssert.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.instanceOf;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.nullValue;
import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertTrue;
@ -71,7 +68,7 @@ public abstract class AbstractTransactionSupportingCacheManagerTests<T extends C
@Test @Test
public void getOnExistingCache() { public void getOnExistingCache() {
assertThat(getCacheManager(false).getCache(CACHE_NAME), is(instanceOf(getCacheType()))); assertThat(getCacheManager(false).getCache(CACHE_NAME)).isInstanceOf(getCacheType());
} }
@Test @Test
@ -81,7 +78,7 @@ public abstract class AbstractTransactionSupportingCacheManagerTests<T extends C
addNativeCache(cacheName); addNativeCache(cacheName);
assertFalse(cacheManager.getCacheNames().contains(cacheName)); assertFalse(cacheManager.getCacheNames().contains(cacheName));
try { try {
assertThat(cacheManager.getCache(cacheName), is(instanceOf(getCacheType()))); assertThat(cacheManager.getCache(cacheName)).isInstanceOf(getCacheType());
assertTrue(cacheManager.getCacheNames().contains(cacheName)); assertTrue(cacheManager.getCacheNames().contains(cacheName));
} }
finally { finally {
@ -94,13 +91,13 @@ public abstract class AbstractTransactionSupportingCacheManagerTests<T extends C
T cacheManager = getCacheManager(false); T cacheManager = getCacheManager(false);
String cacheName = name.getMethodName(); String cacheName = name.getMethodName();
assertFalse(cacheManager.getCacheNames().contains(cacheName)); assertFalse(cacheManager.getCacheNames().contains(cacheName));
assertThat(cacheManager.getCache(cacheName), nullValue()); assertThat(cacheManager.getCache(cacheName)).isNull();
} }
@Test @Test
public void getTransactionalOnExistingCache() { public void getTransactionalOnExistingCache() {
assertThat(getCacheManager(true).getCache(CACHE_NAME), assertThat(getCacheManager(true).getCache(CACHE_NAME))
is(instanceOf(TransactionAwareCacheDecorator.class))); .isInstanceOf(TransactionAwareCacheDecorator.class);
} }
@Test @Test
@ -110,8 +107,8 @@ public abstract class AbstractTransactionSupportingCacheManagerTests<T extends C
assertFalse(cacheManager.getCacheNames().contains(cacheName)); assertFalse(cacheManager.getCacheNames().contains(cacheName));
addNativeCache(cacheName); addNativeCache(cacheName);
try { try {
assertThat(cacheManager.getCache(cacheName), assertThat(cacheManager.getCache(cacheName))
is(instanceOf(TransactionAwareCacheDecorator.class))); .isInstanceOf(TransactionAwareCacheDecorator.class);
assertTrue(cacheManager.getCacheNames().contains(cacheName)); assertTrue(cacheManager.getCacheNames().contains(cacheName));
} }
finally { finally {

View File

@ -57,9 +57,7 @@ import org.springframework.validation.beanvalidation.SpringValidatorAdapter;
import static java.lang.annotation.ElementType.ANNOTATION_TYPE; import static java.lang.annotation.ElementType.ANNOTATION_TYPE;
import static java.lang.annotation.ElementType.TYPE; import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.RetentionPolicy.RUNTIME; import static java.lang.annotation.RetentionPolicy.RUNTIME;
import static org.hamcrest.MatcherAssert.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.core.Is.is;
import static org.hamcrest.core.StringContains.containsString;
import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull; import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame; import static org.junit.Assert.assertSame;
@ -102,13 +100,13 @@ public class SpringValidatorAdapterTests {
BeanPropertyBindingResult errors = new BeanPropertyBindingResult(testBean, "testBean"); BeanPropertyBindingResult errors = new BeanPropertyBindingResult(testBean, "testBean");
validatorAdapter.validate(testBean, errors); validatorAdapter.validate(testBean, errors);
assertThat(errors.getFieldErrorCount("password"), is(1)); assertThat(errors.getFieldErrorCount("password")).isEqualTo(1);
assertThat(errors.getFieldValue("password"), is("pass")); assertThat(errors.getFieldValue("password")).isEqualTo("pass");
FieldError error = errors.getFieldError("password"); FieldError error = errors.getFieldError("password");
assertNotNull(error); assertNotNull(error);
assertThat(messageSource.getMessage(error, Locale.ENGLISH), is("Size of Password is must be between 8 and 128")); assertThat(messageSource.getMessage(error, Locale.ENGLISH)).isEqualTo("Size of Password is must be between 8 and 128");
assertTrue(error.contains(ConstraintViolation.class)); assertTrue(error.contains(ConstraintViolation.class));
assertThat(error.unwrap(ConstraintViolation.class).getPropertyPath().toString(), is("password")); assertThat(error.unwrap(ConstraintViolation.class).getPropertyPath().toString()).isEqualTo("password");
} }
@Test // SPR-13406 @Test // SPR-13406
@ -120,13 +118,13 @@ public class SpringValidatorAdapterTests {
BeanPropertyBindingResult errors = new BeanPropertyBindingResult(testBean, "testBean"); BeanPropertyBindingResult errors = new BeanPropertyBindingResult(testBean, "testBean");
validatorAdapter.validate(testBean, errors); validatorAdapter.validate(testBean, errors);
assertThat(errors.getFieldErrorCount("password"), is(1)); assertThat(errors.getFieldErrorCount("password")).isEqualTo(1);
assertThat(errors.getFieldValue("password"), is("password")); assertThat(errors.getFieldValue("password")).isEqualTo("password");
FieldError error = errors.getFieldError("password"); FieldError error = errors.getFieldError("password");
assertNotNull(error); assertNotNull(error);
assertThat(messageSource.getMessage(error, Locale.ENGLISH), is("Password must be same value as Password(Confirm)")); assertThat(messageSource.getMessage(error, Locale.ENGLISH)).isEqualTo("Password must be same value as Password(Confirm)");
assertTrue(error.contains(ConstraintViolation.class)); assertTrue(error.contains(ConstraintViolation.class));
assertThat(error.unwrap(ConstraintViolation.class).getPropertyPath().toString(), is("password")); assertThat(error.unwrap(ConstraintViolation.class).getPropertyPath().toString()).isEqualTo("password");
} }
@Test // SPR-13406 @Test // SPR-13406
@ -138,19 +136,19 @@ public class SpringValidatorAdapterTests {
BeanPropertyBindingResult errors = new BeanPropertyBindingResult(testBean, "testBean"); BeanPropertyBindingResult errors = new BeanPropertyBindingResult(testBean, "testBean");
validatorAdapter.validate(testBean, errors); validatorAdapter.validate(testBean, errors);
assertThat(errors.getFieldErrorCount("email"), is(1)); assertThat(errors.getFieldErrorCount("email")).isEqualTo(1);
assertThat(errors.getFieldValue("email"), is("test@example.com")); assertThat(errors.getFieldValue("email")).isEqualTo("test@example.com");
assertThat(errors.getFieldErrorCount("confirmEmail"), is(1)); assertThat(errors.getFieldErrorCount("confirmEmail")).isEqualTo(1);
FieldError error1 = errors.getFieldError("email"); FieldError error1 = errors.getFieldError("email");
FieldError error2 = errors.getFieldError("confirmEmail"); FieldError error2 = errors.getFieldError("confirmEmail");
assertNotNull(error1); assertNotNull(error1);
assertNotNull(error2); assertNotNull(error2);
assertThat(messageSource.getMessage(error1, Locale.ENGLISH), is("email must be same value as confirmEmail")); assertThat(messageSource.getMessage(error1, Locale.ENGLISH)).isEqualTo("email must be same value as confirmEmail");
assertThat(messageSource.getMessage(error2, Locale.ENGLISH), is("Email required")); assertThat(messageSource.getMessage(error2, Locale.ENGLISH)).isEqualTo("Email required");
assertTrue(error1.contains(ConstraintViolation.class)); assertTrue(error1.contains(ConstraintViolation.class));
assertThat(error1.unwrap(ConstraintViolation.class).getPropertyPath().toString(), is("email")); assertThat(error1.unwrap(ConstraintViolation.class).getPropertyPath().toString()).isEqualTo("email");
assertTrue(error2.contains(ConstraintViolation.class)); assertTrue(error2.contains(ConstraintViolation.class));
assertThat(error2.unwrap(ConstraintViolation.class).getPropertyPath().toString(), is("confirmEmail")); assertThat(error2.unwrap(ConstraintViolation.class).getPropertyPath().toString()).isEqualTo("confirmEmail");
} }
@Test // SPR-15123 @Test // SPR-15123
@ -164,19 +162,19 @@ public class SpringValidatorAdapterTests {
BeanPropertyBindingResult errors = new BeanPropertyBindingResult(testBean, "testBean"); BeanPropertyBindingResult errors = new BeanPropertyBindingResult(testBean, "testBean");
validatorAdapter.validate(testBean, errors); validatorAdapter.validate(testBean, errors);
assertThat(errors.getFieldErrorCount("email"), is(1)); assertThat(errors.getFieldErrorCount("email")).isEqualTo(1);
assertThat(errors.getFieldValue("email"), is("test@example.com")); assertThat(errors.getFieldValue("email")).isEqualTo("test@example.com");
assertThat(errors.getFieldErrorCount("confirmEmail"), is(1)); assertThat(errors.getFieldErrorCount("confirmEmail")).isEqualTo(1);
FieldError error1 = errors.getFieldError("email"); FieldError error1 = errors.getFieldError("email");
FieldError error2 = errors.getFieldError("confirmEmail"); FieldError error2 = errors.getFieldError("confirmEmail");
assertNotNull(error1); assertNotNull(error1);
assertNotNull(error2); assertNotNull(error2);
assertThat(messageSource.getMessage(error1, Locale.ENGLISH), is("email must be same value as confirmEmail")); assertThat(messageSource.getMessage(error1, Locale.ENGLISH)).isEqualTo("email must be same value as confirmEmail");
assertThat(messageSource.getMessage(error2, Locale.ENGLISH), is("Email required")); assertThat(messageSource.getMessage(error2, Locale.ENGLISH)).isEqualTo("Email required");
assertTrue(error1.contains(ConstraintViolation.class)); assertTrue(error1.contains(ConstraintViolation.class));
assertThat(error1.unwrap(ConstraintViolation.class).getPropertyPath().toString(), is("email")); assertThat(error1.unwrap(ConstraintViolation.class).getPropertyPath().toString()).isEqualTo("email");
assertTrue(error2.contains(ConstraintViolation.class)); assertTrue(error2.contains(ConstraintViolation.class));
assertThat(error2.unwrap(ConstraintViolation.class).getPropertyPath().toString(), is("confirmEmail")); assertThat(error2.unwrap(ConstraintViolation.class).getPropertyPath().toString()).isEqualTo("confirmEmail");
} }
@Test @Test
@ -188,13 +186,13 @@ public class SpringValidatorAdapterTests {
BeanPropertyBindingResult errors = new BeanPropertyBindingResult(testBean, "testBean"); BeanPropertyBindingResult errors = new BeanPropertyBindingResult(testBean, "testBean");
validatorAdapter.validate(testBean, errors); validatorAdapter.validate(testBean, errors);
assertThat(errors.getFieldErrorCount("email"), is(1)); assertThat(errors.getFieldErrorCount("email")).isEqualTo(1);
assertThat(errors.getFieldValue("email"), is("X")); assertThat(errors.getFieldValue("email")).isEqualTo("X");
FieldError error = errors.getFieldError("email"); FieldError error = errors.getFieldError("email");
assertNotNull(error); assertNotNull(error);
assertThat(messageSource.getMessage(error, Locale.ENGLISH), containsString("[\\w.'-]{1,}@[\\w.'-]{1,}")); assertThat(messageSource.getMessage(error, Locale.ENGLISH)).contains("[\\w.'-]{1,}@[\\w.'-]{1,}");
assertTrue(error.contains(ConstraintViolation.class)); assertTrue(error.contains(ConstraintViolation.class));
assertThat(error.unwrap(ConstraintViolation.class).getPropertyPath().toString(), is("email")); assertThat(error.unwrap(ConstraintViolation.class).getPropertyPath().toString()).isEqualTo("email");
} }
@Test // SPR-16177 @Test // SPR-16177
@ -243,7 +241,7 @@ public class SpringValidatorAdapterTests {
BeanPropertyBindingResult errors = new BeanPropertyBindingResult(bean, "bean"); BeanPropertyBindingResult errors = new BeanPropertyBindingResult(bean, "bean");
validatorAdapter.validate(bean, errors); validatorAdapter.validate(bean, errors);
assertThat(errors.getFieldErrorCount("property[4]"), is(1)); assertThat(errors.getFieldErrorCount("property[4]")).isEqualTo(1);
assertNull(errors.getFieldValue("property[4]")); assertNull(errors.getFieldValue("property[4]"));
} }
@ -258,7 +256,7 @@ public class SpringValidatorAdapterTests {
BeanPropertyBindingResult errors = new BeanPropertyBindingResult(bean, "bean"); BeanPropertyBindingResult errors = new BeanPropertyBindingResult(bean, "bean");
validatorAdapter.validate(bean, errors); validatorAdapter.validate(bean, errors);
assertThat(errors.getFieldErrorCount("property[no value can be]"), is(1)); assertThat(errors.getFieldErrorCount("property[no value can be]")).isEqualTo(1);
assertNull(errors.getFieldValue("property[no value can be]")); assertNull(errors.getFieldValue("property[no value can be]"));
} }

View File

@ -53,8 +53,6 @@ import org.springframework.validation.ObjectError;
import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean; import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.instanceOf;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull; import static org.junit.Assert.assertNull;
@ -140,8 +138,7 @@ public class ValidatorFactoryTests {
BeanPropertyBindingResult errors = new BeanPropertyBindingResult(person, "person"); BeanPropertyBindingResult errors = new BeanPropertyBindingResult(person, "person");
validator.validate(person, errors); validator.validate(person, errors);
assertEquals(1, errors.getErrorCount()); assertEquals(1, errors.getErrorCount());
assertThat("Field/Value type mismatch", errors.getFieldError("address").getRejectedValue(), assertThat(errors.getFieldError("address").getRejectedValue()).isInstanceOf(ValidAddress.class);
instanceOf(ValidAddress.class));
} }
@Test @Test

View File

@ -36,10 +36,9 @@ import org.springframework.tests.aop.interceptor.NopInterceptor;
import org.springframework.tests.sample.beans.ITestBean; import org.springframework.tests.sample.beans.ITestBean;
import org.springframework.tests.sample.beans.TestBean; import org.springframework.tests.sample.beans.TestBean;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.hamcrest.CoreMatchers.instanceOf;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertSame; import static org.junit.Assert.assertSame;
@ -294,7 +293,7 @@ public class CglibProxyTests extends AbstractAopProxyTests implements Serializab
as.addAdvice(new NopInterceptor()); as.addAdvice(new NopInterceptor());
cglib = new CglibAopProxy(as); cglib = new CglibAopProxy(as);
assertThat(cglib.getProxy(), instanceOf(ITestBean.class)); assertThat(cglib.getProxy()).isInstanceOf(ITestBean.class);
} }
@Test @Test

View File

@ -22,8 +22,8 @@ import org.springframework.aop.interceptor.DebugInterceptor;
import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext;
import static org.hamcrest.CoreMatchers.is; import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.MatcherAssert.assertThat;
/** /**
* Integration test for Objenesis proxy creation. * Integration test for Objenesis proxy creation.
@ -41,8 +41,8 @@ public class ObjenesisProxyTests {
bean.method(); bean.method();
DebugInterceptor interceptor = context.getBean(DebugInterceptor.class); DebugInterceptor interceptor = context.getBean(DebugInterceptor.class);
assertThat(interceptor.getCount(), is(1L)); assertThat(interceptor.getCount()).isEqualTo(1L);
assertThat(bean.getDependency().getValue(), is(1)); assertThat(bean.getDependency().getValue()).isEqualTo(1);
} }
} }

View File

@ -63,9 +63,6 @@ import org.springframework.util.SerializationTestUtils;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.assertThatIOException; import static org.assertj.core.api.Assertions.assertThatIOException;
import static org.hamcrest.CoreMatchers.instanceOf;
import static org.hamcrest.CoreMatchers.not;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertFalse;
@ -347,8 +344,8 @@ public class ProxyFactoryBeanTests {
*/ */
@Test @Test
public void testCanAddAndRemoveAspectInterfacesOnPrototype() { public void testCanAddAndRemoveAspectInterfacesOnPrototype() {
assertThat("Shouldn't implement TimeStamped before manipulation", assertThat(factory.getBean("test2")).as("Shouldn't implement TimeStamped before manipulation")
factory.getBean("test2"), not(instanceOf(TimeStamped.class))); .isNotInstanceOf(TimeStamped.class);
ProxyFactoryBean config = (ProxyFactoryBean) factory.getBean("&test2"); ProxyFactoryBean config = (ProxyFactoryBean) factory.getBean("&test2");
long time = 666L; long time = 666L;
@ -369,8 +366,8 @@ public class ProxyFactoryBeanTests {
// Check no change on existing object reference // Check no change on existing object reference
assertTrue(ts.getTimeStamp() == time); assertTrue(ts.getTimeStamp() == time);
assertThat("Should no longer implement TimeStamped", assertThat(factory.getBean("test2")).as("Should no longer implement TimeStamped")
factory.getBean("test2"), not(instanceOf(TimeStamped.class))); .isNotInstanceOf(TimeStamped.class);
// Now check non-effect of removing interceptor that isn't there // Now check non-effect of removing interceptor that isn't there
config.removeAdvice(new DebugInterceptor()); config.removeAdvice(new DebugInterceptor());

View File

@ -69,8 +69,6 @@ import org.springframework.util.StopWatch;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.hamcrest.CoreMatchers.instanceOf;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNotNull;
@ -626,7 +624,7 @@ public class XmlBeanFactoryTests {
public void testFactoryReferenceWithDoublePrefix() { public void testFactoryReferenceWithDoublePrefix() {
DefaultListableBeanFactory xbf = new DefaultListableBeanFactory(); DefaultListableBeanFactory xbf = new DefaultListableBeanFactory();
new XmlBeanDefinitionReader(xbf).loadBeanDefinitions(FACTORY_CIRCLE_CONTEXT); new XmlBeanDefinitionReader(xbf).loadBeanDefinitions(FACTORY_CIRCLE_CONTEXT);
assertThat(xbf.getBean("&&singletonFactory"), instanceOf(DummyFactory.class)); assertThat(xbf.getBean("&&singletonFactory")).isInstanceOf(DummyFactory.class);
} }
@Test @Test

View File

@ -24,8 +24,7 @@ import java.util.concurrent.atomic.AtomicInteger;
import org.junit.Test; import org.junit.Test;
import static org.hamcrest.MatcherAssert.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull; import static org.junit.Assert.assertNull;
@ -207,7 +206,7 @@ public abstract class AbstractCacheTests<T extends Cache> {
latch.await(); latch.await();
assertEquals(10, results.size()); assertEquals(10, results.size());
results.forEach(r -> assertThat(r, is(1))); // Only one method got invoked results.forEach(r -> assertThat(r).isEqualTo(1)); // Only one method got invoked
} }
protected String createRandomKey() { protected String createRandomKey() {

View File

@ -33,10 +33,8 @@ import org.springframework.cache.interceptor.CacheOperation;
import org.springframework.cache.interceptor.CacheableOperation; import org.springframework.cache.interceptor.CacheableOperation;
import org.springframework.core.annotation.AliasFor; import org.springframework.core.annotation.AliasFor;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalStateException; import static org.assertj.core.api.Assertions.assertThatIllegalStateException;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.instanceOf;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertSame; import static org.junit.Assert.assertSame;
@ -104,14 +102,14 @@ public class AnnotationCacheOperationSourceTests {
Iterator<CacheOperation> it = ops.iterator(); Iterator<CacheOperation> it = ops.iterator();
CacheOperation cacheOperation = it.next(); CacheOperation cacheOperation = it.next();
assertThat(cacheOperation, instanceOf(CacheableOperation.class)); assertThat(cacheOperation).isInstanceOf(CacheableOperation.class);
assertThat(cacheOperation.getCacheNames(), equalTo(Collections.singleton("directly declared"))); assertThat(cacheOperation.getCacheNames()).isEqualTo(Collections.singleton("directly declared"));
assertThat(cacheOperation.getKey(), equalTo("")); assertThat(cacheOperation.getKey()).isEqualTo("");
cacheOperation = it.next(); cacheOperation = it.next();
assertThat(cacheOperation, instanceOf(CacheableOperation.class)); assertThat(cacheOperation).isInstanceOf(CacheableOperation.class);
assertThat(cacheOperation.getCacheNames(), equalTo(Collections.singleton("composedCache"))); assertThat(cacheOperation.getCacheNames()).isEqualTo(Collections.singleton("composedCache"));
assertThat(cacheOperation.getKey(), equalTo("composedKey")); assertThat(cacheOperation.getKey()).isEqualTo("composedKey");
} }
@Test @Test
@ -120,24 +118,24 @@ public class AnnotationCacheOperationSourceTests {
Iterator<CacheOperation> it = ops.iterator(); Iterator<CacheOperation> it = ops.iterator();
CacheOperation cacheOperation = it.next(); CacheOperation cacheOperation = it.next();
assertThat(cacheOperation, instanceOf(CacheableOperation.class)); assertThat(cacheOperation).isInstanceOf(CacheableOperation.class);
assertThat(cacheOperation.getCacheNames(), equalTo(Collections.singleton("directly declared"))); assertThat(cacheOperation.getCacheNames()).isEqualTo(Collections.singleton("directly declared"));
assertThat(cacheOperation.getKey(), equalTo("")); assertThat(cacheOperation.getKey()).isEqualTo("");
cacheOperation = it.next(); cacheOperation = it.next();
assertThat(cacheOperation, instanceOf(CacheableOperation.class)); assertThat(cacheOperation).isInstanceOf(CacheableOperation.class);
assertThat(cacheOperation.getCacheNames(), equalTo(Collections.singleton("composedCache"))); assertThat(cacheOperation.getCacheNames()).isEqualTo(Collections.singleton("composedCache"));
assertThat(cacheOperation.getKey(), equalTo("composedKey")); assertThat(cacheOperation.getKey()).isEqualTo("composedKey");
cacheOperation = it.next(); cacheOperation = it.next();
assertThat(cacheOperation, instanceOf(CacheableOperation.class)); assertThat(cacheOperation).isInstanceOf(CacheableOperation.class);
assertThat(cacheOperation.getCacheNames(), equalTo(Collections.singleton("foo"))); assertThat(cacheOperation.getCacheNames()).isEqualTo(Collections.singleton("foo"));
assertThat(cacheOperation.getKey(), equalTo("")); assertThat(cacheOperation.getKey()).isEqualTo("");
cacheOperation = it.next(); cacheOperation = it.next();
assertThat(cacheOperation, instanceOf(CacheEvictOperation.class)); assertThat(cacheOperation).isInstanceOf(CacheEvictOperation.class);
assertThat(cacheOperation.getCacheNames(), equalTo(Collections.singleton("composedCacheEvict"))); assertThat(cacheOperation.getCacheNames()).isEqualTo(Collections.singleton("composedCacheEvict"));
assertThat(cacheOperation.getKey(), equalTo("composedEvictionKey")); assertThat(cacheOperation.getKey()).isEqualTo("composedEvictionKey");
} }
@Test @Test

View File

@ -29,11 +29,9 @@ import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager; import org.springframework.cache.CacheManager;
import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.ConfigurableApplicationContext;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.assertThatIOException; import static org.assertj.core.api.Assertions.assertThatIOException;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.nullValue;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNotSame; import static org.junit.Assert.assertNotSame;
@ -276,8 +274,8 @@ public abstract class AbstractCacheAnnotationTests {
cache.clear(); cache.clear();
service.unless(10); service.unless(10);
service.unless(11); service.unless(11);
assertThat(cache.get(10).get(), equalTo(10L)); assertThat(cache.get(10).get()).isEqualTo(10L);
assertThat(cache.get(11), nullValue()); assertThat(cache.get(11)).isNull();
} }
public void testKeyExpression(CacheableService<?> service) throws Exception { public void testKeyExpression(CacheableService<?> service) throws Exception {

View File

@ -38,10 +38,6 @@ import org.springframework.util.ReflectionUtils;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.nullValue;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertTrue;
@ -105,21 +101,21 @@ public class ExpressionEvaluatorTests {
public void withReturnValue() { public void withReturnValue() {
EvaluationContext context = createEvaluationContext("theResult"); EvaluationContext context = createEvaluationContext("theResult");
Object value = new SpelExpressionParser().parseExpression("#result").getValue(context); Object value = new SpelExpressionParser().parseExpression("#result").getValue(context);
assertThat(value, equalTo("theResult")); assertThat(value).isEqualTo("theResult");
} }
@Test @Test
public void withNullReturn() { public void withNullReturn() {
EvaluationContext context = createEvaluationContext(null); EvaluationContext context = createEvaluationContext(null);
Object value = new SpelExpressionParser().parseExpression("#result").getValue(context); Object value = new SpelExpressionParser().parseExpression("#result").getValue(context);
assertThat(value, nullValue()); assertThat(value).isNull();
} }
@Test @Test
public void withoutReturnValue() { public void withoutReturnValue() {
EvaluationContext context = createEvaluationContext(CacheOperationExpressionEvaluator.NO_RESULT); EvaluationContext context = createEvaluationContext(CacheOperationExpressionEvaluator.NO_RESULT);
Object value = new SpelExpressionParser().parseExpression("#result").getValue(context); Object value = new SpelExpressionParser().parseExpression("#result").getValue(context);
assertThat(value, nullValue()); assertThat(value).isNull();
} }
@Test @Test
@ -139,7 +135,7 @@ public class ExpressionEvaluatorTests {
EvaluationContext context = createEvaluationContext(CacheOperationExpressionEvaluator.NO_RESULT, applicationContext); EvaluationContext context = createEvaluationContext(CacheOperationExpressionEvaluator.NO_RESULT, applicationContext);
Object value = new SpelExpressionParser().parseExpression("@myBean.class.getName()").getValue(context); Object value = new SpelExpressionParser().parseExpression("@myBean.class.getName()").getValue(context);
assertThat(value, is(String.class.getName())); assertThat(value).isEqualTo(String.class.getName());
} }
private EvaluationContext createEvaluationContext(Object result) { private EvaluationContext createEvaluationContext(Object result) {

View File

@ -18,10 +18,11 @@ package org.springframework.cache.interceptor;
import org.junit.Test; import org.junit.Test;
import static org.hamcrest.MatcherAssert.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.instanceOf;
import static org.hamcrest.Matchers.not;
/** /**
* Tests for {@link SimpleKeyGenerator} and {@link SimpleKey}. * Tests for {@link SimpleKeyGenerator} and {@link SimpleKey}.
@ -39,10 +40,10 @@ public class SimpleKeyGeneratorTests {
Object k1 = generateKey(new Object[] {}); Object k1 = generateKey(new Object[] {});
Object k2 = generateKey(new Object[] {}); Object k2 = generateKey(new Object[] {});
Object k3 = generateKey(new Object[] { "different" }); Object k3 = generateKey(new Object[] { "different" });
assertThat(k1.hashCode(), equalTo(k2.hashCode())); assertThat(k1.hashCode()).isEqualTo(k2.hashCode());
assertThat(k1.hashCode(), not(equalTo(k3.hashCode()))); assertThat(k1.hashCode()).isNotEqualTo(k3.hashCode());
assertThat(k1, equalTo(k2)); assertThat(k1).isEqualTo(k2);
assertThat(k1, not(equalTo(k3))); assertThat(k1).isNotEqualTo(k3);
} }
@Test @Test
@ -50,11 +51,11 @@ public class SimpleKeyGeneratorTests {
Object k1 = generateKey(new Object[] { "a" }); Object k1 = generateKey(new Object[] { "a" });
Object k2 = generateKey(new Object[] { "a" }); Object k2 = generateKey(new Object[] { "a" });
Object k3 = generateKey(new Object[] { "different" }); Object k3 = generateKey(new Object[] { "different" });
assertThat(k1.hashCode(), equalTo(k2.hashCode())); assertThat(k1.hashCode()).isEqualTo(k2.hashCode());
assertThat(k1.hashCode(), not(equalTo(k3.hashCode()))); assertThat(k1.hashCode()).isNotEqualTo(k3.hashCode());
assertThat(k1, equalTo(k2)); assertThat(k1).isEqualTo(k2);
assertThat(k1, not(equalTo(k3))); assertThat(k1).isNotEqualTo(k3);
assertThat(k1, equalTo("a")); assertThat(k1).isEqualTo("a");
} }
@Test @Test
@ -62,10 +63,10 @@ public class SimpleKeyGeneratorTests {
Object k1 = generateKey(new Object[] { "a", 1, "b" }); Object k1 = generateKey(new Object[] { "a", 1, "b" });
Object k2 = generateKey(new Object[] { "a", 1, "b" }); Object k2 = generateKey(new Object[] { "a", 1, "b" });
Object k3 = generateKey(new Object[] { "b", 1, "a" }); Object k3 = generateKey(new Object[] { "b", 1, "a" });
assertThat(k1.hashCode(), equalTo(k2.hashCode())); assertThat(k1.hashCode()).isEqualTo(k2.hashCode());
assertThat(k1.hashCode(), not(equalTo(k3.hashCode()))); assertThat(k1.hashCode()).isNotEqualTo(k3.hashCode());
assertThat(k1, equalTo(k2)); assertThat(k1).isEqualTo(k2);
assertThat(k1, not(equalTo(k3))); assertThat(k1).isNotEqualTo(k3);
} }
@Test @Test
@ -73,11 +74,11 @@ public class SimpleKeyGeneratorTests {
Object k1 = generateKey(new Object[] { null }); Object k1 = generateKey(new Object[] { null });
Object k2 = generateKey(new Object[] { null }); Object k2 = generateKey(new Object[] { null });
Object k3 = generateKey(new Object[] { "different" }); Object k3 = generateKey(new Object[] { "different" });
assertThat(k1.hashCode(), equalTo(k2.hashCode())); assertThat(k1.hashCode()).isEqualTo(k2.hashCode());
assertThat(k1.hashCode(), not(equalTo(k3.hashCode()))); assertThat(k1.hashCode()).isNotEqualTo(k3.hashCode());
assertThat(k1, equalTo(k2)); assertThat(k1).isEqualTo(k2);
assertThat(k1, not(equalTo(k3))); assertThat(k1).isNotEqualTo(k3);
assertThat(k1, instanceOf(SimpleKey.class)); assertThat(k1).isInstanceOf(SimpleKey.class);
} }
@Test @Test
@ -85,10 +86,10 @@ public class SimpleKeyGeneratorTests {
Object k1 = generateKey(new Object[] { "a", null, "b", null }); Object k1 = generateKey(new Object[] { "a", null, "b", null });
Object k2 = generateKey(new Object[] { "a", null, "b", null }); Object k2 = generateKey(new Object[] { "a", null, "b", null });
Object k3 = generateKey(new Object[] { "a", null, "b" }); Object k3 = generateKey(new Object[] { "a", null, "b" });
assertThat(k1.hashCode(), equalTo(k2.hashCode())); assertThat(k1.hashCode()).isEqualTo(k2.hashCode());
assertThat(k1.hashCode(), not(equalTo(k3.hashCode()))); assertThat(k1.hashCode()).isNotEqualTo(k3.hashCode());
assertThat(k1, equalTo(k2)); assertThat(k1).isEqualTo(k2);
assertThat(k1, not(equalTo(k3))); assertThat(k1).isNotEqualTo(k3);
} }
@Test @Test
@ -96,10 +97,10 @@ public class SimpleKeyGeneratorTests {
Object k1 = generateKey(new Object[] { new String[]{"a", "b"} }); Object k1 = generateKey(new Object[] { new String[]{"a", "b"} });
Object k2 = generateKey(new Object[] { new String[]{"a", "b"} }); Object k2 = generateKey(new Object[] { new String[]{"a", "b"} });
Object k3 = generateKey(new Object[] { new String[]{"b", "a"} }); Object k3 = generateKey(new Object[] { new String[]{"b", "a"} });
assertThat(k1.hashCode(), equalTo(k2.hashCode())); assertThat(k1.hashCode()).isEqualTo(k2.hashCode());
assertThat(k1.hashCode(), not(equalTo(k3.hashCode()))); assertThat(k1.hashCode()).isNotEqualTo(k3.hashCode());
assertThat(k1, equalTo(k2)); assertThat(k1).isEqualTo(k2);
assertThat(k1, not(equalTo(k3))); assertThat(k1).isNotEqualTo(k3);
} }
@Test @Test
@ -107,10 +108,10 @@ public class SimpleKeyGeneratorTests {
Object k1 = generateKey(new Object[] { new String[]{"a", "b"}, "c" }); Object k1 = generateKey(new Object[] { new String[]{"a", "b"}, "c" });
Object k2 = generateKey(new Object[] { new String[]{"a", "b"}, "c" }); Object k2 = generateKey(new Object[] { new String[]{"a", "b"}, "c" });
Object k3 = generateKey(new Object[] { new String[]{"b", "a"}, "c" }); Object k3 = generateKey(new Object[] { new String[]{"b", "a"}, "c" });
assertThat(k1.hashCode(), equalTo(k2.hashCode())); assertThat(k1.hashCode()).isEqualTo(k2.hashCode());
assertThat(k1.hashCode(), not(equalTo(k3.hashCode()))); assertThat(k1.hashCode()).isNotEqualTo(k3.hashCode());
assertThat(k1, equalTo(k2)); assertThat(k1).isEqualTo(k2);
assertThat(k1, not(equalTo(k3))); assertThat(k1).isNotEqualTo(k3);
} }

View File

@ -34,11 +34,8 @@ import org.springframework.core.ResolvableType;
import org.springframework.util.ObjectUtils; import org.springframework.util.ObjectUtils;
import static java.lang.String.format; import static java.lang.String.format;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.allOf;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertFalse;
@ -97,7 +94,7 @@ public class AnnotationConfigApplicationContextTests {
ApplicationContext context = new AnnotationConfigApplicationContext(Config.class); ApplicationContext context = new AnnotationConfigApplicationContext(Config.class);
TestBean testBean = context.getBean(TestBean.class); TestBean testBean = context.getBean(TestBean.class);
assertNotNull(testBean); assertNotNull(testBean);
assertThat(testBean.name, equalTo("foo")); assertThat(testBean.name).isEqualTo("foo");
} }
@Test @Test
@ -114,19 +111,11 @@ public class AnnotationConfigApplicationContextTests {
@Test @Test
public void getBeanByTypeAmbiguityRaisesException() { public void getBeanByTypeAmbiguityRaisesException() {
ApplicationContext context = new AnnotationConfigApplicationContext(TwoTestBeanConfig.class); ApplicationContext context = new AnnotationConfigApplicationContext(TwoTestBeanConfig.class);
assertThatExceptionOfType(NoSuchBeanDefinitionException.class).isThrownBy(() ->
try { context.getBean(TestBean.class))
context.getBean(TestBean.class); .withMessageContaining("No qualifying bean of type '" + TestBean.class.getName() + "'")
} .withMessageContaining("tb1")
catch (NoSuchBeanDefinitionException ex) { .withMessageContaining("tb2");
assertThat(ex.getMessage(),
allOf(
containsString("No qualifying bean of type '" + TestBean.class.getName() + "'"),
containsString("tb1"),
containsString("tb2")
)
);
}
} }
/** /**
@ -158,7 +147,7 @@ public class AnnotationConfigApplicationContextTests {
@Test @Test
public void autowiringIsEnabledByDefault() { public void autowiringIsEnabledByDefault() {
ApplicationContext context = new AnnotationConfigApplicationContext(AutowiredConfig.class); ApplicationContext context = new AnnotationConfigApplicationContext(AutowiredConfig.class);
assertThat(context.getBean(TestBean.class).name, equalTo("foo")); assertThat(context.getBean(TestBean.class).name).isEqualTo("foo");
} }
@Test @Test

View File

@ -25,9 +25,10 @@ import org.junit.Test;
import org.springframework.beans.factory.annotation.AnnotatedBeanDefinition; import org.springframework.beans.factory.annotation.AnnotatedBeanDefinition;
import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.beans.factory.config.BeanDefinition;
import static org.hamcrest.MatcherAssert.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.instanceOf;
/** /**
* @author Phillip Webb * @author Phillip Webb
@ -39,10 +40,10 @@ public class BeanMethodMetadataTests {
public void providesBeanMethodBeanDefinition() throws Exception { public void providesBeanMethodBeanDefinition() throws Exception {
AnnotationConfigApplicationContext context= new AnnotationConfigApplicationContext(Conf.class); AnnotationConfigApplicationContext context= new AnnotationConfigApplicationContext(Conf.class);
BeanDefinition beanDefinition = context.getBeanDefinition("myBean"); BeanDefinition beanDefinition = context.getBeanDefinition("myBean");
assertThat("should provide AnnotatedBeanDefinition", beanDefinition, instanceOf(AnnotatedBeanDefinition.class)); assertThat(beanDefinition).as("should provide AnnotatedBeanDefinition").isInstanceOf(AnnotatedBeanDefinition.class);
Map<String, Object> annotationAttributes = Map<String, Object> annotationAttributes =
((AnnotatedBeanDefinition) beanDefinition).getFactoryMethodMetadata().getAnnotationAttributes(MyAnnotation.class.getName()); ((AnnotatedBeanDefinition) beanDefinition).getFactoryMethodMetadata().getAnnotationAttributes(MyAnnotation.class.getName());
assertThat(annotationAttributes.get("value"), equalTo("test")); assertThat(annotationAttributes.get("value")).isEqualTo("test");
context.close(); context.close();
} }

View File

@ -25,8 +25,7 @@ import org.springframework.aop.interceptor.SimpleTraceInterceptor;
import org.springframework.aop.support.DefaultPointcutAdvisor; import org.springframework.aop.support.DefaultPointcutAdvisor;
import org.springframework.beans.factory.support.RootBeanDefinition; import org.springframework.beans.factory.support.RootBeanDefinition;
import static org.hamcrest.CoreMatchers.equalTo; import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertTrue;
@ -98,7 +97,7 @@ public class BeanMethodPolymorphismTests {
ctx.register(ConfigWithOverloading.class); ctx.register(ConfigWithOverloading.class);
ctx.setAllowBeanDefinitionOverriding(false); ctx.setAllowBeanDefinitionOverriding(false);
ctx.refresh(); ctx.refresh();
assertThat(ctx.getBean(String.class), equalTo("regular")); assertThat(ctx.getBean(String.class)).isEqualTo("regular");
} }
@Test @Test
@ -108,7 +107,7 @@ public class BeanMethodPolymorphismTests {
ctx.getDefaultListableBeanFactory().registerSingleton("anInt", 5); ctx.getDefaultListableBeanFactory().registerSingleton("anInt", 5);
ctx.setAllowBeanDefinitionOverriding(false); ctx.setAllowBeanDefinitionOverriding(false);
ctx.refresh(); ctx.refresh();
assertThat(ctx.getBean(String.class), equalTo("overloaded5")); assertThat(ctx.getBean(String.class)).isEqualTo("overloaded5");
} }
@Test @Test
@ -118,7 +117,7 @@ public class BeanMethodPolymorphismTests {
ctx.setAllowBeanDefinitionOverriding(false); ctx.setAllowBeanDefinitionOverriding(false);
ctx.refresh(); ctx.refresh();
assertFalse(ctx.getDefaultListableBeanFactory().containsSingleton("aString")); assertFalse(ctx.getDefaultListableBeanFactory().containsSingleton("aString"));
assertThat(ctx.getBean(String.class), equalTo("regular")); assertThat(ctx.getBean(String.class)).isEqualTo("regular");
assertTrue(ctx.getDefaultListableBeanFactory().containsSingleton("aString")); assertTrue(ctx.getDefaultListableBeanFactory().containsSingleton("aString"));
} }
@ -130,7 +129,7 @@ public class BeanMethodPolymorphismTests {
ctx.setAllowBeanDefinitionOverriding(false); ctx.setAllowBeanDefinitionOverriding(false);
ctx.refresh(); ctx.refresh();
assertFalse(ctx.getDefaultListableBeanFactory().containsSingleton("aString")); assertFalse(ctx.getDefaultListableBeanFactory().containsSingleton("aString"));
assertThat(ctx.getBean(String.class), equalTo("overloaded5")); assertThat(ctx.getBean(String.class)).isEqualTo("overloaded5");
assertTrue(ctx.getDefaultListableBeanFactory().containsSingleton("aString")); assertTrue(ctx.getDefaultListableBeanFactory().containsSingleton("aString"));
} }
@ -141,7 +140,7 @@ public class BeanMethodPolymorphismTests {
ctx.setAllowBeanDefinitionOverriding(false); ctx.setAllowBeanDefinitionOverriding(false);
ctx.refresh(); ctx.refresh();
assertFalse(ctx.getDefaultListableBeanFactory().containsSingleton("aString")); assertFalse(ctx.getDefaultListableBeanFactory().containsSingleton("aString"));
assertThat(ctx.getBean(String.class), equalTo("overloaded5")); assertThat(ctx.getBean(String.class)).isEqualTo("overloaded5");
assertTrue(ctx.getDefaultListableBeanFactory().containsSingleton("aString")); assertTrue(ctx.getDefaultListableBeanFactory().containsSingleton("aString"));
} }
@ -153,7 +152,7 @@ public class BeanMethodPolymorphismTests {
ctx.setAllowBeanDefinitionOverriding(false); ctx.setAllowBeanDefinitionOverriding(false);
ctx.refresh(); ctx.refresh();
assertFalse(ctx.getDefaultListableBeanFactory().containsSingleton("aString")); assertFalse(ctx.getDefaultListableBeanFactory().containsSingleton("aString"));
assertThat(ctx.getBean(String.class), equalTo("overloaded5")); assertThat(ctx.getBean(String.class)).isEqualTo("overloaded5");
assertTrue(ctx.getDefaultListableBeanFactory().containsSingleton("aString")); assertTrue(ctx.getDefaultListableBeanFactory().containsSingleton("aString"));
} }
@ -165,7 +164,7 @@ public class BeanMethodPolymorphismTests {
@Test @Test
public void beanMethodShadowing() { public void beanMethodShadowing() {
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(ShadowConfig.class); AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(ShadowConfig.class);
assertThat(ctx.getBean(String.class), equalTo("shadow")); assertThat(ctx.getBean(String.class)).isEqualTo("shadow");
} }
@Test @Test

View File

@ -55,9 +55,7 @@ import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Repository; import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import static org.hamcrest.CoreMatchers.instanceOf; import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertTrue;
@ -368,7 +366,7 @@ public class ClassPathScanningCandidateComponentProviderTests {
public void testWithNullEnvironment() { public void testWithNullEnvironment() {
ClassPathScanningCandidateComponentProvider provider = new ClassPathScanningCandidateComponentProvider(true); ClassPathScanningCandidateComponentProvider provider = new ClassPathScanningCandidateComponentProvider(true);
Set<BeanDefinition> candidates = provider.findCandidateComponents(TEST_PROFILE_PACKAGE); Set<BeanDefinition> candidates = provider.findCandidateComponents(TEST_PROFILE_PACKAGE);
assertThat(containsBeanClass(candidates, ProfileAnnotatedComponent.class), is(false)); assertThat(containsBeanClass(candidates, ProfileAnnotatedComponent.class)).isFalse();
} }
@Test @Test
@ -378,7 +376,7 @@ public class ClassPathScanningCandidateComponentProviderTests {
env.setActiveProfiles("other"); env.setActiveProfiles("other");
provider.setEnvironment(env); provider.setEnvironment(env);
Set<BeanDefinition> candidates = provider.findCandidateComponents(TEST_PROFILE_PACKAGE); Set<BeanDefinition> candidates = provider.findCandidateComponents(TEST_PROFILE_PACKAGE);
assertThat(containsBeanClass(candidates, ProfileAnnotatedComponent.class), is(false)); assertThat(containsBeanClass(candidates, ProfileAnnotatedComponent.class)).isFalse();
} }
@Test @Test
@ -388,7 +386,7 @@ public class ClassPathScanningCandidateComponentProviderTests {
env.setActiveProfiles(ProfileAnnotatedComponent.PROFILE_NAME); env.setActiveProfiles(ProfileAnnotatedComponent.PROFILE_NAME);
provider.setEnvironment(env); provider.setEnvironment(env);
Set<BeanDefinition> candidates = provider.findCandidateComponents(TEST_PROFILE_PACKAGE); Set<BeanDefinition> candidates = provider.findCandidateComponents(TEST_PROFILE_PACKAGE);
assertThat(containsBeanClass(candidates, ProfileAnnotatedComponent.class), is(true)); assertThat(containsBeanClass(candidates, ProfileAnnotatedComponent.class)).isTrue();
} }
@Test @Test
@ -396,7 +394,7 @@ public class ClassPathScanningCandidateComponentProviderTests {
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(); AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
ctx.register(ProfileAnnotatedComponent.class); ctx.register(ProfileAnnotatedComponent.class);
ctx.refresh(); ctx.refresh();
assertThat(ctx.containsBean(ProfileAnnotatedComponent.BEAN_NAME), is(false)); assertThat(ctx.containsBean(ProfileAnnotatedComponent.BEAN_NAME)).isFalse();
} }
@Test @Test
@ -405,7 +403,7 @@ public class ClassPathScanningCandidateComponentProviderTests {
ctx.getEnvironment().setActiveProfiles(ProfileAnnotatedComponent.PROFILE_NAME); ctx.getEnvironment().setActiveProfiles(ProfileAnnotatedComponent.PROFILE_NAME);
ctx.register(ProfileAnnotatedComponent.class); ctx.register(ProfileAnnotatedComponent.class);
ctx.refresh(); ctx.refresh();
assertThat(ctx.containsBean(ProfileAnnotatedComponent.BEAN_NAME), is(true)); assertThat(ctx.containsBean(ProfileAnnotatedComponent.BEAN_NAME)).isTrue();
} }
@Test @Test
@ -414,7 +412,7 @@ public class ClassPathScanningCandidateComponentProviderTests {
ctx.getEnvironment().setActiveProfiles(DevComponent.PROFILE_NAME); ctx.getEnvironment().setActiveProfiles(DevComponent.PROFILE_NAME);
ctx.register(ProfileMetaAnnotatedComponent.class); ctx.register(ProfileMetaAnnotatedComponent.class);
ctx.refresh(); ctx.refresh();
assertThat(ctx.containsBean(ProfileMetaAnnotatedComponent.BEAN_NAME), is(true)); assertThat(ctx.containsBean(ProfileMetaAnnotatedComponent.BEAN_NAME)).isTrue();
} }
@Test @Test
@ -423,7 +421,7 @@ public class ClassPathScanningCandidateComponentProviderTests {
ctx.getEnvironment().setActiveProfiles("other"); ctx.getEnvironment().setActiveProfiles("other");
ctx.register(ProfileAnnotatedComponent.class); ctx.register(ProfileAnnotatedComponent.class);
ctx.refresh(); ctx.refresh();
assertThat(ctx.containsBean(ProfileAnnotatedComponent.BEAN_NAME), is(false)); assertThat(ctx.containsBean(ProfileAnnotatedComponent.BEAN_NAME)).isFalse();
} }
@Test @Test
@ -432,7 +430,7 @@ public class ClassPathScanningCandidateComponentProviderTests {
ctx.getEnvironment().setActiveProfiles("other"); ctx.getEnvironment().setActiveProfiles("other");
ctx.register(ProfileMetaAnnotatedComponent.class); ctx.register(ProfileMetaAnnotatedComponent.class);
ctx.refresh(); ctx.refresh();
assertThat(ctx.containsBean(ProfileMetaAnnotatedComponent.BEAN_NAME), is(false)); assertThat(ctx.containsBean(ProfileMetaAnnotatedComponent.BEAN_NAME)).isFalse();
} }
@Test @Test
@ -442,7 +440,7 @@ public class ClassPathScanningCandidateComponentProviderTests {
// no active profiles are set // no active profiles are set
ctx.register(DefaultProfileAnnotatedComponent.class); ctx.register(DefaultProfileAnnotatedComponent.class);
ctx.refresh(); ctx.refresh();
assertThat(ctx.containsBean(DefaultProfileAnnotatedComponent.BEAN_NAME), is(true)); assertThat(ctx.containsBean(DefaultProfileAnnotatedComponent.BEAN_NAME)).isTrue();
} }
@Test @Test
@ -455,7 +453,7 @@ public class ClassPathScanningCandidateComponentProviderTests {
// no active profiles are set // no active profiles are set
ctx.register(beanClass); ctx.register(beanClass);
ctx.refresh(); ctx.refresh();
assertThat(ctx.containsBean(beanName), is(true)); assertThat(ctx.containsBean(beanName)).isTrue();
} }
{ {
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(); AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
@ -463,7 +461,7 @@ public class ClassPathScanningCandidateComponentProviderTests {
ctx.getEnvironment().setActiveProfiles("dev"); ctx.getEnvironment().setActiveProfiles("dev");
ctx.register(beanClass); ctx.register(beanClass);
ctx.refresh(); ctx.refresh();
assertThat(ctx.containsBean(beanName), is(true)); assertThat(ctx.containsBean(beanName)).isTrue();
} }
{ {
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(); AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
@ -471,7 +469,7 @@ public class ClassPathScanningCandidateComponentProviderTests {
ctx.getEnvironment().setActiveProfiles("other"); ctx.getEnvironment().setActiveProfiles("other");
ctx.register(beanClass); ctx.register(beanClass);
ctx.refresh(); ctx.refresh();
assertThat(ctx.containsBean(beanName), is(false)); assertThat(ctx.containsBean(beanName)).isFalse();
} }
} }
@ -485,7 +483,7 @@ public class ClassPathScanningCandidateComponentProviderTests {
// no active profiles are set // no active profiles are set
ctx.register(beanClass); ctx.register(beanClass);
ctx.refresh(); ctx.refresh();
assertThat(ctx.containsBean(beanName), is(true)); assertThat(ctx.containsBean(beanName)).isTrue();
} }
{ {
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(); AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
@ -493,7 +491,7 @@ public class ClassPathScanningCandidateComponentProviderTests {
ctx.getEnvironment().setActiveProfiles("dev"); ctx.getEnvironment().setActiveProfiles("dev");
ctx.register(beanClass); ctx.register(beanClass);
ctx.refresh(); ctx.refresh();
assertThat(ctx.containsBean(beanName), is(true)); assertThat(ctx.containsBean(beanName)).isTrue();
} }
{ {
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(); AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
@ -501,7 +499,7 @@ public class ClassPathScanningCandidateComponentProviderTests {
ctx.getEnvironment().setActiveProfiles("other"); ctx.getEnvironment().setActiveProfiles("other");
ctx.register(beanClass); ctx.register(beanClass);
ctx.refresh(); ctx.refresh();
assertThat(ctx.containsBean(beanName), is(false)); assertThat(ctx.containsBean(beanName)).isFalse();
} }
} }
@ -517,7 +515,7 @@ public class ClassPathScanningCandidateComponentProviderTests {
private void assertBeanDefinitionType(Set<BeanDefinition> candidates, private void assertBeanDefinitionType(Set<BeanDefinition> candidates,
Class<? extends BeanDefinition> expectedType) { Class<? extends BeanDefinition> expectedType) {
candidates.forEach(c -> candidates.forEach(c ->
assertThat(c, is(instanceOf(expectedType))) assertThat(c).isInstanceOf(expectedType)
); );
} }

View File

@ -61,12 +61,7 @@ import org.springframework.core.type.filter.TypeFilter;
import org.springframework.tests.context.SimpleMapScope; import org.springframework.tests.context.SimpleMapScope;
import org.springframework.util.SerializationTestUtils; import org.springframework.util.SerializationTestUtils;
import static org.hamcrest.CoreMatchers.equalTo; import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.not;
import static org.hamcrest.CoreMatchers.notNullValue;
import static org.hamcrest.CoreMatchers.sameInstance;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertTrue;
@ -88,8 +83,8 @@ public class ComponentScanAnnotationIntegrationTests {
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(); AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
ctx.scan(example.scannable._package.class.getPackage().getName()); ctx.scan(example.scannable._package.class.getPackage().getName());
ctx.refresh(); ctx.refresh();
assertThat("control scan for example.scannable package failed to register FooServiceImpl bean", assertThat(ctx.containsBean("fooServiceImpl")).as(
ctx.containsBean("fooServiceImpl"), is(true)); "control scan for example.scannable package failed to register FooServiceImpl bean").isTrue();
} }
@Test @Test
@ -99,10 +94,11 @@ public class ComponentScanAnnotationIntegrationTests {
ctx.refresh(); ctx.refresh();
ctx.getBean(ComponentScanAnnotatedConfig.class); ctx.getBean(ComponentScanAnnotatedConfig.class);
ctx.getBean(TestBean.class); ctx.getBean(TestBean.class);
assertThat("config class bean not found", ctx.containsBeanDefinition("componentScanAnnotatedConfig"), is(true)); assertThat(ctx.containsBeanDefinition("componentScanAnnotatedConfig")).as("config class bean not found")
assertThat("@ComponentScan annotated @Configuration class registered directly against " + .isTrue();
"AnnotationConfigApplicationContext did not trigger component scanning as expected", assertThat(ctx.containsBean("fooServiceImpl")).as("@ComponentScan annotated @Configuration class registered directly against " +
ctx.containsBean("fooServiceImpl"), is(true)); "AnnotationConfigApplicationContext did not trigger component scanning as expected")
.isTrue();
} }
@Test @Test
@ -112,10 +108,11 @@ public class ComponentScanAnnotationIntegrationTests {
ctx.refresh(); ctx.refresh();
ctx.getBean(ComponentScanAnnotatedConfig_WithValueAttribute.class); ctx.getBean(ComponentScanAnnotatedConfig_WithValueAttribute.class);
ctx.getBean(TestBean.class); ctx.getBean(TestBean.class);
assertThat("config class bean not found", ctx.containsBeanDefinition("componentScanAnnotatedConfig_WithValueAttribute"), is(true)); assertThat(ctx.containsBeanDefinition("componentScanAnnotatedConfig_WithValueAttribute")).as("config class bean not found")
assertThat("@ComponentScan annotated @Configuration class registered directly against " + .isTrue();
"AnnotationConfigApplicationContext did not trigger component scanning as expected", assertThat(ctx.containsBean("fooServiceImpl")).as("@ComponentScan annotated @Configuration class registered directly against " +
ctx.containsBean("fooServiceImpl"), is(true)); "AnnotationConfigApplicationContext did not trigger component scanning as expected")
.isTrue();
} }
@Test @Test
@ -124,11 +121,13 @@ public class ComponentScanAnnotationIntegrationTests {
ctx.register(ComponentScanAnnotatedConfigWithImplicitBasePackage.class); ctx.register(ComponentScanAnnotatedConfigWithImplicitBasePackage.class);
ctx.refresh(); ctx.refresh();
ctx.getBean(ComponentScanAnnotatedConfigWithImplicitBasePackage.class); ctx.getBean(ComponentScanAnnotatedConfigWithImplicitBasePackage.class);
assertThat("config class bean not found", ctx.containsBeanDefinition("componentScanAnnotatedConfigWithImplicitBasePackage"), is(true)); assertThat(ctx.containsBeanDefinition("componentScanAnnotatedConfigWithImplicitBasePackage")).as("config class bean not found")
assertThat("@ComponentScan annotated @Configuration class registered directly against " + .isTrue();
"AnnotationConfigApplicationContext did not trigger component scanning as expected", assertThat(ctx.containsBean("scannedComponent")).as("@ComponentScan annotated @Configuration class registered directly against " +
ctx.containsBean("scannedComponent"), is(true)); "AnnotationConfigApplicationContext did not trigger component scanning as expected")
assertThat("@Bean method overrides scanned class", ctx.getBean(ConfigurableComponent.class).isFlag(), is(true)); .isTrue();
assertThat(ctx.getBean(ConfigurableComponent.class).isFlag()).as("@Bean method overrides scanned class")
.isTrue();
} }
@Test @Test
@ -140,11 +139,11 @@ public class ComponentScanAnnotationIntegrationTests {
ctx.getBean(SimpleComponent.class); ctx.getBean(SimpleComponent.class);
ctx.getBean(ClassWithNestedComponents.NestedComponent.class); ctx.getBean(ClassWithNestedComponents.NestedComponent.class);
ctx.getBean(ClassWithNestedComponents.OtherNestedComponent.class); ctx.getBean(ClassWithNestedComponents.OtherNestedComponent.class);
assertThat("config class bean not found", assertThat(ctx.containsBeanDefinition("componentScanAnnotationIntegrationTests.ComposedAnnotationConfig")).as("config class bean not found")
ctx.containsBeanDefinition("componentScanAnnotationIntegrationTests.ComposedAnnotationConfig"), is(true)); .isTrue();
assertThat("@ComponentScan annotated @Configuration class registered directly against " + assertThat(ctx.containsBean("simpleComponent")).as("@ComponentScan annotated @Configuration class registered directly against " +
"AnnotationConfigApplicationContext did not trigger component scanning as expected", "AnnotationConfigApplicationContext did not trigger component scanning as expected")
ctx.containsBean("simpleComponent"), is(true)); .isTrue();
} }
@Test @Test
@ -158,10 +157,11 @@ public class ComponentScanAnnotationIntegrationTests {
ctx.refresh(); ctx.refresh();
ctx.getBean(ComponentScanAnnotatedConfig.class); ctx.getBean(ComponentScanAnnotatedConfig.class);
ctx.getBean(TestBean.class); ctx.getBean(TestBean.class);
assertThat("config class bean not found", ctx.containsBeanDefinition("componentScanAnnotatedConfig"), is(true)); assertThat(ctx.containsBeanDefinition("componentScanAnnotatedConfig")).as("config class bean not found")
assertThat("@ComponentScan annotated @Configuration class registered " + .isTrue();
"as bean definition did not trigger component scanning as expected", assertThat(ctx.containsBean("fooServiceImpl")).as("@ComponentScan annotated @Configuration class registered as bean " +
ctx.containsBean("fooServiceImpl"), is(true)); "definition did not trigger component scanning as expected")
.isTrue();
} }
@Test @Test
@ -169,8 +169,8 @@ public class ComponentScanAnnotationIntegrationTests {
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(); AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
ctx.register(ComponentScanWithBeanNameGenerator.class); ctx.register(ComponentScanWithBeanNameGenerator.class);
ctx.refresh(); ctx.refresh();
assertThat(ctx.containsBean("custom_fooServiceImpl"), is(true)); assertThat(ctx.containsBean("custom_fooServiceImpl")).isTrue();
assertThat(ctx.containsBean("fooServiceImpl"), is(false)); assertThat(ctx.containsBean("fooServiceImpl")).isFalse();
} }
@Test @Test
@ -178,15 +178,15 @@ public class ComponentScanAnnotationIntegrationTests {
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(ComponentScanWithScopeResolver.class); AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(ComponentScanWithScopeResolver.class);
// custom scope annotation makes the bean prototype scoped. subsequent calls // custom scope annotation makes the bean prototype scoped. subsequent calls
// to getBean should return distinct instances. // to getBean should return distinct instances.
assertThat(ctx.getBean(CustomScopeAnnotationBean.class), not(sameInstance(ctx.getBean(CustomScopeAnnotationBean.class)))); assertThat(ctx.getBean(CustomScopeAnnotationBean.class)).isNotSameAs(ctx.getBean(CustomScopeAnnotationBean.class));
assertThat(ctx.containsBean("scannedComponent"), is(false)); assertThat(ctx.containsBean("scannedComponent")).isFalse();
} }
@Test @Test
public void multiComponentScan() { public void multiComponentScan() {
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(MultiComponentScan.class); AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(MultiComponentScan.class);
assertThat(ctx.getBean(CustomScopeAnnotationBean.class), not(sameInstance(ctx.getBean(CustomScopeAnnotationBean.class)))); assertThat(ctx.getBean(CustomScopeAnnotationBean.class)).isNotSameAs(ctx.getBean(CustomScopeAnnotationBean.class));
assertThat(ctx.containsBean("scannedComponent"), is(true)); assertThat(ctx.containsBean("scannedComponent")).isTrue();
} }
@Test @Test
@ -194,7 +194,7 @@ public class ComponentScanAnnotationIntegrationTests {
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(ComponentScanWithCustomTypeFilter.class); AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(ComponentScanWithCustomTypeFilter.class);
assertFalse(ctx.getDefaultListableBeanFactory().containsSingleton("componentScanParserTests.KustomAnnotationAutowiredBean")); assertFalse(ctx.getDefaultListableBeanFactory().containsSingleton("componentScanParserTests.KustomAnnotationAutowiredBean"));
KustomAnnotationAutowiredBean testBean = ctx.getBean("componentScanParserTests.KustomAnnotationAutowiredBean", KustomAnnotationAutowiredBean.class); KustomAnnotationAutowiredBean testBean = ctx.getBean("componentScanParserTests.KustomAnnotationAutowiredBean", KustomAnnotationAutowiredBean.class);
assertThat(testBean.getDependency(), notNullValue()); assertThat(testBean.getDependency()).isNotNull();
} }
@Test @Test
@ -212,12 +212,12 @@ public class ComponentScanAnnotationIntegrationTests {
// should cast to the interface // should cast to the interface
FooService bean = (FooService) ctx.getBean("scopedProxyTestBean"); FooService bean = (FooService) ctx.getBean("scopedProxyTestBean");
// should be dynamic proxy // should be dynamic proxy
assertThat(AopUtils.isJdkDynamicProxy(bean), is(true)); assertThat(AopUtils.isJdkDynamicProxy(bean)).isTrue();
// test serializability // test serializability
assertThat(bean.foo(1), equalTo("bar")); assertThat(bean.foo(1)).isEqualTo("bar");
FooService deserialized = (FooService) SerializationTestUtils.serializeAndDeserialize(bean); FooService deserialized = (FooService) SerializationTestUtils.serializeAndDeserialize(bean);
assertThat(deserialized, notNullValue()); assertThat(deserialized).isNotNull();
assertThat(deserialized.foo(1), equalTo("bar")); assertThat(deserialized.foo(1)).isEqualTo("bar");
} }
@Test @Test
@ -229,7 +229,7 @@ public class ComponentScanAnnotationIntegrationTests {
// should cast to the interface // should cast to the interface
FooService bean = (FooService) ctx.getBean("scopedProxyTestBean"); FooService bean = (FooService) ctx.getBean("scopedProxyTestBean");
// should be dynamic proxy // should be dynamic proxy
assertThat(AopUtils.isJdkDynamicProxy(bean), is(true)); assertThat(AopUtils.isJdkDynamicProxy(bean)).isTrue();
} }
@Test @Test
@ -241,7 +241,7 @@ public class ComponentScanAnnotationIntegrationTests {
// should cast to the interface // should cast to the interface
FooService bean = (FooService) ctx.getBean("scopedProxyTestBean"); FooService bean = (FooService) ctx.getBean("scopedProxyTestBean");
// should be dynamic proxy // should be dynamic proxy
assertThat(AopUtils.isJdkDynamicProxy(bean), is(true)); assertThat(AopUtils.isJdkDynamicProxy(bean)).isTrue();
} }
@Test @Test
@ -267,7 +267,7 @@ public class ComponentScanAnnotationIntegrationTests {
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(); AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
ctx.register(ComponentScanWithBasePackagesAndValueAlias.class); ctx.register(ComponentScanWithBasePackagesAndValueAlias.class);
ctx.refresh(); ctx.refresh();
assertThat(ctx.containsBean("fooServiceImpl"), is(true)); assertThat(ctx.containsBean("fooServiceImpl")).isTrue();
} }

View File

@ -23,8 +23,8 @@ import org.springframework.context.annotation.componentscan.level1.Level1Config;
import org.springframework.context.annotation.componentscan.level2.Level2Config; import org.springframework.context.annotation.componentscan.level2.Level2Config;
import org.springframework.context.annotation.componentscan.level3.Level3Component; import org.springframework.context.annotation.componentscan.level3.Level3Component;
import static org.hamcrest.CoreMatchers.sameInstance; import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.MatcherAssert.assertThat;
/** /**
* Tests ensuring that configuration classes marked with @ComponentScan * Tests ensuring that configuration classes marked with @ComponentScan
@ -47,8 +47,8 @@ public class ComponentScanAnnotationRecursionTests {
ctx.getBean(Level3Component.class); ctx.getBean(Level3Component.class);
// assert that enhancement is working // assert that enhancement is working
assertThat(ctx.getBean("level1Bean"), sameInstance(ctx.getBean("level1Bean"))); assertThat(ctx.getBean("level1Bean")).isSameAs(ctx.getBean("level1Bean"));
assertThat(ctx.getBean("level2Bean"), sameInstance(ctx.getBean("level2Bean"))); assertThat(ctx.getBean("level2Bean")).isSameAs(ctx.getBean("level2Bean"));
} }
public void evenCircularScansAreSupported() { public void evenCircularScansAreSupported() {

View File

@ -33,8 +33,7 @@ import org.springframework.core.type.classreading.MetadataReader;
import org.springframework.core.type.classreading.MetadataReaderFactory; import org.springframework.core.type.classreading.MetadataReaderFactory;
import org.springframework.core.type.filter.TypeFilter; import org.springframework.core.type.filter.TypeFilter;
import static org.hamcrest.CoreMatchers.is; import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNotNull;
@ -127,7 +126,7 @@ public class ComponentScanParserTests {
GenericXmlApplicationContext context = new GenericXmlApplicationContext(); GenericXmlApplicationContext context = new GenericXmlApplicationContext();
context.load(xmlLocation); context.load(xmlLocation);
context.refresh(); context.refresh();
assertThat(context.containsBean(ProfileAnnotatedComponent.BEAN_NAME), is(false)); assertThat(context.containsBean(ProfileAnnotatedComponent.BEAN_NAME)).isFalse();
context.close(); context.close();
} }
{ // should include the profile-annotated bean with active profiles set { // should include the profile-annotated bean with active profiles set
@ -135,7 +134,7 @@ public class ComponentScanParserTests {
context.getEnvironment().setActiveProfiles(ProfileAnnotatedComponent.PROFILE_NAME); context.getEnvironment().setActiveProfiles(ProfileAnnotatedComponent.PROFILE_NAME);
context.load(xmlLocation); context.load(xmlLocation);
context.refresh(); context.refresh();
assertThat(context.containsBean(ProfileAnnotatedComponent.BEAN_NAME), is(true)); assertThat(context.containsBean(ProfileAnnotatedComponent.BEAN_NAME)).isTrue();
context.close(); context.close();
} }
{ // ensure the same works for AbstractRefreshableApplicationContext impls too { // ensure the same works for AbstractRefreshableApplicationContext impls too
@ -143,7 +142,7 @@ public class ComponentScanParserTests {
false); false);
context.getEnvironment().setActiveProfiles(ProfileAnnotatedComponent.PROFILE_NAME); context.getEnvironment().setActiveProfiles(ProfileAnnotatedComponent.PROFILE_NAME);
context.refresh(); context.refresh();
assertThat(context.containsBean(ProfileAnnotatedComponent.BEAN_NAME), is(true)); assertThat(context.containsBean(ProfileAnnotatedComponent.BEAN_NAME)).isTrue();
context.close(); context.close();
} }
} }

View File

@ -24,11 +24,8 @@ import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.tests.sample.beans.TestBean; import org.springframework.tests.sample.beans.TestBean;
import static org.hamcrest.CoreMatchers.not; import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.CoreMatchers.notNullValue;
import static org.hamcrest.CoreMatchers.nullValue;
import static org.hamcrest.CoreMatchers.sameInstance;
import static org.hamcrest.MatcherAssert.assertThat;
/** /**
* Tests semantics of declaring {@link BeanFactoryPostProcessor}-returning @Bean * Tests semantics of declaring {@link BeanFactoryPostProcessor}-returning @Bean
@ -47,7 +44,7 @@ public class ConfigurationClassAndBFPPTests {
ctx.refresh(); ctx.refresh();
// instance method BFPP interferes with lifecycle -> autowiring fails! // instance method BFPP interferes with lifecycle -> autowiring fails!
// WARN-level logging should have been issued about returning BFPP from non-static @Bean method // WARN-level logging should have been issued about returning BFPP from non-static @Bean method
assertThat(ctx.getBean(AutowiredConfigWithBFPPAsInstanceMethod.class).autowiredTestBean, nullValue()); assertThat(ctx.getBean(AutowiredConfigWithBFPPAsInstanceMethod.class).autowiredTestBean).isNull();
} }
@Test @Test
@ -56,7 +53,7 @@ public class ConfigurationClassAndBFPPTests {
ctx.register(TestBeanConfig.class, AutowiredConfigWithBFPPAsStaticMethod.class); ctx.register(TestBeanConfig.class, AutowiredConfigWithBFPPAsStaticMethod.class);
ctx.refresh(); ctx.refresh();
// static method BFPP does not interfere with lifecycle -> autowiring succeeds // static method BFPP does not interfere with lifecycle -> autowiring succeeds
assertThat(ctx.getBean(AutowiredConfigWithBFPPAsStaticMethod.class).autowiredTestBean, notNullValue()); assertThat(ctx.getBean(AutowiredConfigWithBFPPAsStaticMethod.class).autowiredTestBean).isNotNull();
} }
@ -106,7 +103,7 @@ public class ConfigurationClassAndBFPPTests {
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(); AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
ctx.register(ConfigWithStaticBeanMethod.class); ctx.register(ConfigWithStaticBeanMethod.class);
ctx.refresh(); ctx.refresh();
assertThat(ConfigWithStaticBeanMethod.testBean(), not(sameInstance(ConfigWithStaticBeanMethod.testBean()))); assertThat(ConfigWithStaticBeanMethod.testBean()).isNotSameAs(ConfigWithStaticBeanMethod.testBean());
} }

View File

@ -23,8 +23,8 @@ import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.tests.sample.beans.TestBean; import org.springframework.tests.sample.beans.TestBean;
import static org.hamcrest.CoreMatchers.is; import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.MatcherAssert.assertThat;
/** /**
* Tests cornering the issue reported in SPR-8080. If the product of a @Bean method * Tests cornering the issue reported in SPR-8080. If the product of a @Bean method
@ -56,7 +56,7 @@ public class ConfigurationClassPostConstructAndAutowiringTests {
assertions(ctx); assertions(ctx);
Config2 config2 = ctx.getBean(Config2.class); Config2 config2 = ctx.getBean(Config2.class);
assertThat(config2.testBean, is(ctx.getBean(TestBean.class))); assertThat(config2.testBean).isEqualTo(ctx.getBean(TestBean.class));
} }
/** /**
@ -75,8 +75,8 @@ public class ConfigurationClassPostConstructAndAutowiringTests {
private void assertions(AnnotationConfigApplicationContext ctx) { private void assertions(AnnotationConfigApplicationContext ctx) {
Config1 config1 = ctx.getBean(Config1.class); Config1 config1 = ctx.getBean(Config1.class);
TestBean testBean = ctx.getBean(TestBean.class); TestBean testBean = ctx.getBean(TestBean.class);
assertThat(config1.beanMethodCallCount, is(1)); assertThat(config1.beanMethodCallCount).isEqualTo(1);
assertThat(testBean.getAge(), is(2)); assertThat(testBean.getAge()).isEqualTo(2);
} }

View File

@ -31,8 +31,7 @@ import org.springframework.core.type.AnnotatedTypeMetadata;
import org.springframework.core.type.AnnotationMetadata; import org.springframework.core.type.AnnotationMetadata;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import static org.hamcrest.MatcherAssert.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertTrue;
@ -248,7 +247,7 @@ public class ConfigurationClassWithConditionTests {
@Override @Override
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) { public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
AnnotationAttributes attributes = AnnotationAttributes.fromMap(metadata.getAnnotationAttributes(MetaConditional.class.getName())); AnnotationAttributes attributes = AnnotationAttributes.fromMap(metadata.getAnnotationAttributes(MetaConditional.class.getName()));
assertThat(attributes.getString("value"), equalTo("test")); assertThat(attributes.getString("value")).isEqualTo("test");
return true; return true;
} }
} }

View File

@ -24,8 +24,8 @@ import org.springframework.beans.factory.DisposableBean;
import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.support.GenericXmlApplicationContext; import org.springframework.context.support.GenericXmlApplicationContext;
import static org.hamcrest.CoreMatchers.is; import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.MatcherAssert.assertThat;
/** /**
* @author Chris Beams * @author Chris Beams
@ -48,27 +48,27 @@ public class DestroyMethodInferenceTests {
WithInheritedCloseMethod c8 = ctx.getBean("c8", WithInheritedCloseMethod.class); WithInheritedCloseMethod c8 = ctx.getBean("c8", WithInheritedCloseMethod.class);
WithDisposableBean c9 = ctx.getBean("c9", WithDisposableBean.class); WithDisposableBean c9 = ctx.getBean("c9", WithDisposableBean.class);
assertThat(c0.closed, is(false)); assertThat(c0.closed).as("c0").isFalse();
assertThat(c1.closed, is(false)); assertThat(c1.closed).as("c1").isFalse();
assertThat(c2.closed, is(false)); assertThat(c2.closed).as("c2").isFalse();
assertThat(c3.closed, is(false)); assertThat(c3.closed).as("c3").isFalse();
assertThat(c4.closed, is(false)); assertThat(c4.closed).as("c4").isFalse();
assertThat(c5.closed, is(false)); assertThat(c5.closed).as("c5").isFalse();
assertThat(c6.closed, is(false)); assertThat(c6.closed).as("c6").isFalse();
assertThat(c7.closed, is(false)); assertThat(c7.closed).as("c7").isFalse();
assertThat(c8.closed, is(false)); assertThat(c8.closed).as("c8").isFalse();
assertThat(c9.closed, is(false)); assertThat(c9.closed).as("c9").isFalse();
ctx.close(); ctx.close();
assertThat("c0", c0.closed, is(true)); assertThat(c0.closed).as("c0").isTrue();
assertThat("c1", c1.closed, is(true)); assertThat(c1.closed).as("c1").isTrue();
assertThat("c2", c2.closed, is(true)); assertThat(c2.closed).as("c2").isTrue();
assertThat("c3", c3.closed, is(true)); assertThat(c3.closed).as("c3").isTrue();
assertThat("c4", c4.closed, is(true)); assertThat(c4.closed).as("c4").isTrue();
assertThat("c5", c5.closed, is(true)); assertThat(c5.closed).as("c5").isTrue();
assertThat("c6", c6.closed, is(false)); assertThat(c6.closed).as("c6").isFalse();
assertThat("c7", c7.closed, is(true)); assertThat(c7.closed).as("c7").isTrue();
assertThat("c8", c8.closed, is(false)); assertThat(c8.closed).as("c8").isFalse();
assertThat("c9", c9.closed, is(true)); assertThat(c9.closed).as("c9").isTrue();
} }
@Test @Test
@ -81,16 +81,16 @@ public class DestroyMethodInferenceTests {
WithNoCloseMethod x4 = ctx.getBean("x4", WithNoCloseMethod.class); WithNoCloseMethod x4 = ctx.getBean("x4", WithNoCloseMethod.class);
WithInheritedCloseMethod x8 = ctx.getBean("x8", WithInheritedCloseMethod.class); WithInheritedCloseMethod x8 = ctx.getBean("x8", WithInheritedCloseMethod.class);
assertThat(x1.closed, is(false)); assertThat(x1.closed).isFalse();
assertThat(x2.closed, is(false)); assertThat(x2.closed).isFalse();
assertThat(x3.closed, is(false)); assertThat(x3.closed).isFalse();
assertThat(x4.closed, is(false)); assertThat(x4.closed).isFalse();
ctx.close(); ctx.close();
assertThat(x1.closed, is(false)); assertThat(x1.closed).isFalse();
assertThat(x2.closed, is(true)); assertThat(x2.closed).isTrue();
assertThat(x3.closed, is(true)); assertThat(x3.closed).isTrue();
assertThat(x4.closed, is(false)); assertThat(x4.closed).isFalse();
assertThat(x8.closed, is(false)); assertThat(x8.closed).isFalse();
} }

View File

@ -32,8 +32,7 @@ import org.springframework.aop.support.AopUtils;
import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContext;
import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.ConfigurableApplicationContext;
import static org.hamcrest.CoreMatchers.is; import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertTrue;
@ -49,7 +48,7 @@ public class EnableAspectJAutoProxyTests {
ApplicationContext ctx = new AnnotationConfigApplicationContext(ConfigWithJdkProxy.class); ApplicationContext ctx = new AnnotationConfigApplicationContext(ConfigWithJdkProxy.class);
aspectIsApplied(ctx); aspectIsApplied(ctx);
assertThat(AopUtils.isJdkDynamicProxy(ctx.getBean(FooService.class)), is(true)); assertThat(AopUtils.isJdkDynamicProxy(ctx.getBean(FooService.class))).isTrue();
} }
@Test @Test
@ -57,7 +56,7 @@ public class EnableAspectJAutoProxyTests {
ApplicationContext ctx = new AnnotationConfigApplicationContext(ConfigWithCglibProxy.class); ApplicationContext ctx = new AnnotationConfigApplicationContext(ConfigWithCglibProxy.class);
aspectIsApplied(ctx); aspectIsApplied(ctx);
assertThat(AopUtils.isCglibProxy(ctx.getBean(FooService.class)), is(true)); assertThat(AopUtils.isCglibProxy(ctx.getBean(FooService.class))).isTrue();
} }
@Test @Test
@ -65,7 +64,7 @@ public class EnableAspectJAutoProxyTests {
ApplicationContext ctx = new AnnotationConfigApplicationContext(ConfigWithExposedProxy.class); ApplicationContext ctx = new AnnotationConfigApplicationContext(ConfigWithExposedProxy.class);
aspectIsApplied(ctx); aspectIsApplied(ctx);
assertThat(AopUtils.isJdkDynamicProxy(ctx.getBean(FooService.class)), is(true)); assertThat(AopUtils.isJdkDynamicProxy(ctx.getBean(FooService.class))).isTrue();
} }
private void aspectIsApplied(ApplicationContext ctx) { private void aspectIsApplied(ApplicationContext ctx) {

View File

@ -36,9 +36,7 @@ import org.springframework.core.type.StandardAnnotationMetadata;
import org.springframework.scheduling.annotation.AsyncAnnotationBeanPostProcessor; import org.springframework.scheduling.annotation.AsyncAnnotationBeanPostProcessor;
import org.springframework.util.Assert; import org.springframework.util.Assert;
import static org.hamcrest.CoreMatchers.is; import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.CoreMatchers.notNullValue;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNotNull;
@ -61,11 +59,11 @@ public class ImportAwareTests {
ImportedConfig importAwareConfig = ctx.getBean(ImportedConfig.class); ImportedConfig importAwareConfig = ctx.getBean(ImportedConfig.class);
AnnotationMetadata importMetadata = importAwareConfig.importMetadata; AnnotationMetadata importMetadata = importAwareConfig.importMetadata;
assertThat("import metadata was not injected", importMetadata, notNullValue()); assertThat(importMetadata).isNotNull();
assertThat(importMetadata.getClassName(), is(ImportingConfig.class.getName())); assertThat(importMetadata.getClassName()).isEqualTo(ImportingConfig.class.getName());
AnnotationAttributes importAttribs = AnnotationConfigUtils.attributesFor(importMetadata, Import.class); AnnotationAttributes importAttribs = AnnotationConfigUtils.attributesFor(importMetadata, Import.class);
Class<?>[] importedClasses = importAttribs.getClassArray("value"); Class<?>[] importedClasses = importAttribs.getClassArray("value");
assertThat(importedClasses[0].getName(), is(ImportedConfig.class.getName())); assertThat(importedClasses[0].getName()).isEqualTo(ImportedConfig.class.getName());
} }
@Test @Test
@ -77,11 +75,11 @@ public class ImportAwareTests {
ImportedConfig importAwareConfig = ctx.getBean(ImportedConfig.class); ImportedConfig importAwareConfig = ctx.getBean(ImportedConfig.class);
AnnotationMetadata importMetadata = importAwareConfig.importMetadata; AnnotationMetadata importMetadata = importAwareConfig.importMetadata;
assertThat("import metadata was not injected", importMetadata, notNullValue()); assertThat(importMetadata).isNotNull();
assertThat(importMetadata.getClassName(), is(IndirectlyImportingConfig.class.getName())); assertThat(importMetadata.getClassName()).isEqualTo(IndirectlyImportingConfig.class.getName());
AnnotationAttributes enableAttribs = AnnotationConfigUtils.attributesFor(importMetadata, EnableImportedConfig.class); AnnotationAttributes enableAttribs = AnnotationConfigUtils.attributesFor(importMetadata, EnableImportedConfig.class);
String foo = enableAttribs.getString("foo"); String foo = enableAttribs.getString("foo");
assertThat(foo, is("xyz")); assertThat(foo).isEqualTo("xyz");
} }
@Test @Test
@ -93,11 +91,11 @@ public class ImportAwareTests {
ImportedConfigLite importAwareConfig = ctx.getBean(ImportedConfigLite.class); ImportedConfigLite importAwareConfig = ctx.getBean(ImportedConfigLite.class);
AnnotationMetadata importMetadata = importAwareConfig.importMetadata; AnnotationMetadata importMetadata = importAwareConfig.importMetadata;
assertThat("import metadata was not injected", importMetadata, notNullValue()); assertThat(importMetadata).isNotNull();
assertThat(importMetadata.getClassName(), is(ImportingConfigLite.class.getName())); assertThat(importMetadata.getClassName()).isEqualTo(ImportingConfigLite.class.getName());
AnnotationAttributes importAttribs = AnnotationConfigUtils.attributesFor(importMetadata, Import.class); AnnotationAttributes importAttribs = AnnotationConfigUtils.attributesFor(importMetadata, Import.class);
Class<?>[] importedClasses = importAttribs.getClassArray("value"); Class<?>[] importedClasses = importAttribs.getClassArray("value");
assertThat(importedClasses[0].getName(), is(ImportedConfigLite.class.getName())); assertThat(importedClasses[0].getName()).isEqualTo(ImportedConfigLite.class.getName());
} }
@Test @Test

View File

@ -35,9 +35,8 @@ import org.springframework.core.env.Environment;
import org.springframework.core.io.ResourceLoader; import org.springframework.core.io.ResourceLoader;
import org.springframework.core.type.AnnotationMetadata; import org.springframework.core.type.AnnotationMetadata;
import static org.hamcrest.CoreMatchers.is; import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.CoreMatchers.notNullValue;
import static org.hamcrest.MatcherAssert.assertThat;
/** /**
* Integration tests for {@link ImportBeanDefinitionRegistrar}. * Integration tests for {@link ImportBeanDefinitionRegistrar}.
@ -52,10 +51,10 @@ public class ImportBeanDefinitionRegistrarTests {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(Config.class); AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(Config.class);
context.getBean(MessageSource.class); context.getBean(MessageSource.class);
assertThat(SampleRegistrar.beanFactory, is(context.getBeanFactory())); assertThat(SampleRegistrar.beanFactory).isEqualTo(context.getBeanFactory());
assertThat(SampleRegistrar.classLoader, is(context.getBeanFactory().getBeanClassLoader())); assertThat(SampleRegistrar.classLoader).isEqualTo(context.getBeanFactory().getBeanClassLoader());
assertThat(SampleRegistrar.resourceLoader, is(notNullValue())); assertThat(SampleRegistrar.resourceLoader).isNotNull();
assertThat(SampleRegistrar.environment, is(context.getEnvironment())); assertThat(SampleRegistrar.environment).isEqualTo(context.getEnvironment());
} }

View File

@ -31,8 +31,6 @@ import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import org.hamcrest.Matcher;
import org.hamcrest.collection.IsIterableContainingInOrder;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import org.mockito.InOrder; import org.mockito.InOrder;
@ -53,11 +51,7 @@ import org.springframework.lang.Nullable;
import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap; import org.springframework.util.MultiValueMap;
import static org.hamcrest.MatcherAssert.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasEntry;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.notNullValue;
import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq; import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.inOrder; import static org.mockito.Mockito.inOrder;
@ -100,20 +94,20 @@ public class ImportSelectorTests {
@Test @Test
public void invokeAwareMethodsInImportSelector() { public void invokeAwareMethodsInImportSelector() {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AwareConfig.class); AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AwareConfig.class);
assertThat(SampleImportSelector.beanFactory, is(context.getBeanFactory())); assertThat(SampleImportSelector.beanFactory).isEqualTo(context.getBeanFactory());
assertThat(SampleImportSelector.classLoader, is(context.getBeanFactory().getBeanClassLoader())); assertThat(SampleImportSelector.classLoader).isEqualTo(context.getBeanFactory().getBeanClassLoader());
assertThat(SampleImportSelector.resourceLoader, is(notNullValue())); assertThat(SampleImportSelector.resourceLoader).isNotNull();
assertThat(SampleImportSelector.environment, is(context.getEnvironment())); assertThat(SampleImportSelector.environment).isEqualTo(context.getEnvironment());
} }
@Test @Test
public void correctMetaDataOnIndirectImports() { public void correctMetaDataOnIndirectImports() {
new AnnotationConfigApplicationContext(IndirectConfig.class); new AnnotationConfigApplicationContext(IndirectConfig.class);
Matcher<String> isFromIndirect = equalTo(IndirectImport.class.getName()); String indirectImport = IndirectImport.class.getName();
assertThat(importFrom.get(ImportSelector1.class), isFromIndirect); assertThat(importFrom.get(ImportSelector1.class)).isEqualTo(indirectImport);
assertThat(importFrom.get(ImportSelector2.class), isFromIndirect); assertThat(importFrom.get(ImportSelector2.class)).isEqualTo(indirectImport);
assertThat(importFrom.get(DeferredImportSelector1.class), isFromIndirect); assertThat(importFrom.get(DeferredImportSelector1.class)).isEqualTo(indirectImport);
assertThat(importFrom.get(DeferredImportSelector2.class), isFromIndirect); assertThat(importFrom.get(DeferredImportSelector2.class)).isEqualTo(indirectImport);
} }
@Test @Test
@ -127,9 +121,9 @@ public class ImportSelectorTests {
ordered.verify(beanFactory).registerBeanDefinition(eq("b"), any()); ordered.verify(beanFactory).registerBeanDefinition(eq("b"), any());
ordered.verify(beanFactory).registerBeanDefinition(eq("c"), any()); ordered.verify(beanFactory).registerBeanDefinition(eq("c"), any());
ordered.verify(beanFactory).registerBeanDefinition(eq("d"), any()); ordered.verify(beanFactory).registerBeanDefinition(eq("d"), any());
assertThat(TestImportGroup.instancesCount.get(), equalTo(1)); assertThat(TestImportGroup.instancesCount.get()).isEqualTo(1);
assertThat(TestImportGroup.imports.size(), equalTo(1)); assertThat(TestImportGroup.imports.size()).isEqualTo(1);
assertThat(TestImportGroup.imports.values().iterator().next().size(), equalTo(2)); assertThat(TestImportGroup.imports.values().iterator().next().size()).isEqualTo(2);
} }
@Test @Test
@ -142,11 +136,11 @@ public class ImportSelectorTests {
InOrder ordered = inOrder(beanFactory); InOrder ordered = inOrder(beanFactory);
ordered.verify(beanFactory).registerBeanDefinition(eq("c"), any()); ordered.verify(beanFactory).registerBeanDefinition(eq("c"), any());
ordered.verify(beanFactory).registerBeanDefinition(eq("d"), any()); ordered.verify(beanFactory).registerBeanDefinition(eq("d"), any());
assertThat(TestImportGroup.instancesCount.get(), equalTo(1)); assertThat(TestImportGroup.instancesCount.get()).isEqualTo(1);
assertThat(TestImportGroup.imports.size(), equalTo(2)); assertThat(TestImportGroup.imports.size()).isEqualTo(2);
Iterator<AnnotationMetadata> iterator = TestImportGroup.imports.keySet().iterator(); Iterator<AnnotationMetadata> iterator = TestImportGroup.imports.keySet().iterator();
assertThat(iterator.next().getClassName(), equalTo(GroupedConfig2.class.getName())); assertThat(iterator.next().getClassName()).isEqualTo(GroupedConfig2.class.getName());
assertThat(iterator.next().getClassName(), equalTo(GroupedConfig1.class.getName())); assertThat(iterator.next().getClassName()).isEqualTo(GroupedConfig1.class.getName());
} }
@Test @Test
@ -159,15 +153,14 @@ public class ImportSelectorTests {
ordered.verify(beanFactory).registerBeanDefinition(eq("a"), any()); ordered.verify(beanFactory).registerBeanDefinition(eq("a"), any());
ordered.verify(beanFactory).registerBeanDefinition(eq("e"), any()); ordered.verify(beanFactory).registerBeanDefinition(eq("e"), any());
ordered.verify(beanFactory).registerBeanDefinition(eq("c"), any()); ordered.verify(beanFactory).registerBeanDefinition(eq("c"), any());
assertThat(TestImportGroup.instancesCount.get(), equalTo(2)); assertThat(TestImportGroup.instancesCount.get()).isEqualTo(2);
assertThat(TestImportGroup.imports.size(), equalTo(2)); assertThat(TestImportGroup.imports.size()).isEqualTo(2);
assertThat(TestImportGroup.allImports(), hasEntry( assertThat(TestImportGroup.allImports())
is(ParentConfiguration1.class.getName()), .containsOnlyKeys(ParentConfiguration1.class.getName(), ChildConfiguration1.class.getName());
IsIterableContainingInOrder.contains(DeferredImportSelector1.class.getName(), assertThat(TestImportGroup.allImports().get(ParentConfiguration1.class.getName()))
ChildConfiguration1.class.getName()))); .containsExactly(DeferredImportSelector1.class.getName(), ChildConfiguration1.class.getName());
assertThat(TestImportGroup.allImports(), hasEntry( assertThat(TestImportGroup.allImports().get(ChildConfiguration1.class.getName()))
is(ChildConfiguration1.class.getName()), .containsExactly(DeferredImportedSelector3.class.getName());
IsIterableContainingInOrder.contains(DeferredImportedSelector3.class.getName())));
} }
@Test @Test
@ -179,24 +172,23 @@ public class ImportSelectorTests {
InOrder ordered = inOrder(beanFactory); InOrder ordered = inOrder(beanFactory);
ordered.verify(beanFactory).registerBeanDefinition(eq("b"), any()); ordered.verify(beanFactory).registerBeanDefinition(eq("b"), any());
ordered.verify(beanFactory).registerBeanDefinition(eq("d"), any()); ordered.verify(beanFactory).registerBeanDefinition(eq("d"), any());
assertThat(TestImportGroup.instancesCount.get(), equalTo(2)); assertThat(TestImportGroup.instancesCount.get()).isEqualTo(2);
assertThat(TestImportGroup.allImports().size(), equalTo(2)); assertThat(TestImportGroup.allImports().size()).isEqualTo(2);
assertThat(TestImportGroup.allImports(), hasEntry( assertThat(TestImportGroup.allImports())
is(ParentConfiguration2.class.getName()), .containsOnlyKeys(ParentConfiguration2.class.getName(), ChildConfiguration2.class.getName());
IsIterableContainingInOrder.contains(DeferredImportSelector2.class.getName(), assertThat(TestImportGroup.allImports().get(ParentConfiguration2.class.getName()))
ChildConfiguration2.class.getName()))); .containsExactly(DeferredImportSelector2.class.getName(), ChildConfiguration2.class.getName());
assertThat(TestImportGroup.allImports(), hasEntry( assertThat(TestImportGroup.allImports().get(ChildConfiguration2.class.getName()))
is(ChildConfiguration2.class.getName()), .containsExactly(DeferredImportSelector2.class.getName());
IsIterableContainingInOrder.contains(DeferredImportSelector2.class.getName())));
} }
@Test @Test
public void invokeAwareMethodsInImportGroup() { public void invokeAwareMethodsInImportGroup() {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(GroupedConfig1.class); AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(GroupedConfig1.class);
assertThat(TestImportGroup.beanFactory, is(context.getBeanFactory())); assertThat(TestImportGroup.beanFactory).isEqualTo(context.getBeanFactory());
assertThat(TestImportGroup.classLoader, is(context.getBeanFactory().getBeanClassLoader())); assertThat(TestImportGroup.classLoader).isEqualTo(context.getBeanFactory().getBeanClassLoader());
assertThat(TestImportGroup.resourceLoader, is(notNullValue())); assertThat(TestImportGroup.resourceLoader).isNotNull();
assertThat(TestImportGroup.environment, is(context.getEnvironment())); assertThat(TestImportGroup.environment).isEqualTo(context.getEnvironment());
} }

View File

@ -21,8 +21,7 @@ import org.junit.Test;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import org.springframework.tests.sample.beans.TestBean; import org.springframework.tests.sample.beans.TestBean;
import static org.hamcrest.CoreMatchers.is; import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertTrue;
@ -52,7 +51,7 @@ public class NestedConfigurationClassTests {
ctx.getBean("l2Bean"); ctx.getBean("l2Bean");
// ensure that override order is correct // ensure that override order is correct
assertThat(ctx.getBean("overrideBean", TestBean.class).getName(), is("override-l1")); assertThat(ctx.getBean("overrideBean", TestBean.class).getName()).isEqualTo("override-l1");
} }
@Test @Test
@ -74,7 +73,7 @@ public class NestedConfigurationClassTests {
ctx.getBean("l2Bean"); ctx.getBean("l2Bean");
// ensure that override order is correct // ensure that override order is correct
assertThat(ctx.getBean("overrideBean", TestBean.class).getName(), is("override-l0")); assertThat(ctx.getBean("overrideBean", TestBean.class).getName()).isEqualTo("override-l0");
} }
@Test @Test
@ -96,7 +95,7 @@ public class NestedConfigurationClassTests {
ctx.getBean("l2Bean"); ctx.getBean("l2Bean");
// ensure that override order is correct // ensure that override order is correct
assertThat(ctx.getBean("overrideBean", TestBean.class).getName(), is("override-l0")); assertThat(ctx.getBean("overrideBean", TestBean.class).getName()).isEqualTo("override-l0");
} }
@Test @Test
@ -118,7 +117,7 @@ public class NestedConfigurationClassTests {
// ensure that override order is correct and that it is a singleton // ensure that override order is correct and that it is a singleton
TestBean ob = ctx.getBean("overrideBean", TestBean.class); TestBean ob = ctx.getBean("overrideBean", TestBean.class);
assertThat(ob.getName(), is("override-s1")); assertThat(ob.getName()).isEqualTo("override-s1");
assertTrue(ob == ctx.getBean("overrideBean", TestBean.class)); assertTrue(ob == ctx.getBean("overrideBean", TestBean.class));
TestBean pb1 = ctx.getBean("prototypeBean", TestBean.class); TestBean pb1 = ctx.getBean("prototypeBean", TestBean.class);
@ -146,7 +145,7 @@ public class NestedConfigurationClassTests {
// ensure that override order is correct and that it is a singleton // ensure that override order is correct and that it is a singleton
TestBean ob = ctx.getBean("overrideBean", TestBean.class); TestBean ob = ctx.getBean("overrideBean", TestBean.class);
assertThat(ob.getName(), is("override-s1")); assertThat(ob.getName()).isEqualTo("override-s1");
assertTrue(ob == ctx.getBean("overrideBean", TestBean.class)); assertTrue(ob == ctx.getBean("overrideBean", TestBean.class));
TestBean pb1 = ctx.getBean("prototypeBean", TestBean.class); TestBean pb1 = ctx.getBean("prototypeBean", TestBean.class);
@ -174,7 +173,7 @@ public class NestedConfigurationClassTests {
// ensure that override order is correct and that it is a singleton // ensure that override order is correct and that it is a singleton
TestBean ob = ctx.getBean("overrideBean", TestBean.class); TestBean ob = ctx.getBean("overrideBean", TestBean.class);
assertThat(ob.getName(), is("override-s1")); assertThat(ob.getName()).isEqualTo("override-s1");
assertTrue(ob == ctx.getBean("overrideBean", TestBean.class)); assertTrue(ob == ctx.getBean("overrideBean", TestBean.class));
TestBean pb1 = ctx.getBean("prototypeBean", TestBean.class); TestBean pb1 = ctx.getBean("prototypeBean", TestBean.class);

View File

@ -23,8 +23,8 @@ import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContext;
import static org.hamcrest.CoreMatchers.equalTo; import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.MatcherAssert.assertThat;
/** /**
* Tests changes introduced for SPR-8874, allowing beans of primitive types to be looked * Tests changes introduced for SPR-8874, allowing beans of primitive types to be looked
@ -47,34 +47,34 @@ public class PrimitiveBeanLookupAndAutowiringTests {
public void primitiveLookupByName() { public void primitiveLookupByName() {
ApplicationContext ctx = new AnnotationConfigApplicationContext(Config.class); ApplicationContext ctx = new AnnotationConfigApplicationContext(Config.class);
boolean b = ctx.getBean("b", boolean.class); boolean b = ctx.getBean("b", boolean.class);
assertThat(b, equalTo(true)); assertThat(b).isEqualTo(true);
int i = ctx.getBean("i", int.class); int i = ctx.getBean("i", int.class);
assertThat(i, equalTo(42)); assertThat(i).isEqualTo(42);
} }
@Test @Test
public void primitiveLookupByType() { public void primitiveLookupByType() {
ApplicationContext ctx = new AnnotationConfigApplicationContext(Config.class); ApplicationContext ctx = new AnnotationConfigApplicationContext(Config.class);
boolean b = ctx.getBean(boolean.class); boolean b = ctx.getBean(boolean.class);
assertThat(b, equalTo(true)); assertThat(b).isEqualTo(true);
int i = ctx.getBean(int.class); int i = ctx.getBean(int.class);
assertThat(i, equalTo(42)); assertThat(i).isEqualTo(42);
} }
@Test @Test
public void primitiveAutowiredInjection() { public void primitiveAutowiredInjection() {
ApplicationContext ctx = ApplicationContext ctx =
new AnnotationConfigApplicationContext(Config.class, AutowiredComponent.class); new AnnotationConfigApplicationContext(Config.class, AutowiredComponent.class);
assertThat(ctx.getBean(AutowiredComponent.class).b, equalTo(true)); assertThat(ctx.getBean(AutowiredComponent.class).b).isEqualTo(true);
assertThat(ctx.getBean(AutowiredComponent.class).i, equalTo(42)); assertThat(ctx.getBean(AutowiredComponent.class).i).isEqualTo(42);
} }
@Test @Test
public void primitiveResourceInjection() { public void primitiveResourceInjection() {
ApplicationContext ctx = ApplicationContext ctx =
new AnnotationConfigApplicationContext(Config.class, ResourceComponent.class); new AnnotationConfigApplicationContext(Config.class, ResourceComponent.class);
assertThat(ctx.getBean(ResourceComponent.class).b, equalTo(true)); assertThat(ctx.getBean(ResourceComponent.class).b).isEqualTo(true);
assertThat(ctx.getBean(ResourceComponent.class).i, equalTo(42)); assertThat(ctx.getBean(ResourceComponent.class).i).isEqualTo(42);
} }

View File

@ -38,10 +38,8 @@ import org.springframework.core.io.support.PropertiesLoaderUtils;
import org.springframework.core.io.support.PropertySourceFactory; import org.springframework.core.io.support.PropertySourceFactory;
import org.springframework.tests.sample.beans.TestBean; import org.springframework.tests.sample.beans.TestBean;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertTrue;
/** /**
@ -61,7 +59,7 @@ public class PropertySourceAnnotationTests {
ctx.refresh(); ctx.refresh();
assertTrue("property source p1 was not added", assertTrue("property source p1 was not added",
ctx.getEnvironment().getPropertySources().contains("p1")); ctx.getEnvironment().getPropertySources().contains("p1"));
assertThat(ctx.getBean(TestBean.class).getName(), equalTo("p1TestBean")); assertThat(ctx.getBean(TestBean.class).getName()).isEqualTo("p1TestBean");
// assert that the property source was added last to the set of sources // assert that the property source was added last to the set of sources
String name; String name;
@ -72,7 +70,7 @@ public class PropertySourceAnnotationTests {
} }
while (iterator.hasNext()); while (iterator.hasNext());
assertThat(name, is("p1")); assertThat(name).isEqualTo("p1");
} }
@Test @Test
@ -82,7 +80,7 @@ public class PropertySourceAnnotationTests {
ctx.refresh(); ctx.refresh();
assertTrue("property source p1 was not added", assertTrue("property source p1 was not added",
ctx.getEnvironment().getPropertySources().contains("class path resource [org/springframework/context/annotation/p1.properties]")); ctx.getEnvironment().getPropertySources().contains("class path resource [org/springframework/context/annotation/p1.properties]"));
assertThat(ctx.getBean(TestBean.class).getName(), equalTo("p1TestBean")); assertThat(ctx.getBean(TestBean.class).getName()).isEqualTo("p1TestBean");
} }
@Test @Test
@ -105,7 +103,7 @@ public class PropertySourceAnnotationTests {
ctx.register(ConfigWithImplicitName.class, P2Config.class); ctx.register(ConfigWithImplicitName.class, P2Config.class);
ctx.refresh(); ctx.refresh();
// p2 should 'win' as it was registered last // p2 should 'win' as it was registered last
assertThat(ctx.getBean(TestBean.class).getName(), equalTo("p2TestBean")); assertThat(ctx.getBean(TestBean.class).getName()).isEqualTo("p2TestBean");
} }
{ {
@ -113,7 +111,7 @@ public class PropertySourceAnnotationTests {
ctx.register(P2Config.class, ConfigWithImplicitName.class); ctx.register(P2Config.class, ConfigWithImplicitName.class);
ctx.refresh(); ctx.refresh();
// p1 should 'win' as it was registered last // p1 should 'win' as it was registered last
assertThat(ctx.getBean(TestBean.class).getName(), equalTo("p1TestBean")); assertThat(ctx.getBean(TestBean.class).getName()).isEqualTo("p1TestBean");
} }
} }
@ -122,7 +120,7 @@ public class PropertySourceAnnotationTests {
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(); AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
ctx.register(ConfigWithImplicitName.class, WithCustomFactory.class); ctx.register(ConfigWithImplicitName.class, WithCustomFactory.class);
ctx.refresh(); ctx.refresh();
assertThat(ctx.getBean(TestBean.class).getName(), equalTo("P2TESTBEAN")); assertThat(ctx.getBean(TestBean.class).getName()).isEqualTo("P2TESTBEAN");
} }
@Test @Test
@ -130,7 +128,7 @@ public class PropertySourceAnnotationTests {
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(); AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
ctx.register(ConfigWithImplicitName.class, WithCustomFactoryAsMeta.class); ctx.register(ConfigWithImplicitName.class, WithCustomFactoryAsMeta.class);
ctx.refresh(); ctx.refresh();
assertThat(ctx.getBean(TestBean.class).getName(), equalTo("P2TESTBEAN")); assertThat(ctx.getBean(TestBean.class).getName()).isEqualTo("P2TESTBEAN");
} }
@Test @Test
@ -150,7 +148,7 @@ public class PropertySourceAnnotationTests {
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(); AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
ctx.register(ConfigWithUnresolvablePlaceholderAndDefault.class); ctx.register(ConfigWithUnresolvablePlaceholderAndDefault.class);
ctx.refresh(); ctx.refresh();
assertThat(ctx.getBean(TestBean.class).getName(), equalTo("p1TestBean")); assertThat(ctx.getBean(TestBean.class).getName()).isEqualTo("p1TestBean");
} }
@Test @Test
@ -159,7 +157,7 @@ public class PropertySourceAnnotationTests {
ctx.register(ConfigWithResolvablePlaceholder.class); ctx.register(ConfigWithResolvablePlaceholder.class);
System.setProperty("path.to.properties", "org/springframework/context/annotation"); System.setProperty("path.to.properties", "org/springframework/context/annotation");
ctx.refresh(); ctx.refresh();
assertThat(ctx.getBean(TestBean.class).getName(), equalTo("p1TestBean")); assertThat(ctx.getBean(TestBean.class).getName()).isEqualTo("p1TestBean");
System.clearProperty("path.to.properties"); System.clearProperty("path.to.properties");
} }
@ -169,7 +167,7 @@ public class PropertySourceAnnotationTests {
ctx.register(ConfigWithResolvablePlaceholderAndFactoryBean.class); ctx.register(ConfigWithResolvablePlaceholderAndFactoryBean.class);
System.setProperty("path.to.properties", "org/springframework/context/annotation"); System.setProperty("path.to.properties", "org/springframework/context/annotation");
ctx.refresh(); ctx.refresh();
assertThat(ctx.getBean(TestBean.class).getName(), equalTo("p1TestBean")); assertThat(ctx.getBean(TestBean.class).getName()).isEqualTo("p1TestBean");
System.clearProperty("path.to.properties"); System.clearProperty("path.to.properties");
} }
@ -188,37 +186,37 @@ public class PropertySourceAnnotationTests {
@Test @Test
public void withNameAndMultipleResourceLocations() { public void withNameAndMultipleResourceLocations() {
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(ConfigWithNameAndMultipleResourceLocations.class); AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(ConfigWithNameAndMultipleResourceLocations.class);
assertThat(ctx.getEnvironment().containsProperty("from.p1"), is(true)); assertThat(ctx.getEnvironment().containsProperty("from.p1")).isTrue();
assertThat(ctx.getEnvironment().containsProperty("from.p2"), is(true)); assertThat(ctx.getEnvironment().containsProperty("from.p2")).isTrue();
// p2 should 'win' as it was registered last // p2 should 'win' as it was registered last
assertThat(ctx.getEnvironment().getProperty("testbean.name"), equalTo("p2TestBean")); assertThat(ctx.getEnvironment().getProperty("testbean.name")).isEqualTo("p2TestBean");
} }
@Test @Test
public void withMultipleResourceLocations() { public void withMultipleResourceLocations() {
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(ConfigWithMultipleResourceLocations.class); AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(ConfigWithMultipleResourceLocations.class);
assertThat(ctx.getEnvironment().containsProperty("from.p1"), is(true)); assertThat(ctx.getEnvironment().containsProperty("from.p1")).isTrue();
assertThat(ctx.getEnvironment().containsProperty("from.p2"), is(true)); assertThat(ctx.getEnvironment().containsProperty("from.p2")).isTrue();
// p2 should 'win' as it was registered last // p2 should 'win' as it was registered last
assertThat(ctx.getEnvironment().getProperty("testbean.name"), equalTo("p2TestBean")); assertThat(ctx.getEnvironment().getProperty("testbean.name")).isEqualTo("p2TestBean");
} }
@Test @Test
public void withPropertySources() { public void withPropertySources() {
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(ConfigWithPropertySources.class); AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(ConfigWithPropertySources.class);
assertThat(ctx.getEnvironment().containsProperty("from.p1"), is(true)); assertThat(ctx.getEnvironment().containsProperty("from.p1")).isTrue();
assertThat(ctx.getEnvironment().containsProperty("from.p2"), is(true)); assertThat(ctx.getEnvironment().containsProperty("from.p2")).isTrue();
// p2 should 'win' as it was registered last // p2 should 'win' as it was registered last
assertThat(ctx.getEnvironment().getProperty("testbean.name"), equalTo("p2TestBean")); assertThat(ctx.getEnvironment().getProperty("testbean.name")).isEqualTo("p2TestBean");
} }
@Test @Test
public void withNamedPropertySources() { public void withNamedPropertySources() {
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(ConfigWithNamedPropertySources.class); AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(ConfigWithNamedPropertySources.class);
assertThat(ctx.getEnvironment().containsProperty("from.p1"), is(true)); assertThat(ctx.getEnvironment().containsProperty("from.p1")).isTrue();
assertThat(ctx.getEnvironment().containsProperty("from.p2"), is(true)); assertThat(ctx.getEnvironment().containsProperty("from.p2")).isTrue();
// p2 should 'win' as it was registered last // p2 should 'win' as it was registered last
assertThat(ctx.getEnvironment().getProperty("testbean.name"), equalTo("p2TestBean")); assertThat(ctx.getEnvironment().getProperty("testbean.name")).isEqualTo("p2TestBean");
} }
@Test @Test
@ -231,16 +229,16 @@ public class PropertySourceAnnotationTests {
@Test @Test
public void withIgnoredPropertySource() { public void withIgnoredPropertySource() {
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(ConfigWithIgnoredPropertySource.class); AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(ConfigWithIgnoredPropertySource.class);
assertThat(ctx.getEnvironment().containsProperty("from.p1"), is(true)); assertThat(ctx.getEnvironment().containsProperty("from.p1")).isTrue();
assertThat(ctx.getEnvironment().containsProperty("from.p2"), is(true)); assertThat(ctx.getEnvironment().containsProperty("from.p2")).isTrue();
} }
@Test @Test
public void withSameSourceImportedInDifferentOrder() { public void withSameSourceImportedInDifferentOrder() {
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(ConfigWithSameSourceImportedInDifferentOrder.class); AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(ConfigWithSameSourceImportedInDifferentOrder.class);
assertThat(ctx.getEnvironment().containsProperty("from.p1"), is(true)); assertThat(ctx.getEnvironment().containsProperty("from.p1")).isTrue();
assertThat(ctx.getEnvironment().containsProperty("from.p2"), is(true)); assertThat(ctx.getEnvironment().containsProperty("from.p2")).isTrue();
assertThat(ctx.getEnvironment().getProperty("testbean.name"), equalTo("p2TestBean")); assertThat(ctx.getEnvironment().getProperty("testbean.name")).isEqualTo("p2TestBean");
} }
@Test @Test
@ -248,15 +246,15 @@ public class PropertySourceAnnotationTests {
// SPR-10820: p2 should 'win' as it was registered last // SPR-10820: p2 should 'win' as it was registered last
AnnotationConfigApplicationContext ctxWithName = new AnnotationConfigApplicationContext(ConfigWithNameAndMultipleResourceLocations.class); AnnotationConfigApplicationContext ctxWithName = new AnnotationConfigApplicationContext(ConfigWithNameAndMultipleResourceLocations.class);
AnnotationConfigApplicationContext ctxWithoutName = new AnnotationConfigApplicationContext(ConfigWithMultipleResourceLocations.class); AnnotationConfigApplicationContext ctxWithoutName = new AnnotationConfigApplicationContext(ConfigWithMultipleResourceLocations.class);
assertThat(ctxWithoutName.getEnvironment().getProperty("testbean.name"), equalTo("p2TestBean")); assertThat(ctxWithoutName.getEnvironment().getProperty("testbean.name")).isEqualTo("p2TestBean");
assertThat(ctxWithName.getEnvironment().getProperty("testbean.name"), equalTo("p2TestBean")); assertThat(ctxWithName.getEnvironment().getProperty("testbean.name")).isEqualTo("p2TestBean");
} }
@Test @Test
public void orderingWithAndWithoutNameAndFourResourceLocations() { public void orderingWithAndWithoutNameAndFourResourceLocations() {
// SPR-12198: p4 should 'win' as it was registered last // SPR-12198: p4 should 'win' as it was registered last
AnnotationConfigApplicationContext ctxWithoutName = new AnnotationConfigApplicationContext(ConfigWithFourResourceLocations.class); AnnotationConfigApplicationContext ctxWithoutName = new AnnotationConfigApplicationContext(ConfigWithFourResourceLocations.class);
assertThat(ctxWithoutName.getEnvironment().getProperty("testbean.name"), equalTo("p4TestBean")); assertThat(ctxWithoutName.getEnvironment().getProperty("testbean.name")).isEqualTo("p4TestBean");
} }
@Test @Test
@ -267,7 +265,7 @@ public class PropertySourceAnnotationTests {
ctxWithoutName.getEnvironment().getPropertySources().addLast(mySource); ctxWithoutName.getEnvironment().getPropertySources().addLast(mySource);
ctxWithoutName.register(ConfigWithFourResourceLocations.class); ctxWithoutName.register(ConfigWithFourResourceLocations.class);
ctxWithoutName.refresh(); ctxWithoutName.refresh();
assertThat(ctxWithoutName.getEnvironment().getProperty("testbean.name"), equalTo("myTestBean")); assertThat(ctxWithoutName.getEnvironment().getProperty("testbean.name")).isEqualTo("myTestBean");
} }

View File

@ -22,8 +22,7 @@ import org.junit.Test;
import org.springframework.util.ReflectionUtils; import org.springframework.util.ReflectionUtils;
import static org.hamcrest.CoreMatchers.is; import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
/** /**
@ -46,7 +45,7 @@ public class ReflectionUtilsIntegrationTests {
m1MethodCount++; m1MethodCount++;
} }
} }
assertThat(m1MethodCount, is(1)); assertThat(m1MethodCount).isEqualTo(1);
for (Method method : methods) { for (Method method : methods) {
if (method.getName().contains("m1")) { if (method.getName().contains("m1")) {
assertEquals(method.getReturnType(), Integer.class); assertEquals(method.getReturnType(), Integer.class);

View File

@ -22,8 +22,8 @@ import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.role.ComponentWithRole; import org.springframework.context.annotation.role.ComponentWithRole;
import org.springframework.context.annotation.role.ComponentWithoutRole; import org.springframework.context.annotation.role.ComponentWithoutRole;
import static org.hamcrest.CoreMatchers.is; import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.MatcherAssert.assertThat;
/** /**
* Tests the use of the @Role and @Description annotation on @Bean methods and @Component classes. * Tests the use of the @Role and @Description annotation on @Bean methods and @Component classes.
@ -39,12 +39,10 @@ public class RoleAndDescriptionAnnotationTests {
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(); AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
ctx.register(Config.class); ctx.register(Config.class);
ctx.refresh(); ctx.refresh();
assertThat("Expected bean to have ROLE_APPLICATION", assertThat(ctx.getBeanDefinition("foo").getRole()).isEqualTo(BeanDefinition.ROLE_APPLICATION);
ctx.getBeanDefinition("foo").getRole(), is(BeanDefinition.ROLE_APPLICATION)); assertThat(ctx.getBeanDefinition("foo").getDescription()).isNull();
assertThat(ctx.getBeanDefinition("foo").getDescription(), is((Object) null)); assertThat(ctx.getBeanDefinition("bar").getRole()).isEqualTo(BeanDefinition.ROLE_INFRASTRUCTURE);
assertThat("Expected bean to have ROLE_INFRASTRUCTURE", assertThat(ctx.getBeanDefinition("bar").getDescription()).isEqualTo("A Bean method with a role");
ctx.getBeanDefinition("bar").getRole(), is(BeanDefinition.ROLE_INFRASTRUCTURE));
assertThat(ctx.getBeanDefinition("bar").getDescription(), is("A Bean method with a role"));
} }
@Test @Test
@ -52,12 +50,10 @@ public class RoleAndDescriptionAnnotationTests {
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(); AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
ctx.register(ComponentWithoutRole.class, ComponentWithRole.class); ctx.register(ComponentWithoutRole.class, ComponentWithRole.class);
ctx.refresh(); ctx.refresh();
assertThat("Expected bean to have ROLE_APPLICATION", assertThat(ctx.getBeanDefinition("componentWithoutRole").getRole()).isEqualTo(BeanDefinition.ROLE_APPLICATION);
ctx.getBeanDefinition("componentWithoutRole").getRole(), is(BeanDefinition.ROLE_APPLICATION)); assertThat(ctx.getBeanDefinition("componentWithoutRole").getDescription()).isNull();
assertThat(ctx.getBeanDefinition("componentWithoutRole").getDescription(), is((Object) null)); assertThat(ctx.getBeanDefinition("componentWithRole").getRole()).isEqualTo(BeanDefinition.ROLE_INFRASTRUCTURE);
assertThat("Expected bean to have ROLE_INFRASTRUCTURE", assertThat(ctx.getBeanDefinition("componentWithRole").getDescription()).isEqualTo("A Component with a role");
ctx.getBeanDefinition("componentWithRole").getRole(), is(BeanDefinition.ROLE_INFRASTRUCTURE));
assertThat(ctx.getBeanDefinition("componentWithRole").getDescription(), is("A Component with a role"));
} }
@ -66,12 +62,10 @@ public class RoleAndDescriptionAnnotationTests {
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(); AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
ctx.scan("org.springframework.context.annotation.role"); ctx.scan("org.springframework.context.annotation.role");
ctx.refresh(); ctx.refresh();
assertThat("Expected bean to have ROLE_APPLICATION", assertThat(ctx.getBeanDefinition("componentWithoutRole").getRole()).isEqualTo(BeanDefinition.ROLE_APPLICATION);
ctx.getBeanDefinition("componentWithoutRole").getRole(), is(BeanDefinition.ROLE_APPLICATION)); assertThat(ctx.getBeanDefinition("componentWithoutRole").getDescription()).isNull();
assertThat(ctx.getBeanDefinition("componentWithoutRole").getDescription(), is((Object) null)); assertThat(ctx.getBeanDefinition("componentWithRole").getRole()).isEqualTo(BeanDefinition.ROLE_INFRASTRUCTURE);
assertThat("Expected bean to have ROLE_INFRASTRUCTURE", assertThat(ctx.getBeanDefinition("componentWithRole").getDescription()).isEqualTo("A Component with a role");
ctx.getBeanDefinition("componentWithRole").getRole(), is(BeanDefinition.ROLE_INFRASTRUCTURE));
assertThat(ctx.getBeanDefinition("componentWithRole").getDescription(), is("A Component with a role"));
} }

View File

@ -21,9 +21,8 @@ import org.junit.Test;
import org.springframework.beans.factory.BeanCreationException; import org.springframework.beans.factory.BeanCreationException;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.Is.is;
/** /**
* @author Stephane Nicoll * @author Stephane Nicoll
@ -43,14 +42,14 @@ public class Spr12278Tests {
public void componentSingleConstructor() { public void componentSingleConstructor() {
this.context = new AnnotationConfigApplicationContext(BaseConfiguration.class, this.context = new AnnotationConfigApplicationContext(BaseConfiguration.class,
SingleConstructorComponent.class); SingleConstructorComponent.class);
assertThat(this.context.getBean(SingleConstructorComponent.class).autowiredName, is("foo")); assertThat(this.context.getBean(SingleConstructorComponent.class).autowiredName).isEqualTo("foo");
} }
@Test @Test
public void componentTwoConstructorsNoHint() { public void componentTwoConstructorsNoHint() {
this.context = new AnnotationConfigApplicationContext(BaseConfiguration.class, this.context = new AnnotationConfigApplicationContext(BaseConfiguration.class,
TwoConstructorsComponent.class); TwoConstructorsComponent.class);
assertThat(this.context.getBean(TwoConstructorsComponent.class).name, is("fallback")); assertThat(this.context.getBean(TwoConstructorsComponent.class).name).isEqualTo("fallback");
} }
@Test @Test

View File

@ -22,9 +22,8 @@ import org.springframework.beans.factory.FactoryBean;
import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext;
import static org.hamcrest.CoreMatchers.is; import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.CoreMatchers.not;
import static org.hamcrest.MatcherAssert.assertThat;
/** /**
* Tests to verify that FactoryBean semantics are the same in Configuration * Tests to verify that FactoryBean semantics are the same in Configuration
@ -49,16 +48,16 @@ public class Spr6602Tests {
Bar bar1 = ctx.getBean(Bar.class); Bar bar1 = ctx.getBean(Bar.class);
Bar bar2 = ctx.getBean(Bar.class); Bar bar2 = ctx.getBean(Bar.class);
assertThat(bar1, is(bar2)); assertThat(bar1).isEqualTo(bar2);
assertThat(bar1, is(foo.bar)); assertThat(bar1).isEqualTo(foo.bar);
BarFactory barFactory1 = ctx.getBean(BarFactory.class); BarFactory barFactory1 = ctx.getBean(BarFactory.class);
BarFactory barFactory2 = ctx.getBean(BarFactory.class); BarFactory barFactory2 = ctx.getBean(BarFactory.class);
assertThat(barFactory1, is(barFactory2)); assertThat(barFactory1).isEqualTo(barFactory2);
Bar bar3 = barFactory1.getObject(); Bar bar3 = barFactory1.getObject();
Bar bar4 = barFactory1.getObject(); Bar bar4 = barFactory1.getObject();
assertThat(bar3, is(not(bar4))); assertThat(bar3).isNotEqualTo(bar4);
} }

View File

@ -27,10 +27,8 @@ import org.springframework.beans.factory.config.InstantiationAwareBeanPostProces
import org.springframework.beans.factory.support.AbstractBeanFactory; import org.springframework.beans.factory.support.AbstractBeanFactory;
import org.springframework.beans.factory.support.RootBeanDefinition; import org.springframework.beans.factory.support.RootBeanDefinition;
import static org.hamcrest.CoreMatchers.equalTo; import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.CoreMatchers.instanceOf;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
/** /**
* Unit tests for SPR-8954, in which a custom {@link InstantiationAwareBeanPostProcessor} * Unit tests for SPR-8954, in which a custom {@link InstantiationAwareBeanPostProcessor}
@ -53,19 +51,19 @@ public class Spr8954Tests {
bf.getBeanFactory().addBeanPostProcessor(new PredictingBPP()); bf.getBeanFactory().addBeanPostProcessor(new PredictingBPP());
bf.refresh(); bf.refresh();
assertThat(bf.getBean("foo"), instanceOf(Foo.class)); assertThat(bf.getBean("foo")).isInstanceOf(Foo.class);
assertThat(bf.getBean("&foo"), instanceOf(FooFactoryBean.class)); assertThat(bf.getBean("&foo")).isInstanceOf(FooFactoryBean.class);
assertThat(bf.isTypeMatch("&foo", FactoryBean.class), is(true)); assertThat(bf.isTypeMatch("&foo", FactoryBean.class)).isTrue();
@SuppressWarnings("rawtypes") @SuppressWarnings("rawtypes")
Map<String, FactoryBean> fbBeans = bf.getBeansOfType(FactoryBean.class); Map<String, FactoryBean> fbBeans = bf.getBeansOfType(FactoryBean.class);
assertThat(1, equalTo(fbBeans.size())); assertThat(1).isEqualTo(fbBeans.size());
assertThat("&foo", equalTo(fbBeans.keySet().iterator().next())); assertThat("&foo").isEqualTo(fbBeans.keySet().iterator().next());
Map<String, AnInterface> aiBeans = bf.getBeansOfType(AnInterface.class); Map<String, AnInterface> aiBeans = bf.getBeansOfType(AnInterface.class);
assertThat(1, equalTo(aiBeans.size())); assertThat(1).isEqualTo(aiBeans.size());
assertThat("&foo", equalTo(aiBeans.keySet().iterator().next())); assertThat("&foo").isEqualTo(aiBeans.keySet().iterator().next());
} }
@Test @Test
@ -75,16 +73,16 @@ public class Spr8954Tests {
bf.getBeanFactory().addBeanPostProcessor(new PredictingBPP()); bf.getBeanFactory().addBeanPostProcessor(new PredictingBPP());
bf.refresh(); bf.refresh();
assertThat(bf.isTypeMatch("&foo", FactoryBean.class), is(true)); assertThat(bf.isTypeMatch("&foo", FactoryBean.class)).isTrue();
@SuppressWarnings("rawtypes") @SuppressWarnings("rawtypes")
Map<String, FactoryBean> fbBeans = bf.getBeansOfType(FactoryBean.class); Map<String, FactoryBean> fbBeans = bf.getBeansOfType(FactoryBean.class);
assertThat(1, equalTo(fbBeans.size())); assertThat(1).isEqualTo(fbBeans.size());
assertThat("&foo", equalTo(fbBeans.keySet().iterator().next())); assertThat("&foo").isEqualTo(fbBeans.keySet().iterator().next());
Map<String, AnInterface> aiBeans = bf.getBeansOfType(AnInterface.class); Map<String, AnInterface> aiBeans = bf.getBeansOfType(AnInterface.class);
assertThat(1, equalTo(aiBeans.size())); assertThat(1).isEqualTo(aiBeans.size());
assertThat("&foo", equalTo(aiBeans.keySet().iterator().next())); assertThat("&foo").isEqualTo(aiBeans.keySet().iterator().next());
} }

View File

@ -44,8 +44,7 @@ import org.springframework.core.io.Resource;
import org.springframework.tests.sample.beans.Colour; import org.springframework.tests.sample.beans.Colour;
import org.springframework.tests.sample.beans.TestBean; import org.springframework.tests.sample.beans.TestBean;
import static org.hamcrest.CoreMatchers.equalTo; import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.Assert.assertNull; import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame; import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertTrue;
@ -65,8 +64,8 @@ public class AutowiredConfigurationTests {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext( ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
AutowiredConfigurationTests.class.getSimpleName() + ".xml", AutowiredConfigurationTests.class); AutowiredConfigurationTests.class.getSimpleName() + ".xml", AutowiredConfigurationTests.class);
assertThat(context.getBean("colour", Colour.class), equalTo(Colour.RED)); assertThat(context.getBean("colour", Colour.class)).isEqualTo(Colour.RED);
assertThat(context.getBean("testBean", TestBean.class).getName(), equalTo(Colour.RED.toString())); assertThat(context.getBean("testBean", TestBean.class).getName()).isEqualTo(Colour.RED.toString());
} }
@Test @Test
@ -74,8 +73,8 @@ public class AutowiredConfigurationTests {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext( AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(
AutowiredMethodConfig.class, ColorConfig.class); AutowiredMethodConfig.class, ColorConfig.class);
assertThat(context.getBean(Colour.class), equalTo(Colour.RED)); assertThat(context.getBean(Colour.class)).isEqualTo(Colour.RED);
assertThat(context.getBean(TestBean.class).getName(), equalTo("RED-RED")); assertThat(context.getBean(TestBean.class).getName()).isEqualTo("RED-RED");
} }
@Test @Test
@ -83,8 +82,8 @@ public class AutowiredConfigurationTests {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext( AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(
OptionalAutowiredMethodConfig.class, ColorConfig.class); OptionalAutowiredMethodConfig.class, ColorConfig.class);
assertThat(context.getBean(Colour.class), equalTo(Colour.RED)); assertThat(context.getBean(Colour.class)).isEqualTo(Colour.RED);
assertThat(context.getBean(TestBean.class).getName(), equalTo("RED-RED")); assertThat(context.getBean(TestBean.class).getName()).isEqualTo("RED-RED");
} }
@Test @Test
@ -93,7 +92,7 @@ public class AutowiredConfigurationTests {
OptionalAutowiredMethodConfig.class); OptionalAutowiredMethodConfig.class);
assertTrue(context.getBeansOfType(Colour.class).isEmpty()); assertTrue(context.getBeansOfType(Colour.class).isEmpty());
assertThat(context.getBean(TestBean.class).getName(), equalTo("")); assertThat(context.getBean(TestBean.class).getName()).isEqualTo("");
} }
@Test @Test
@ -186,10 +185,10 @@ public class AutowiredConfigurationTests {
System.setProperty("myProp", "foo"); System.setProperty("myProp", "foo");
testBean = context.getBean("testBean", TestBean.class); testBean = context.getBean("testBean", TestBean.class);
assertThat(testBean.getName(), equalTo("foo")); assertThat(testBean.getName()).isEqualTo("foo");
testBean = context.getBean("testBean2", TestBean.class); testBean = context.getBean("testBean2", TestBean.class);
assertThat(testBean.getName(), equalTo("foo")); assertThat(testBean.getName()).isEqualTo("foo");
System.clearProperty("myProp"); System.clearProperty("myProp");
@ -206,8 +205,8 @@ public class AutowiredConfigurationTests {
"AutowiredConfigurationTests-custom.xml", AutowiredConfigurationTests.class); "AutowiredConfigurationTests-custom.xml", AutowiredConfigurationTests.class);
TestBean testBean = context.getBean("testBean", TestBean.class); TestBean testBean = context.getBean("testBean", TestBean.class);
assertThat(testBean.getName(), equalTo("localhost")); assertThat(testBean.getName()).isEqualTo("localhost");
assertThat(testBean.getAge(), equalTo(contentLength())); assertThat(testBean.getAge()).isEqualTo(contentLength());
} }
@Test @Test
@ -218,8 +217,8 @@ public class AutowiredConfigurationTests {
context.refresh(); context.refresh();
TestBean testBean = context.getBean("testBean", TestBean.class); TestBean testBean = context.getBean("testBean", TestBean.class);
assertThat(testBean.getName(), equalTo("localhost")); assertThat(testBean.getName()).isEqualTo("localhost");
assertThat(testBean.getAge(), equalTo(contentLength())); assertThat(testBean.getAge()).isEqualTo(contentLength());
} }
private int contentLength() throws IOException { private int contentLength() throws IOException {

View File

@ -35,8 +35,7 @@ import org.springframework.stereotype.Component;
import org.springframework.tests.sample.beans.NestedTestBean; import org.springframework.tests.sample.beans.NestedTestBean;
import org.springframework.tests.sample.beans.TestBean; import org.springframework.tests.sample.beans.TestBean;
import static org.hamcrest.CoreMatchers.equalTo; import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertTrue;
@ -56,8 +55,8 @@ public class BeanMethodQualificationTests {
new AnnotationConfigApplicationContext(StandardConfig.class, StandardPojo.class); new AnnotationConfigApplicationContext(StandardConfig.class, StandardPojo.class);
assertFalse(ctx.getBeanFactory().containsSingleton("testBean1")); assertFalse(ctx.getBeanFactory().containsSingleton("testBean1"));
StandardPojo pojo = ctx.getBean(StandardPojo.class); StandardPojo pojo = ctx.getBean(StandardPojo.class);
assertThat(pojo.testBean.getName(), equalTo("interesting")); assertThat(pojo.testBean.getName()).isEqualTo("interesting");
assertThat(pojo.testBean2.getName(), equalTo("boring")); assertThat(pojo.testBean2.getName()).isEqualTo("boring");
} }
@Test @Test
@ -66,8 +65,8 @@ public class BeanMethodQualificationTests {
new AnnotationConfigApplicationContext(ScopedConfig.class, StandardPojo.class); new AnnotationConfigApplicationContext(ScopedConfig.class, StandardPojo.class);
assertFalse(ctx.getBeanFactory().containsSingleton("testBean1")); assertFalse(ctx.getBeanFactory().containsSingleton("testBean1"));
StandardPojo pojo = ctx.getBean(StandardPojo.class); StandardPojo pojo = ctx.getBean(StandardPojo.class);
assertThat(pojo.testBean.getName(), equalTo("interesting")); assertThat(pojo.testBean.getName()).isEqualTo("interesting");
assertThat(pojo.testBean2.getName(), equalTo("boring")); assertThat(pojo.testBean2.getName()).isEqualTo("boring");
} }
@Test @Test
@ -76,8 +75,8 @@ public class BeanMethodQualificationTests {
new AnnotationConfigApplicationContext(ScopedProxyConfig.class, StandardPojo.class); new AnnotationConfigApplicationContext(ScopedProxyConfig.class, StandardPojo.class);
assertTrue(ctx.getBeanFactory().containsSingleton("testBean1")); // a shared scoped proxy assertTrue(ctx.getBeanFactory().containsSingleton("testBean1")); // a shared scoped proxy
StandardPojo pojo = ctx.getBean(StandardPojo.class); StandardPojo pojo = ctx.getBean(StandardPojo.class);
assertThat(pojo.testBean.getName(), equalTo("interesting")); assertThat(pojo.testBean.getName()).isEqualTo("interesting");
assertThat(pojo.testBean2.getName(), equalTo("boring")); assertThat(pojo.testBean2.getName()).isEqualTo("boring");
} }
@Test @Test
@ -89,10 +88,10 @@ public class BeanMethodQualificationTests {
assertTrue(BeanFactoryAnnotationUtils.isQualifierMatch(value -> value.equals("boring"), assertTrue(BeanFactoryAnnotationUtils.isQualifierMatch(value -> value.equals("boring"),
"testBean2", ctx.getDefaultListableBeanFactory())); "testBean2", ctx.getDefaultListableBeanFactory()));
CustomPojo pojo = ctx.getBean(CustomPojo.class); CustomPojo pojo = ctx.getBean(CustomPojo.class);
assertThat(pojo.testBean.getName(), equalTo("interesting")); assertThat(pojo.testBean.getName()).isEqualTo("interesting");
TestBean testBean2 = BeanFactoryAnnotationUtils.qualifiedBeanOfType( TestBean testBean2 = BeanFactoryAnnotationUtils.qualifiedBeanOfType(
ctx.getDefaultListableBeanFactory(), TestBean.class, "boring"); ctx.getDefaultListableBeanFactory(), TestBean.class, "boring");
assertThat(testBean2.getName(), equalTo("boring")); assertThat(testBean2.getName()).isEqualTo("boring");
} }
@Test @Test
@ -106,7 +105,7 @@ public class BeanMethodQualificationTests {
assertTrue(BeanFactoryAnnotationUtils.isQualifierMatch(value -> value.equals("boring"), assertTrue(BeanFactoryAnnotationUtils.isQualifierMatch(value -> value.equals("boring"),
"testBean2", ctx.getDefaultListableBeanFactory())); "testBean2", ctx.getDefaultListableBeanFactory()));
CustomPojo pojo = ctx.getBean(CustomPojo.class); CustomPojo pojo = ctx.getBean(CustomPojo.class);
assertThat(pojo.testBean.getName(), equalTo("interesting")); assertThat(pojo.testBean.getName()).isEqualTo("interesting");
} }
@Test @Test
@ -120,7 +119,7 @@ public class BeanMethodQualificationTests {
assertFalse(ctx.getBeanFactory().containsSingleton("testBean1")); assertFalse(ctx.getBeanFactory().containsSingleton("testBean1"));
assertFalse(ctx.getBeanFactory().containsSingleton("testBean2")); assertFalse(ctx.getBeanFactory().containsSingleton("testBean2"));
CustomPojo pojo = ctx.getBean(CustomPojo.class); CustomPojo pojo = ctx.getBean(CustomPojo.class);
assertThat(pojo.testBean.getName(), equalTo("interesting")); assertThat(pojo.testBean.getName()).isEqualTo("interesting");
} }
@Test @Test
@ -129,7 +128,7 @@ public class BeanMethodQualificationTests {
new AnnotationConfigApplicationContext(CustomConfigWithAttributeOverride.class, CustomPojo.class); new AnnotationConfigApplicationContext(CustomConfigWithAttributeOverride.class, CustomPojo.class);
assertFalse(ctx.getBeanFactory().containsSingleton("testBeanX")); assertFalse(ctx.getBeanFactory().containsSingleton("testBeanX"));
CustomPojo pojo = ctx.getBean(CustomPojo.class); CustomPojo pojo = ctx.getBean(CustomPojo.class);
assertThat(pojo.testBean.getName(), equalTo("interesting")); assertThat(pojo.testBean.getName()).isEqualTo("interesting");
} }
@Test @Test

View File

@ -27,8 +27,8 @@ import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import; import org.springframework.context.annotation.Import;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import static org.hamcrest.CoreMatchers.is; import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.MatcherAssert.assertThat;
/** /**
* Unit tests ensuring that configuration class bean names as expressed via @Configuration * Unit tests ensuring that configuration class bean names as expressed via @Configuration
@ -45,10 +45,10 @@ public class ConfigurationBeanNameTests {
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(); AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
ctx.register(A.class); ctx.register(A.class);
ctx.refresh(); ctx.refresh();
assertThat(ctx.containsBean("outer"), is(true)); assertThat(ctx.containsBean("outer")).isTrue();
assertThat(ctx.containsBean("imported"), is(true)); assertThat(ctx.containsBean("imported")).isTrue();
assertThat(ctx.containsBean("nested"), is(true)); assertThat(ctx.containsBean("nested")).isTrue();
assertThat(ctx.containsBean("nestedBean"), is(true)); assertThat(ctx.containsBean("nestedBean")).isTrue();
} }
@Test @Test
@ -56,10 +56,10 @@ public class ConfigurationBeanNameTests {
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(); AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
ctx.register(A.B.class); ctx.register(A.B.class);
ctx.refresh(); ctx.refresh();
assertThat(ctx.containsBean("outer"), is(false)); assertThat(ctx.containsBean("outer")).isFalse();
assertThat(ctx.containsBean("imported"), is(false)); assertThat(ctx.containsBean("imported")).isFalse();
assertThat(ctx.containsBean("nested"), is(true)); assertThat(ctx.containsBean("nested")).isTrue();
assertThat(ctx.containsBean("nestedBean"), is(true)); assertThat(ctx.containsBean("nestedBean")).isTrue();
} }
@Test @Test
@ -74,10 +74,10 @@ public class ConfigurationBeanNameTests {
}); });
ctx.register(A.class); ctx.register(A.class);
ctx.refresh(); ctx.refresh();
assertThat(ctx.containsBean("custom-outer"), is(true)); assertThat(ctx.containsBean("custom-outer")).isTrue();
assertThat(ctx.containsBean("custom-imported"), is(true)); assertThat(ctx.containsBean("custom-imported")).isTrue();
assertThat(ctx.containsBean("custom-nested"), is(true)); assertThat(ctx.containsBean("custom-nested")).isTrue();
assertThat(ctx.containsBean("nestedBean"), is(true)); assertThat(ctx.containsBean("nestedBean")).isTrue();
} }
@Configuration("outer") @Configuration("outer")

View File

@ -35,8 +35,8 @@ import org.springframework.context.support.GenericApplicationContext;
import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.ClassPathResource;
import org.springframework.tests.sample.beans.TestBean; import org.springframework.tests.sample.beans.TestBean;
import static org.hamcrest.CoreMatchers.equalTo; import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.MatcherAssert.assertThat;
/** /**
* System tests covering use of AspectJ {@link Aspect}s in conjunction with {@link Configuration} classes. * System tests covering use of AspectJ {@link Aspect}s in conjunction with {@link Configuration} classes.
@ -73,9 +73,9 @@ public class ConfigurationClassAspectIntegrationTests {
ctx.refresh(); ctx.refresh();
TestBean testBean = ctx.getBean("testBean", TestBean.class); TestBean testBean = ctx.getBean("testBean", TestBean.class);
assertThat(testBean.getName(), equalTo("name")); assertThat(testBean.getName()).isEqualTo("name");
testBean.absquatulate(); testBean.absquatulate();
assertThat(testBean.getName(), equalTo("advisedName")); assertThat(testBean.getName()).isEqualTo("advisedName");
} }
@Test @Test

View File

@ -26,9 +26,8 @@ import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.tests.sample.beans.ITestBean; import org.springframework.tests.sample.beans.ITestBean;
import org.springframework.tests.sample.beans.TestBean; import org.springframework.tests.sample.beans.TestBean;
import static org.hamcrest.CoreMatchers.equalTo; import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.CoreMatchers.nullValue;
import static org.hamcrest.MatcherAssert.assertThat;
/** /**
* A configuration class that registers a non-static placeholder configurer {@code @Bean} * A configuration class that registers a non-static placeholder configurer {@code @Bean}
@ -71,7 +70,7 @@ public class ConfigurationClassWithPlaceholderConfigurerBeanTests {
TestBean testBean = ctx.getBean(TestBean.class); TestBean testBean = ctx.getBean(TestBean.class);
// Proof that the @Value field did not get set: // Proof that the @Value field did not get set:
assertThat(testBean.getName(), nullValue()); assertThat(testBean.getName()).isNull();
} }
@Test @Test
@ -84,7 +83,7 @@ public class ConfigurationClassWithPlaceholderConfigurerBeanTests {
System.clearProperty("test.name"); System.clearProperty("test.name");
TestBean testBean = ctx.getBean(TestBean.class); TestBean testBean = ctx.getBean(TestBean.class);
assertThat(testBean.getName(), equalTo("foo")); assertThat(testBean.getName()).isEqualTo("foo");
} }
@Test @Test
@ -98,7 +97,7 @@ public class ConfigurationClassWithPlaceholderConfigurerBeanTests {
System.clearProperty("test.name"); System.clearProperty("test.name");
TestBean testBean = ctx.getBean(TestBean.class); TestBean testBean = ctx.getBean(TestBean.class);
assertThat(testBean.getName(), equalTo("foo")); assertThat(testBean.getName()).isEqualTo("foo");
} }
@Test @Test
@ -110,7 +109,7 @@ public class ConfigurationClassWithPlaceholderConfigurerBeanTests {
ctx.refresh(); ctx.refresh();
TestBean testBean = ctx.getBean(TestBean.class); TestBean testBean = ctx.getBean(TestBean.class);
assertThat(testBean.getName(), equalTo("bar")); assertThat(testBean.getName()).isEqualTo("bar");
} }
@Test @Test
@ -122,7 +121,7 @@ public class ConfigurationClassWithPlaceholderConfigurerBeanTests {
ctx.refresh(); ctx.refresh();
TestBean testBean = ctx.getBean(TestBean.class); TestBean testBean = ctx.getBean(TestBean.class);
assertThat(testBean.getName(), equalTo("bar")); assertThat(testBean.getName()).isEqualTo("bar");
} }

View File

@ -26,9 +26,8 @@ import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
import org.springframework.tests.sample.beans.TestBean; import org.springframework.tests.sample.beans.TestBean;
import static org.hamcrest.CoreMatchers.is; import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.CoreMatchers.sameInstance;
import static org.hamcrest.MatcherAssert.assertThat;
/** /**
* Ensures that @Configuration is supported properly as a meta-annotation. * Ensures that @Configuration is supported properly as a meta-annotation.
@ -42,10 +41,10 @@ public class ConfigurationMetaAnnotationTests {
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(); AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
ctx.register(Config.class); ctx.register(Config.class);
ctx.refresh(); ctx.refresh();
assertThat(ctx.containsBean("customName"), is(true)); assertThat(ctx.containsBean("customName")).isTrue();
TestBean a = ctx.getBean("a", TestBean.class); TestBean a = ctx.getBean("a", TestBean.class);
TestBean b = ctx.getBean("b", TestBean.class); TestBean b = ctx.getBean("b", TestBean.class);
assertThat(b, sameInstance(a.getSpouse())); assertThat(b).isSameAs(a.getSpouse());
} }

View File

@ -29,8 +29,8 @@ import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import; import org.springframework.context.annotation.Import;
import org.springframework.tests.sample.beans.TestBean; import org.springframework.tests.sample.beans.TestBean;
import static org.hamcrest.CoreMatchers.is; import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.MatcherAssert.assertThat;
/** /**
* Tests that @Import may be used both as a locally declared and meta-declared * Tests that @Import may be used both as a locally declared and meta-declared
@ -48,8 +48,8 @@ public class ImportAnnotationDetectionTests {
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(); AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
ctx.register(MultiMetaImportConfig.class); ctx.register(MultiMetaImportConfig.class);
ctx.refresh(); ctx.refresh();
assertThat(ctx.containsBean("testBean1"), is(true)); assertThat(ctx.containsBean("testBean1")).isTrue();
assertThat(ctx.containsBean("testBean2"), is(true)); assertThat(ctx.containsBean("testBean2")).isTrue();
} }
@Test @Test
@ -57,9 +57,9 @@ public class ImportAnnotationDetectionTests {
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(); AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
ctx.register(MultiMetaImportConfigWithLocalImport.class); ctx.register(MultiMetaImportConfigWithLocalImport.class);
ctx.refresh(); ctx.refresh();
assertThat(ctx.containsBean("testBean1"), is(true)); assertThat(ctx.containsBean("testBean1")).isTrue();
assertThat(ctx.containsBean("testBean2"), is(true)); assertThat(ctx.containsBean("testBean2")).isTrue();
assertThat(ctx.containsBean("testBean3"), is(true)); assertThat(ctx.containsBean("testBean3")).isTrue();
} }
@Test @Test
@ -67,9 +67,9 @@ public class ImportAnnotationDetectionTests {
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(); AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
ctx.register(MultiMetaImportConfigWithLocalImportWithBeanOverride.class); ctx.register(MultiMetaImportConfigWithLocalImportWithBeanOverride.class);
ctx.refresh(); ctx.refresh();
assertThat(ctx.containsBean("testBean1"), is(true)); assertThat(ctx.containsBean("testBean1")).isTrue();
assertThat(ctx.containsBean("testBean2"), is(true)); assertThat(ctx.containsBean("testBean2")).isTrue();
assertThat(ctx.getBean("testBean2", TestBean.class).getName(), is("2a")); assertThat(ctx.getBean("testBean2", TestBean.class).getName()).isEqualTo("2a");
} }
@Test @Test
@ -77,9 +77,9 @@ public class ImportAnnotationDetectionTests {
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(); AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
ctx.register(ImportFromBean.class); ctx.register(ImportFromBean.class);
ctx.refresh(); ctx.refresh();
assertThat(ctx.containsBean("importAnnotationDetectionTests.ImportFromBean"), is(true)); assertThat(ctx.containsBean("importAnnotationDetectionTests.ImportFromBean")).isTrue();
assertThat(ctx.containsBean("testBean1"), is(true)); assertThat(ctx.containsBean("testBean1")).isTrue();
assertThat(ctx.getBean("testBean1", TestBean.class).getName(), is("1")); assertThat(ctx.getBean("testBean1", TestBean.class).getName()).isEqualTo("1");
} }
@Configuration @Configuration

View File

@ -34,8 +34,7 @@ import org.springframework.core.env.MapPropertySource;
import org.springframework.core.env.PropertySource; import org.springframework.core.env.PropertySource;
import org.springframework.tests.sample.beans.TestBean; import org.springframework.tests.sample.beans.TestBean;
import static org.hamcrest.CoreMatchers.equalTo; import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertTrue;
@ -107,7 +106,7 @@ public class ImportResourceTests {
public void importXmlWithAutowiredConfig() { public void importXmlWithAutowiredConfig() {
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(ImportXmlAutowiredConfig.class); AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(ImportXmlAutowiredConfig.class);
String name = ctx.getBean("xmlBeanName", String.class); String name = ctx.getBean("xmlBeanName", String.class);
assertThat(name, equalTo("xml.declared")); assertThat(name).isEqualTo("xml.declared");
ctx.close(); ctx.close();
} }

View File

@ -29,9 +29,7 @@ import org.springframework.context.annotation.Import;
import org.springframework.tests.sample.beans.ITestBean; import org.springframework.tests.sample.beans.ITestBean;
import org.springframework.tests.sample.beans.TestBean; import org.springframework.tests.sample.beans.TestBean;
import static org.hamcrest.CoreMatchers.equalTo; import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertTrue;
/** /**
@ -54,7 +52,7 @@ public class ImportTests {
private void assertBeanDefinitionCount(int expectedCount, Class<?>... classes) { private void assertBeanDefinitionCount(int expectedCount, Class<?>... classes) {
DefaultListableBeanFactory beanFactory = processConfigurationClasses(classes); DefaultListableBeanFactory beanFactory = processConfigurationClasses(classes);
assertThat(beanFactory.getBeanDefinitionCount(), equalTo(expectedCount)); assertThat(beanFactory.getBeanDefinitionCount()).isEqualTo(expectedCount);
beanFactory.preInstantiateSingletons(); beanFactory.preInstantiateSingletons();
for (Class<?> clazz : classes) { for (Class<?> clazz : classes) {
beanFactory.getBean(clazz); beanFactory.getBean(clazz);
@ -70,7 +68,7 @@ public class ImportTests {
beanFactory.registerBeanDefinition("config", new RootBeanDefinition(ConfigurationWithImportAnnotation.class.getName())); beanFactory.registerBeanDefinition("config", new RootBeanDefinition(ConfigurationWithImportAnnotation.class.getName()));
ConfigurationClassPostProcessor pp = new ConfigurationClassPostProcessor(); ConfigurationClassPostProcessor pp = new ConfigurationClassPostProcessor();
pp.postProcessBeanFactory(beanFactory); pp.postProcessBeanFactory(beanFactory);
assertThat(beanFactory.getBeanDefinitionCount(), equalTo(configClasses + beansInClasses)); assertThat(beanFactory.getBeanDefinitionCount()).isEqualTo(configClasses + beansInClasses);
} }
@Test @Test
@ -178,8 +176,8 @@ public class ImportTests {
WithMultipleArgumentsThatWillCauseDuplication.class)); WithMultipleArgumentsThatWillCauseDuplication.class));
ConfigurationClassPostProcessor pp = new ConfigurationClassPostProcessor(); ConfigurationClassPostProcessor pp = new ConfigurationClassPostProcessor();
pp.postProcessBeanFactory(beanFactory); pp.postProcessBeanFactory(beanFactory);
assertThat(beanFactory.getBeanDefinitionCount(), equalTo(4)); assertThat(beanFactory.getBeanDefinitionCount()).isEqualTo(4);
assertThat(beanFactory.getBean("foo", ITestBean.class).getName(), equalTo("foo2")); assertThat(beanFactory.getBean("foo", ITestBean.class).getName()).isEqualTo("foo2");
} }
@Configuration @Configuration
@ -341,8 +339,8 @@ public class ImportTests {
ctx.register(B.class); ctx.register(B.class);
ctx.refresh(); ctx.refresh();
System.out.println(ctx.getBeanFactory()); System.out.println(ctx.getBeanFactory());
assertThat(ctx.getBeanNamesForType(B.class)[0], is("config-b")); assertThat(ctx.getBeanNamesForType(B.class)[0]).isEqualTo("config-b");
assertThat(ctx.getBeanNamesForType(A.class)[0], is("config-a")); assertThat(ctx.getBeanNamesForType(A.class)[0]).isEqualTo("config-a");
} }
@Configuration("config-a") @Configuration("config-a")

View File

@ -27,8 +27,7 @@ import org.springframework.context.annotation.Import;
import org.springframework.tests.sample.beans.TestBean; import org.springframework.tests.sample.beans.TestBean;
import org.springframework.util.ClassUtils; import org.springframework.util.ClassUtils;
import static org.hamcrest.CoreMatchers.sameInstance; import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.Assert.assertSame; import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertTrue;
@ -73,8 +72,9 @@ public class ImportedConfigurationClassEnhancementTests {
Config config = ctx.getBean(Config.class); Config config = ctx.getBean(Config.class);
TestBean testBean1 = config.autowiredConfig.testBean(); TestBean testBean1 = config.autowiredConfig.testBean();
TestBean testBean2 = config.autowiredConfig.testBean(); TestBean testBean2 = config.autowiredConfig.testBean();
assertThat("got two distinct instances of testBean when singleton scoping was expected", assertThat(testBean1)
testBean1, sameInstance(testBean2)); .as("got two distinct instances of testBean when singleton scoping was expected")
.isSameAs(testBean2);
} }

View File

@ -22,9 +22,8 @@ import org.springframework.context.annotation.AnnotationConfigApplicationContext
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
import static org.hamcrest.CoreMatchers.is; import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.CoreMatchers.not;
import static org.hamcrest.MatcherAssert.assertThat;
/** /**
* Reproduces SPR-8756, which has been marked as "won't fix" for reasons * Reproduces SPR-8756, which has been marked as "won't fix" for reasons
@ -42,7 +41,7 @@ public class PackagePrivateBeanMethodInheritanceTests {
Foo foo1 = ctx.getBean("foo1", Foo.class); Foo foo1 = ctx.getBean("foo1", Foo.class);
Foo foo2 = ctx.getBean("foo2", Foo.class); Foo foo2 = ctx.getBean("foo2", Foo.class);
ctx.getBean("packagePrivateBar", Bar.class); // <-- i.e. @Bean was registered ctx.getBean("packagePrivateBar", Bar.class); // <-- i.e. @Bean was registered
assertThat(foo1.bar, not(is(foo2.bar))); // <-- i.e. @Bean *not* enhanced assertThat(foo1.bar).isNotEqualTo(foo2.bar); // <-- i.e. @Bean *not* enhanced
} }
@Test @Test
@ -52,8 +51,8 @@ public class PackagePrivateBeanMethodInheritanceTests {
ctx.refresh(); ctx.refresh();
Foo foo1 = ctx.getBean("foo1", Foo.class); Foo foo1 = ctx.getBean("foo1", Foo.class);
Foo foo2 = ctx.getBean("foo2", Foo.class); Foo foo2 = ctx.getBean("foo2", Foo.class);
ctx.getBean("protectedBar", Bar.class); // <-- i.e. @Bean was registered ctx.getBean("protectedBar", Bar.class); // <-- i.e. @Bean was registered
assertThat(foo1.bar, is(foo2.bar)); // <-- i.e. @Bean *was* enhanced assertThat(foo1.bar).isEqualTo(foo2.bar); // <-- i.e. @Bean *was* enhanced
} }
public static class Foo { public static class Foo {

View File

@ -25,9 +25,10 @@ import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope; import org.springframework.context.annotation.Scope;
import org.springframework.context.annotation.ScopedProxyMode; import org.springframework.context.annotation.ScopedProxyMode;
import static org.hamcrest.MatcherAssert.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.sameInstance;
/** /**
* @author Phillip Webb * @author Phillip Webb
@ -48,19 +49,19 @@ public class Spr10744Tests {
Foo bean1 = context.getBean("foo", Foo.class); Foo bean1 = context.getBean("foo", Foo.class);
Foo bean2 = context.getBean("foo", Foo.class); Foo bean2 = context.getBean("foo", Foo.class);
assertThat(bean1, sameInstance(bean2)); assertThat(bean1).isSameAs(bean2);
// Should not have invoked constructor for the proxy instance // Should not have invoked constructor for the proxy instance
assertThat(createCount, equalTo(0)); assertThat(createCount).isEqualTo(0);
assertThat(scopeCount, equalTo(0)); assertThat(scopeCount).isEqualTo(0);
// Proxy mode should create new scoped object on each method call // Proxy mode should create new scoped object on each method call
bean1.getMessage(); bean1.getMessage();
assertThat(createCount, equalTo(1)); assertThat(createCount).isEqualTo(1);
assertThat(scopeCount, equalTo(1)); assertThat(scopeCount).isEqualTo(1);
bean1.getMessage(); bean1.getMessage();
assertThat(createCount, equalTo(2)); assertThat(createCount).isEqualTo(2);
assertThat(scopeCount, equalTo(2)); assertThat(scopeCount).isEqualTo(2);
context.close(); context.close();
} }

View File

@ -28,8 +28,7 @@ import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
import org.springframework.util.ClassUtils; import org.springframework.util.ClassUtils;
import static org.hamcrest.CoreMatchers.equalTo; import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertTrue;
public class Spr7167Tests { public class Spr7167Tests {
@ -38,9 +37,9 @@ public class Spr7167Tests {
public void test() { public void test() {
ConfigurableApplicationContext ctx = new AnnotationConfigApplicationContext(MyConfig.class); ConfigurableApplicationContext ctx = new AnnotationConfigApplicationContext(MyConfig.class);
assertThat("someDependency was not post processed", assertThat(ctx.getBeanFactory().getBeanDefinition("someDependency").getDescription())
ctx.getBeanFactory().getBeanDefinition("someDependency").getDescription(), .as("someDependency was not post processed")
equalTo("post processed by MyPostProcessor")); .isEqualTo("post processed by MyPostProcessor");
MyConfig config = ctx.getBean(MyConfig.class); MyConfig config = ctx.getBean(MyConfig.class);
assertTrue("Config class was not enhanced", ClassUtils.isCglibProxy(config)); assertTrue("Config class was not enhanced", ClassUtils.isCglibProxy(config));

View File

@ -29,9 +29,8 @@ import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import; import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.configuration.spr9031.scanpackage.Spr9031Component; import org.springframework.context.annotation.configuration.spr9031.scanpackage.Spr9031Component;
import static org.hamcrest.CoreMatchers.not; import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.CoreMatchers.nullValue;
import static org.hamcrest.MatcherAssert.assertThat;
/** /**
* Unit tests cornering bug SPR-9031. * Unit tests cornering bug SPR-9031.
@ -50,7 +49,7 @@ public class Spr9031Tests {
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(); AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
ctx.register(HighLevelConfig.class); ctx.register(HighLevelConfig.class);
ctx.refresh(); ctx.refresh();
assertThat(ctx.getBean(LowLevelConfig.class).scanned, not(nullValue())); assertThat(ctx.getBean(LowLevelConfig.class).scanned).isNotNull();
} }
/** /**
@ -62,7 +61,7 @@ public class Spr9031Tests {
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(); AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
ctx.register(LowLevelConfig.class); ctx.register(LowLevelConfig.class);
ctx.refresh(); ctx.refresh();
assertThat(ctx.getBean(LowLevelConfig.class).scanned, not(nullValue())); assertThat(ctx.getBean(LowLevelConfig.class).scanned).isNotNull();
} }
@Configuration @Configuration

View File

@ -25,8 +25,8 @@ import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import; import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.spr10546.scanpackage.AEnclosingConfig; import org.springframework.context.annotation.spr10546.scanpackage.AEnclosingConfig;
import static org.hamcrest.CoreMatchers.equalTo; import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.MatcherAssert.assertThat;
/** /**
* @author Rob Winch * @author Rob Winch
@ -64,7 +64,7 @@ public class Spr10546Tests {
context = ctx; context = ctx;
ctx.scan(AEnclosingConfig.class.getPackage().getName()); ctx.scan(AEnclosingConfig.class.getPackage().getName());
ctx.refresh(); ctx.refresh();
assertThat(context.getBean("myBean",String.class), equalTo("myBean")); assertThat(context.getBean("myBean",String.class)).isEqualTo("myBean");
} }
@Test @Test
@ -143,7 +143,7 @@ public class Spr10546Tests {
private void assertLoadsMyBean(Class<?>... annotatedClasses) { private void assertLoadsMyBean(Class<?>... annotatedClasses) {
context = new AnnotationConfigApplicationContext(annotatedClasses); context = new AnnotationConfigApplicationContext(annotatedClasses);
assertThat(context.getBean("myBean",String.class), equalTo("myBean")); assertThat(context.getBean("myBean",String.class)).isEqualTo("myBean");
} }
} }

View File

@ -24,8 +24,8 @@ import org.junit.Test;
import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import static org.hamcrest.CoreMatchers.is; import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.MatcherAssert.assertThat;
/** /**
* Tests cornering the regression reported in SPR-8761. * Tests cornering the regression reported in SPR-8761.
@ -43,7 +43,7 @@ public class Spr8761Tests {
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(); AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
ctx.scan(getClass().getPackage().getName()); ctx.scan(getClass().getPackage().getName());
ctx.refresh(); ctx.refresh();
assertThat(ctx.containsBean("withNestedAnnotation"), is(true)); assertThat(ctx.containsBean("withNestedAnnotation")).isTrue();
} }
} }

View File

@ -64,10 +64,9 @@ import org.springframework.util.Assert;
import org.springframework.validation.annotation.Validated; import org.springframework.validation.annotation.Validated;
import org.springframework.validation.beanvalidation.MethodValidationPostProcessor; import org.springframework.validation.beanvalidation.MethodValidationPostProcessor;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.assertThatIllegalStateException; import static org.assertj.core.api.Assertions.assertThatIllegalStateException;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.contains;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertTrue;
@ -548,7 +547,7 @@ public class AnnotationDrivenEventListenerTests {
assertTrue(listener.order.isEmpty()); assertTrue(listener.order.isEmpty());
this.context.publishEvent("whatever"); this.context.publishEvent("whatever");
assertThat(listener.order, contains("first", "second", "third")); assertThat(listener.order).contains("first", "second", "third");
} }
@Test @Ignore // SPR-15122 @Test @Ignore // SPR-15122
@ -556,7 +555,7 @@ public class AnnotationDrivenEventListenerTests {
load(EventOnPostConstruct.class, OrderedTestListener.class); load(EventOnPostConstruct.class, OrderedTestListener.class);
OrderedTestListener listener = this.context.getBean(OrderedTestListener.class); OrderedTestListener listener = this.context.getBean(OrderedTestListener.class);
assertThat(listener.order, contains("first", "second", "third")); assertThat(listener.order).contains("first", "second", "third");
} }

View File

@ -24,8 +24,7 @@ import org.springframework.context.support.GenericApplicationContext;
import org.springframework.mock.env.MockPropertySource; import org.springframework.mock.env.MockPropertySource;
import org.springframework.tests.sample.beans.TestBean; import org.springframework.tests.sample.beans.TestBean;
import static org.hamcrest.CoreMatchers.equalTo; import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.springframework.beans.factory.support.BeanDefinitionBuilder.genericBeanDefinition; import static org.springframework.beans.factory.support.BeanDefinitionBuilder.genericBeanDefinition;
/** /**
@ -49,7 +48,7 @@ public class EnvironmentAccessorIntegrationTests {
ctx.getEnvironment().getPropertySources().addFirst(new MockPropertySource().withProperty("my.name", "myBean")); ctx.getEnvironment().getPropertySources().addFirst(new MockPropertySource().withProperty("my.name", "myBean"));
ctx.refresh(); ctx.refresh();
assertThat(ctx.getBean(TestBean.class).getName(), equalTo("myBean")); assertThat(ctx.getBean(TestBean.class).getName()).isEqualTo("myBean");
ctx.close(); ctx.close();
} }

View File

@ -23,12 +23,13 @@ import org.junit.Test;
import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.ClassPathResource;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalStateException; import static org.assertj.core.api.Assertions.assertThatIllegalStateException;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsInAnyOrder;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.nullValue;
/** /**
* Tests for {@link CandidateComponentsIndexLoader}. * Tests for {@link CandidateComponentsIndexLoader}.
@ -40,7 +41,7 @@ public class CandidateComponentsIndexLoaderTests {
@Test @Test
public void validateIndexIsDisabledByDefault() { public void validateIndexIsDisabledByDefault() {
CandidateComponentsIndex index = CandidateComponentsIndexLoader.loadIndex(null); CandidateComponentsIndex index = CandidateComponentsIndexLoader.loadIndex(null);
assertThat("No spring.components should be available at the default location", index, is(nullValue())); assertThat(index).as("No spring.components should be available at the default location").isNull();
} }
@Test @Test
@ -49,9 +50,9 @@ public class CandidateComponentsIndexLoaderTests {
CandidateComponentsTestClassLoader.index(getClass().getClassLoader(), CandidateComponentsTestClassLoader.index(getClass().getClassLoader(),
new ClassPathResource("spring.components", getClass()))); new ClassPathResource("spring.components", getClass())));
Set<String> components = index.getCandidateTypes("org.springframework", "foo"); Set<String> components = index.getCandidateTypes("org.springframework", "foo");
assertThat(components, containsInAnyOrder( assertThat(components).contains(
"org.springframework.context.index.Sample1", "org.springframework.context.index.Sample1",
"org.springframework.context.index.Sample2")); "org.springframework.context.index.Sample2");
} }
@Test @Test
@ -60,8 +61,8 @@ public class CandidateComponentsIndexLoaderTests {
CandidateComponentsTestClassLoader.index(getClass().getClassLoader(), CandidateComponentsTestClassLoader.index(getClass().getClassLoader(),
new ClassPathResource("spring.components", getClass()))); new ClassPathResource("spring.components", getClass())));
Set<String> components = index.getCandidateTypes("org.springframework", "biz"); Set<String> components = index.getCandidateTypes("org.springframework", "biz");
assertThat(components, containsInAnyOrder( assertThat(components).contains(
"org.springframework.context.index.Sample3")); "org.springframework.context.index.Sample3");
} }
@Test @Test
@ -70,7 +71,7 @@ public class CandidateComponentsIndexLoaderTests {
CandidateComponentsTestClassLoader.index(getClass().getClassLoader(), CandidateComponentsTestClassLoader.index(getClass().getClassLoader(),
new ClassPathResource("spring.components", getClass()))); new ClassPathResource("spring.components", getClass())));
Set<String> components = index.getCandidateTypes("org.springframework", "none"); Set<String> components = index.getCandidateTypes("org.springframework", "none");
assertThat(components, hasSize(0)); assertThat(components).isEmpty();
} }
@Test @Test
@ -79,14 +80,14 @@ public class CandidateComponentsIndexLoaderTests {
CandidateComponentsTestClassLoader.index(getClass().getClassLoader(), CandidateComponentsTestClassLoader.index(getClass().getClassLoader(),
new ClassPathResource("spring.components", getClass()))); new ClassPathResource("spring.components", getClass())));
Set<String> components = index.getCandidateTypes("com.example", "foo"); Set<String> components = index.getCandidateTypes("com.example", "foo");
assertThat(components, hasSize(0)); assertThat(components).isEmpty();
} }
@Test @Test
public void loadIndexNoSpringComponentsResource() { public void loadIndexNoSpringComponentsResource() {
CandidateComponentsIndex index = CandidateComponentsIndexLoader.loadIndex( CandidateComponentsIndex index = CandidateComponentsIndexLoader.loadIndex(
CandidateComponentsTestClassLoader.disableIndex(getClass().getClassLoader())); CandidateComponentsTestClassLoader.disableIndex(getClass().getClassLoader()));
assertThat(index, is(nullValue())); assertThat(index).isNull();
} }
@Test @Test
@ -94,7 +95,7 @@ public class CandidateComponentsIndexLoaderTests {
CandidateComponentsIndex index = CandidateComponentsIndexLoader.loadIndex( CandidateComponentsIndex index = CandidateComponentsIndexLoader.loadIndex(
CandidateComponentsTestClassLoader.index(getClass().getClassLoader(), CandidateComponentsTestClassLoader.index(getClass().getClassLoader(),
new ClassPathResource("empty-spring.components", getClass()))); new ClassPathResource("empty-spring.components", getClass())));
assertThat(index, is(nullValue())); assertThat(index).isNull();
} }
@Test @Test

View File

@ -23,10 +23,11 @@ import java.util.Set;
import org.junit.Test; import org.junit.Test;
import static org.hamcrest.MatcherAssert.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.contains;
import static org.hamcrest.Matchers.containsInAnyOrder;
import static org.hamcrest.Matchers.hasSize;
/** /**
* Tests for {@link CandidateComponentsIndex}. * Tests for {@link CandidateComponentsIndex}.
@ -40,8 +41,8 @@ public class CandidateComponentsIndexTests {
CandidateComponentsIndex index = new CandidateComponentsIndex( CandidateComponentsIndex index = new CandidateComponentsIndex(
Collections.singletonList(createSampleProperties())); Collections.singletonList(createSampleProperties()));
Set<String> actual = index.getCandidateTypes("com.example.service", "service"); Set<String> actual = index.getCandidateTypes("com.example.service", "service");
assertThat(actual, containsInAnyOrder("com.example.service.One", assertThat(actual).contains("com.example.service.One",
"com.example.service.sub.Two", "com.example.service.Three")); "com.example.service.sub.Two", "com.example.service.Three");
} }
@Test @Test
@ -49,7 +50,7 @@ public class CandidateComponentsIndexTests {
CandidateComponentsIndex index = new CandidateComponentsIndex( CandidateComponentsIndex index = new CandidateComponentsIndex(
Collections.singletonList(createSampleProperties())); Collections.singletonList(createSampleProperties()));
Set<String> actual = index.getCandidateTypes("com.example.service.sub", "service"); Set<String> actual = index.getCandidateTypes("com.example.service.sub", "service");
assertThat(actual, containsInAnyOrder("com.example.service.sub.Two")); assertThat(actual).contains("com.example.service.sub.Two");
} }
@Test @Test
@ -57,7 +58,7 @@ public class CandidateComponentsIndexTests {
CandidateComponentsIndex index = new CandidateComponentsIndex( CandidateComponentsIndex index = new CandidateComponentsIndex(
Collections.singletonList(createSampleProperties())); Collections.singletonList(createSampleProperties()));
Set<String> actual = index.getCandidateTypes("com.example.service.none", "service"); Set<String> actual = index.getCandidateTypes("com.example.service.none", "service");
assertThat(actual, hasSize(0)); assertThat(actual).isEmpty();
} }
@Test @Test
@ -65,7 +66,7 @@ public class CandidateComponentsIndexTests {
CandidateComponentsIndex index = new CandidateComponentsIndex( CandidateComponentsIndex index = new CandidateComponentsIndex(
Collections.singletonList(createSampleProperties())); Collections.singletonList(createSampleProperties()));
Set<String> actual = index.getCandidateTypes("com.example.service", "entity"); Set<String> actual = index.getCandidateTypes("com.example.service", "entity");
assertThat(actual, hasSize(0)); assertThat(actual).isEmpty();
} }
@Test @Test
@ -73,10 +74,10 @@ public class CandidateComponentsIndexTests {
CandidateComponentsIndex index = new CandidateComponentsIndex(Arrays.asList( CandidateComponentsIndex index = new CandidateComponentsIndex(Arrays.asList(
createProperties("com.example.Foo", "service"), createProperties("com.example.Foo", "service"),
createProperties("com.example.Foo", "entity"))); createProperties("com.example.Foo", "entity")));
assertThat(index.getCandidateTypes("com.example", "service"), assertThat(index.getCandidateTypes("com.example", "service"))
contains("com.example.Foo")); .contains("com.example.Foo");
assertThat(index.getCandidateTypes("com.example", "entity"), assertThat(index.getCandidateTypes("com.example", "entity"))
contains("com.example.Foo")); .contains("com.example.Foo");
} }
private static Properties createProperties(String key, String stereotypes) { private static Properties createProperties(String key, String stereotypes) {

View File

@ -34,9 +34,8 @@ import org.springframework.core.io.FileSystemResource;
import org.springframework.lang.Nullable; import org.springframework.lang.Nullable;
import org.springframework.tests.sample.beans.ResourceTestBean; import org.springframework.tests.sample.beans.ResourceTestBean;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.instanceOf;
import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertTrue;
/** /**
@ -142,8 +141,8 @@ public class ConversionServiceFactoryBeanTests {
public ComplexConstructorArgument(Map<String, Class<?>> map) { public ComplexConstructorArgument(Map<String, Class<?>> map) {
assertTrue(!map.isEmpty()); assertTrue(!map.isEmpty());
assertThat(map.keySet().iterator().next(), instanceOf(String.class)); assertThat(map.keySet().iterator().next()).isInstanceOf(String.class);
assertThat(map.values().iterator().next(), instanceOf(Class.class)); assertThat(map.values().iterator().next()).isInstanceOf(Class.class);
} }
} }

View File

@ -24,9 +24,8 @@ import org.springframework.context.annotation.AnnotationConfigApplicationContext
import org.springframework.core.env.ConfigurableEnvironment; import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.Environment; import org.springframework.core.env.Environment;
import static org.hamcrest.CoreMatchers.anyOf; import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.CoreMatchers.sameInstance;
import static org.hamcrest.MatcherAssert.assertThat;
/** /**
* Tests covering the integration of the {@link Environment} into * Tests covering the integration of the {@link Environment} into
@ -47,10 +46,7 @@ public class EnvironmentIntegrationTests {
child.refresh(); child.refresh();
ConfigurableEnvironment env = child.getBean(ConfigurableEnvironment.class); ConfigurableEnvironment env = child.getBean(ConfigurableEnvironment.class);
assertThat("unknown env", env, anyOf( assertThat(env).isSameAs(child.getEnvironment());
sameInstance(parent.getEnvironment()),
sameInstance(child.getEnvironment())));
assertThat("expected child ctx env", env, sameInstance(child.getEnvironment()));
child.close(); child.close();
parent.close(); parent.close();

View File

@ -32,8 +32,8 @@ import org.springframework.core.env.StandardEnvironmentTests;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import static java.lang.String.format; import static java.lang.String.format;
import static org.hamcrest.CoreMatchers.is; import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.MatcherAssert.assertThat;
/** /**
* Tests integration between Environment and SecurityManagers. See SPR-9970. * Tests integration between Environment and SecurityManagers. See SPR-9970.
@ -78,7 +78,7 @@ public class EnvironmentSecurityManagerIntegrationTests {
DefaultListableBeanFactory bf = new DefaultListableBeanFactory(); DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
AnnotatedBeanDefinitionReader reader = new AnnotatedBeanDefinitionReader(bf); AnnotatedBeanDefinitionReader reader = new AnnotatedBeanDefinitionReader(bf);
reader.register(C1.class); reader.register(C1.class);
assertThat(bf.containsBean("c1"), is(true)); assertThat(bf.containsBean("c1")).isTrue();
} }
@Test @Test
@ -108,7 +108,7 @@ public class EnvironmentSecurityManagerIntegrationTests {
DefaultListableBeanFactory bf = new DefaultListableBeanFactory(); DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
AnnotatedBeanDefinitionReader reader = new AnnotatedBeanDefinitionReader(bf); AnnotatedBeanDefinitionReader reader = new AnnotatedBeanDefinitionReader(bf);
reader.register(C1.class); reader.register(C1.class);
assertThat(bf.containsBean("c1"), is(false)); assertThat(bf.containsBean("c1")).isFalse();
} }

View File

@ -21,8 +21,8 @@ import org.junit.Test;
import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContext;
import org.springframework.util.ClassUtils; import org.springframework.util.ClassUtils;
import static org.hamcrest.CoreMatchers.is; import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.MatcherAssert.assertThat;
/** /**
* Unit tests for {@link GenericXmlApplicationContext}. * Unit tests for {@link GenericXmlApplicationContext}.
@ -43,7 +43,7 @@ public class GenericXmlApplicationContextTests {
@Test @Test
public void classRelativeResourceLoading_ctor() { public void classRelativeResourceLoading_ctor() {
ApplicationContext ctx = new GenericXmlApplicationContext(RELATIVE_CLASS, RESOURCE_NAME); ApplicationContext ctx = new GenericXmlApplicationContext(RELATIVE_CLASS, RESOURCE_NAME);
assertThat(ctx.containsBean(TEST_BEAN_NAME), is(true)); assertThat(ctx.containsBean(TEST_BEAN_NAME)).isTrue();
} }
@Test @Test
@ -51,13 +51,13 @@ public class GenericXmlApplicationContextTests {
GenericXmlApplicationContext ctx = new GenericXmlApplicationContext(); GenericXmlApplicationContext ctx = new GenericXmlApplicationContext();
ctx.load(RELATIVE_CLASS, RESOURCE_NAME); ctx.load(RELATIVE_CLASS, RESOURCE_NAME);
ctx.refresh(); ctx.refresh();
assertThat(ctx.containsBean(TEST_BEAN_NAME), is(true)); assertThat(ctx.containsBean(TEST_BEAN_NAME)).isTrue();
} }
@Test @Test
public void fullyQualifiedResourceLoading_ctor() { public void fullyQualifiedResourceLoading_ctor() {
ApplicationContext ctx = new GenericXmlApplicationContext(FQ_RESOURCE_PATH); ApplicationContext ctx = new GenericXmlApplicationContext(FQ_RESOURCE_PATH);
assertThat(ctx.containsBean(TEST_BEAN_NAME), is(true)); assertThat(ctx.containsBean(TEST_BEAN_NAME)).isTrue();
} }
@Test @Test
@ -65,6 +65,6 @@ public class GenericXmlApplicationContextTests {
GenericXmlApplicationContext ctx = new GenericXmlApplicationContext(); GenericXmlApplicationContext ctx = new GenericXmlApplicationContext();
ctx.load(FQ_RESOURCE_PATH); ctx.load(FQ_RESOURCE_PATH);
ctx.refresh(); ctx.refresh();
assertThat(ctx.containsBean(TEST_BEAN_NAME), is(true)); assertThat(ctx.containsBean(TEST_BEAN_NAME)).isTrue();
} }
} }

View File

@ -33,13 +33,9 @@ import org.springframework.mock.env.MockEnvironment;
import org.springframework.mock.env.MockPropertySource; import org.springframework.mock.env.MockPropertySource;
import org.springframework.tests.sample.beans.TestBean; import org.springframework.tests.sample.beans.TestBean;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.assertThatIllegalStateException; import static org.assertj.core.api.Assertions.assertThatIllegalStateException;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.not;
import static org.hamcrest.CoreMatchers.nullValue;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
import static org.springframework.beans.factory.support.BeanDefinitionBuilder.genericBeanDefinition; import static org.springframework.beans.factory.support.BeanDefinitionBuilder.genericBeanDefinition;
import static org.springframework.beans.factory.support.BeanDefinitionBuilder.rootBeanDefinition; import static org.springframework.beans.factory.support.BeanDefinitionBuilder.rootBeanDefinition;
@ -66,8 +62,8 @@ public class PropertySourcesPlaceholderConfigurerTests {
PropertySourcesPlaceholderConfigurer ppc = new PropertySourcesPlaceholderConfigurer(); PropertySourcesPlaceholderConfigurer ppc = new PropertySourcesPlaceholderConfigurer();
ppc.setEnvironment(env); ppc.setEnvironment(env);
ppc.postProcessBeanFactory(bf); ppc.postProcessBeanFactory(bf);
assertThat(bf.getBean(TestBean.class).getName(), equalTo("myValue")); assertThat(bf.getBean(TestBean.class).getName()).isEqualTo("myValue");
assertThat(ppc.getAppliedPropertySources(), not(nullValue())); assertThat(ppc.getAppliedPropertySources()).isNotNull();
} }
@Test @Test
@ -82,7 +78,7 @@ public class PropertySourcesPlaceholderConfigurerTests {
Resource resource = new ClassPathResource("PropertySourcesPlaceholderConfigurerTests.properties", this.getClass()); Resource resource = new ClassPathResource("PropertySourcesPlaceholderConfigurerTests.properties", this.getClass());
ppc.setLocation(resource); ppc.setLocation(resource);
ppc.postProcessBeanFactory(bf); ppc.postProcessBeanFactory(bf);
assertThat(bf.getBean(TestBean.class).getName(), equalTo("foo")); assertThat(bf.getBean(TestBean.class).getName()).isEqualTo("foo");
} }
@Test @Test
@ -109,7 +105,7 @@ public class PropertySourcesPlaceholderConfigurerTests {
PropertySourcesPlaceholderConfigurer ppc = new PropertySourcesPlaceholderConfigurer(); PropertySourcesPlaceholderConfigurer ppc = new PropertySourcesPlaceholderConfigurer();
ppc.setPropertySources(propertySources); ppc.setPropertySources(propertySources);
ppc.postProcessBeanFactory(bf); ppc.postProcessBeanFactory(bf);
assertThat(bf.getBean(TestBean.class).getName(), equalTo("foo")); assertThat(bf.getBean(TestBean.class).getName()).isEqualTo("foo");
assertEquals(ppc.getAppliedPropertySources().iterator().next(), propertySources.iterator().next()); assertEquals(ppc.getAppliedPropertySources().iterator().next(), propertySources.iterator().next());
} }
@ -129,7 +125,7 @@ public class PropertySourcesPlaceholderConfigurerTests {
ppc.setEnvironment(new MockEnvironment().withProperty("my.name", "env")); ppc.setEnvironment(new MockEnvironment().withProperty("my.name", "env"));
ppc.setIgnoreUnresolvablePlaceholders(true); ppc.setIgnoreUnresolvablePlaceholders(true);
ppc.postProcessBeanFactory(bf); ppc.postProcessBeanFactory(bf);
assertThat(bf.getBean(TestBean.class).getName(), equalTo("${my.name}")); assertThat(bf.getBean(TestBean.class).getName()).isEqualTo("${my.name}");
assertEquals(ppc.getAppliedPropertySources().iterator().next(), propertySources.iterator().next()); assertEquals(ppc.getAppliedPropertySources().iterator().next(), propertySources.iterator().next());
} }
@ -152,7 +148,7 @@ public class PropertySourcesPlaceholderConfigurerTests {
}}); }});
ppc.setIgnoreUnresolvablePlaceholders(true); ppc.setIgnoreUnresolvablePlaceholders(true);
ppc.postProcessBeanFactory(bf); ppc.postProcessBeanFactory(bf);
assertThat(bf.getBean(TestBean.class).getName(), equalTo("${my.name}")); assertThat(bf.getBean(TestBean.class).getName()).isEqualTo("${my.name}");
} }
@Test @Test
@ -180,7 +176,7 @@ public class PropertySourcesPlaceholderConfigurerTests {
PropertySourcesPlaceholderConfigurer ppc = new PropertySourcesPlaceholderConfigurer(); PropertySourcesPlaceholderConfigurer ppc = new PropertySourcesPlaceholderConfigurer();
ppc.setIgnoreUnresolvablePlaceholders(true); ppc.setIgnoreUnresolvablePlaceholders(true);
ppc.postProcessBeanFactory(bf); ppc.postProcessBeanFactory(bf);
assertThat(bf.getBean(TestBean.class).getName(), equalTo("${my.name}")); assertThat(bf.getBean(TestBean.class).getName()).isEqualTo("${my.name}");
} }
@Test @Test
@ -215,7 +211,7 @@ public class PropertySourcesPlaceholderConfigurerTests {
}}); }});
ppc.setIgnoreUnresolvablePlaceholders(true); ppc.setIgnoreUnresolvablePlaceholders(true);
ppc.postProcessBeanFactory(bf); ppc.postProcessBeanFactory(bf);
assertThat(bf.getBean(TestBean.class).getName(), equalTo("${bogus}")); assertThat(bf.getBean(TestBean.class).getName()).isEqualTo("${bogus}");
} }
@Test @Test
@ -240,7 +236,7 @@ public class PropertySourcesPlaceholderConfigurerTests {
ppc.setEnvironment(env); ppc.setEnvironment(env);
ppc.postProcessBeanFactory(bf); ppc.postProcessBeanFactory(bf);
assertThat(bf.getBean(TestBean.class).getName(), equalTo("bar")); assertThat(bf.getBean(TestBean.class).getName()).isEqualTo("bar");
} }
@SuppressWarnings("serial") @SuppressWarnings("serial")
@ -260,10 +256,10 @@ public class PropertySourcesPlaceholderConfigurerTests {
ppc.setEnvironment(new MockEnvironment().withProperty("foo", "enclosing")); ppc.setEnvironment(new MockEnvironment().withProperty("foo", "enclosing"));
ppc.postProcessBeanFactory(bf); ppc.postProcessBeanFactory(bf);
if (override) { if (override) {
assertThat(bf.getBean(TestBean.class).getName(), equalTo("local")); assertThat(bf.getBean(TestBean.class).getName()).isEqualTo("local");
} }
else { else {
assertThat(bf.getBean(TestBean.class).getName(), equalTo("enclosing")); assertThat(bf.getBean(TestBean.class).getName()).isEqualTo("enclosing");
} }
} }
@ -287,8 +283,8 @@ public class PropertySourcesPlaceholderConfigurerTests {
System.clearProperty("key1"); System.clearProperty("key1");
System.clearProperty("key2"); System.clearProperty("key2");
assertThat(bf.getBean(TestBean.class).getName(), is("systemKey1Value")); assertThat(bf.getBean(TestBean.class).getName()).isEqualTo("systemKey1Value");
assertThat(bf.getBean(TestBean.class).getSex(), is("${key2}")); assertThat(bf.getBean(TestBean.class).getSex()).isEqualTo("${key2}");
} }
@Test @Test
@ -301,7 +297,7 @@ public class PropertySourcesPlaceholderConfigurerTests {
.getBeanDefinition()); .getBeanDefinition());
ppc.setEnvironment(new MockEnvironment().withProperty("my.name", "customNull")); ppc.setEnvironment(new MockEnvironment().withProperty("my.name", "customNull"));
ppc.postProcessBeanFactory(bf); ppc.postProcessBeanFactory(bf);
assertThat(bf.getBean(TestBean.class).getName(), nullValue()); assertThat(bf.getBean(TestBean.class).getName()).isNull();
} }
@Test @Test
@ -313,7 +309,7 @@ public class PropertySourcesPlaceholderConfigurerTests {
.getBeanDefinition()); .getBeanDefinition());
ppc.setEnvironment(new MockEnvironment().withProperty("my.name", " myValue ")); ppc.setEnvironment(new MockEnvironment().withProperty("my.name", " myValue "));
ppc.postProcessBeanFactory(bf); ppc.postProcessBeanFactory(bf);
assertThat(bf.getBean(TestBean.class).getName(), equalTo(" myValue ")); assertThat(bf.getBean(TestBean.class).getName()).isEqualTo(" myValue ");
} }
@Test @Test
@ -326,7 +322,7 @@ public class PropertySourcesPlaceholderConfigurerTests {
.getBeanDefinition()); .getBeanDefinition());
ppc.setEnvironment(new MockEnvironment().withProperty("my.name", " myValue ")); ppc.setEnvironment(new MockEnvironment().withProperty("my.name", " myValue "));
ppc.postProcessBeanFactory(bf); ppc.postProcessBeanFactory(bf);
assertThat(bf.getBean(TestBean.class).getName(), equalTo("myValue")); assertThat(bf.getBean(TestBean.class).getName()).isEqualTo("myValue");
} }
@Test @Test
@ -351,7 +347,7 @@ public class PropertySourcesPlaceholderConfigurerTests {
.addPropertyValue("jedi", "${jedi:false}") .addPropertyValue("jedi", "${jedi:false}")
.getBeanDefinition()); .getBeanDefinition());
ppc.postProcessBeanFactory(bf); ppc.postProcessBeanFactory(bf);
assertThat(bf.getBean(TestBean.class).isJedi(), equalTo(true)); assertThat(bf.getBean(TestBean.class).isJedi()).isEqualTo(true);
} }
@Test @Test
@ -370,7 +366,7 @@ public class PropertySourcesPlaceholderConfigurerTests {
ppc.setEnvironment(env); ppc.setEnvironment(env);
ppc.setIgnoreUnresolvablePlaceholders(true); ppc.setIgnoreUnresolvablePlaceholders(true);
ppc.postProcessBeanFactory(bf); ppc.postProcessBeanFactory(bf);
assertThat(bf.getBean(OptionalTestBean.class).getName(), equalTo(Optional.of("myValue"))); assertThat(bf.getBean(OptionalTestBean.class).getName()).isEqualTo(Optional.of("myValue"));
} }
@Test @Test
@ -390,7 +386,7 @@ public class PropertySourcesPlaceholderConfigurerTests {
ppc.setIgnoreUnresolvablePlaceholders(true); ppc.setIgnoreUnresolvablePlaceholders(true);
ppc.setNullValue(""); ppc.setNullValue("");
ppc.postProcessBeanFactory(bf); ppc.postProcessBeanFactory(bf);
assertThat(bf.getBean(OptionalTestBean.class).getName(), equalTo(Optional.empty())); assertThat(bf.getBean(OptionalTestBean.class).getName()).isEqualTo(Optional.empty());
} }

View File

@ -28,8 +28,7 @@ import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.DefaultListableBeanFactory; import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.ConfigurableApplicationContext;
import static org.hamcrest.CoreMatchers.equalTo; import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.springframework.beans.factory.support.BeanDefinitionBuilder.rootBeanDefinition; import static org.springframework.beans.factory.support.BeanDefinitionBuilder.rootBeanDefinition;
/** /**
@ -79,17 +78,17 @@ public class SerializableBeanFactoryMemoryLeakTests {
} }
private void assertFactoryCountThroughoutLifecycle(ConfigurableApplicationContext ctx) throws Exception { private void assertFactoryCountThroughoutLifecycle(ConfigurableApplicationContext ctx) throws Exception {
assertThat(serializableFactoryCount(), equalTo(0)); assertThat(serializableFactoryCount()).isEqualTo(0);
try { try {
ctx.refresh(); ctx.refresh();
assertThat(serializableFactoryCount(), equalTo(1)); assertThat(serializableFactoryCount()).isEqualTo(1);
ctx.close(); ctx.close();
} }
catch (BeanCreationException ex) { catch (BeanCreationException ex) {
// ignore - this is expected on refresh() for failure case tests // ignore - this is expected on refresh() for failure case tests
} }
finally { finally {
assertThat(serializableFactoryCount(), equalTo(0)); assertThat(serializableFactoryCount()).isEqualTo(0);
} }
} }

View File

@ -30,10 +30,11 @@ import org.junit.Test;
import org.springframework.format.annotation.DateTimeFormat.ISO; import org.springframework.format.annotation.DateTimeFormat.ISO;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalStateException; import static org.assertj.core.api.Assertions.assertThatIllegalStateException;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.is;
/** /**
* Tests for {@link DateFormatter}. * Tests for {@link DateFormatter}.
@ -51,8 +52,8 @@ public class DateFormatterTests {
DateFormatter formatter = new DateFormatter(); DateFormatter formatter = new DateFormatter();
formatter.setTimeZone(UTC); formatter.setTimeZone(UTC);
Date date = getDate(2009, Calendar.JUNE, 1); Date date = getDate(2009, Calendar.JUNE, 1);
assertThat(formatter.print(date, Locale.US), is("Jun 1, 2009")); assertThat(formatter.print(date, Locale.US)).isEqualTo("Jun 1, 2009");
assertThat(formatter.parse("Jun 1, 2009", Locale.US), is(date)); assertThat(formatter.parse("Jun 1, 2009", Locale.US)).isEqualTo(date);
} }
@Test @Test
@ -60,8 +61,8 @@ public class DateFormatterTests {
DateFormatter formatter = new DateFormatter("yyyy-MM-dd"); DateFormatter formatter = new DateFormatter("yyyy-MM-dd");
formatter.setTimeZone(UTC); formatter.setTimeZone(UTC);
Date date = getDate(2009, Calendar.JUNE, 1); Date date = getDate(2009, Calendar.JUNE, 1);
assertThat(formatter.print(date, Locale.US), is("2009-06-01")); assertThat(formatter.print(date, Locale.US)).isEqualTo("2009-06-01");
assertThat(formatter.parse("2009-06-01", Locale.US), is(date)); assertThat(formatter.parse("2009-06-01", Locale.US)).isEqualTo(date);
} }
@Test @Test
@ -70,8 +71,8 @@ public class DateFormatterTests {
formatter.setTimeZone(UTC); formatter.setTimeZone(UTC);
formatter.setStyle(DateFormat.SHORT); formatter.setStyle(DateFormat.SHORT);
Date date = getDate(2009, Calendar.JUNE, 1); Date date = getDate(2009, Calendar.JUNE, 1);
assertThat(formatter.print(date, Locale.US), is("6/1/09")); assertThat(formatter.print(date, Locale.US)).isEqualTo("6/1/09");
assertThat(formatter.parse("6/1/09", Locale.US), is(date)); assertThat(formatter.parse("6/1/09", Locale.US)).isEqualTo(date);
} }
@Test @Test
@ -80,8 +81,8 @@ public class DateFormatterTests {
formatter.setTimeZone(UTC); formatter.setTimeZone(UTC);
formatter.setStyle(DateFormat.MEDIUM); formatter.setStyle(DateFormat.MEDIUM);
Date date = getDate(2009, Calendar.JUNE, 1); Date date = getDate(2009, Calendar.JUNE, 1);
assertThat(formatter.print(date, Locale.US), is("Jun 1, 2009")); assertThat(formatter.print(date, Locale.US)).isEqualTo("Jun 1, 2009");
assertThat(formatter.parse("Jun 1, 2009", Locale.US), is(date)); assertThat(formatter.parse("Jun 1, 2009", Locale.US)).isEqualTo(date);
} }
@Test @Test
@ -90,8 +91,8 @@ public class DateFormatterTests {
formatter.setTimeZone(UTC); formatter.setTimeZone(UTC);
formatter.setStyle(DateFormat.LONG); formatter.setStyle(DateFormat.LONG);
Date date = getDate(2009, Calendar.JUNE, 1); Date date = getDate(2009, Calendar.JUNE, 1);
assertThat(formatter.print(date, Locale.US), is("June 1, 2009")); assertThat(formatter.print(date, Locale.US)).isEqualTo("June 1, 2009");
assertThat(formatter.parse("June 1, 2009", Locale.US), is(date)); assertThat(formatter.parse("June 1, 2009", Locale.US)).isEqualTo(date);
} }
@Test @Test
@ -100,8 +101,8 @@ public class DateFormatterTests {
formatter.setTimeZone(UTC); formatter.setTimeZone(UTC);
formatter.setStyle(DateFormat.FULL); formatter.setStyle(DateFormat.FULL);
Date date = getDate(2009, Calendar.JUNE, 1); Date date = getDate(2009, Calendar.JUNE, 1);
assertThat(formatter.print(date, Locale.US), is("Monday, June 1, 2009")); assertThat(formatter.print(date, Locale.US)).isEqualTo("Monday, June 1, 2009");
assertThat(formatter.parse("Monday, June 1, 2009", Locale.US), is(date)); assertThat(formatter.parse("Monday, June 1, 2009", Locale.US)).isEqualTo(date);
} }
@Test @Test
@ -110,9 +111,9 @@ public class DateFormatterTests {
formatter.setTimeZone(UTC); formatter.setTimeZone(UTC);
formatter.setIso(ISO.DATE); formatter.setIso(ISO.DATE);
Date date = getDate(2009, Calendar.JUNE, 1, 14, 23, 5, 3); Date date = getDate(2009, Calendar.JUNE, 1, 14, 23, 5, 3);
assertThat(formatter.print(date, Locale.US), is("2009-06-01")); assertThat(formatter.print(date, Locale.US)).isEqualTo("2009-06-01");
assertThat(formatter.parse("2009-6-01", Locale.US), assertThat(formatter.parse("2009-6-01", Locale.US))
is(getDate(2009, Calendar.JUNE, 1))); .isEqualTo(getDate(2009, Calendar.JUNE, 1));
} }
@Test @Test
@ -121,9 +122,9 @@ public class DateFormatterTests {
formatter.setTimeZone(UTC); formatter.setTimeZone(UTC);
formatter.setIso(ISO.TIME); formatter.setIso(ISO.TIME);
Date date = getDate(2009, Calendar.JANUARY, 1, 14, 23, 5, 3); Date date = getDate(2009, Calendar.JANUARY, 1, 14, 23, 5, 3);
assertThat(formatter.print(date, Locale.US), is("14:23:05.003Z")); assertThat(formatter.print(date, Locale.US)).isEqualTo("14:23:05.003Z");
assertThat(formatter.parse("14:23:05.003Z", Locale.US), assertThat(formatter.parse("14:23:05.003Z", Locale.US))
is(getDate(1970, Calendar.JANUARY, 1, 14, 23, 5, 3))); .isEqualTo(getDate(1970, Calendar.JANUARY, 1, 14, 23, 5, 3));
} }
@Test @Test
@ -132,8 +133,8 @@ public class DateFormatterTests {
formatter.setTimeZone(UTC); formatter.setTimeZone(UTC);
formatter.setIso(ISO.DATE_TIME); formatter.setIso(ISO.DATE_TIME);
Date date = getDate(2009, Calendar.JUNE, 1, 14, 23, 5, 3); Date date = getDate(2009, Calendar.JUNE, 1, 14, 23, 5, 3);
assertThat(formatter.print(date, Locale.US), is("2009-06-01T14:23:05.003Z")); assertThat(formatter.print(date, Locale.US)).isEqualTo("2009-06-01T14:23:05.003Z");
assertThat(formatter.parse("2009-06-01T14:23:05.003Z", Locale.US), is(date)); assertThat(formatter.parse("2009-06-01T14:23:05.003Z", Locale.US)).isEqualTo(date);
} }
@Test @Test
@ -162,10 +163,12 @@ public class DateFormatterTests {
formatter.setStylePattern(style); formatter.setStylePattern(style);
DateTimeFormatter jodaFormatter = DateTimeFormat.forStyle(style).withLocale(locale).withZone(DateTimeZone.UTC); DateTimeFormatter jodaFormatter = DateTimeFormat.forStyle(style).withLocale(locale).withZone(DateTimeZone.UTC);
String jodaPrinted = jodaFormatter.print(date.getTime()); String jodaPrinted = jodaFormatter.print(date.getTime());
assertThat("Unable to print style pattern " + style, assertThat(formatter.print(date, locale))
formatter.print(date, locale), is(equalTo(jodaPrinted))); .as("Unable to print style pattern " + style)
assertThat("Unable to parse style pattern " + style, .isEqualTo(jodaPrinted);
formatter.parse(jodaPrinted, locale), is(equalTo(date))); assertThat(formatter.parse(jodaPrinted, locale))
.as("Unable to parse style pattern " + style)
.isEqualTo(date);
} }
@Test @Test
@ -187,16 +190,16 @@ public class DateFormatterTests {
formatter.setPattern("yyyy"); formatter.setPattern("yyyy");
Date date = getDate(2009, Calendar.JUNE, 1, 14, 23, 5, 3); Date date = getDate(2009, Calendar.JUNE, 1, 14, 23, 5, 3);
assertThat("uses pattern",formatter.print(date, Locale.US), is("2009")); assertThat(formatter.print(date, Locale.US)).as("uses pattern").isEqualTo("2009");
formatter.setPattern(""); formatter.setPattern("");
assertThat("uses ISO", formatter.print(date, Locale.US), is("2009-06-01T14:23:05.003Z")); assertThat(formatter.print(date, Locale.US)).as("uses ISO").isEqualTo("2009-06-01T14:23:05.003Z");
formatter.setIso(ISO.NONE); formatter.setIso(ISO.NONE);
assertThat("uses style pattern", formatter.print(date, Locale.US), is("June 1, 2009")); assertThat(formatter.print(date, Locale.US)).as("uses style pattern").isEqualTo("June 1, 2009");
formatter.setStylePattern(""); formatter.setStylePattern("");
assertThat("uses style", formatter.print(date, Locale.US), is("6/1/09")); assertThat(formatter.print(date, Locale.US)).as("uses style").isEqualTo("6/1/09");
} }

View File

@ -36,8 +36,7 @@ import org.springframework.format.annotation.DateTimeFormat.ISO;
import org.springframework.format.support.FormattingConversionService; import org.springframework.format.support.FormattingConversionService;
import org.springframework.validation.DataBinder; import org.springframework.validation.DataBinder;
import static org.hamcrest.MatcherAssert.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNotNull;
@ -218,7 +217,7 @@ public class DateFormattingTests {
public void stringToDateWithoutGlobalFormat() { public void stringToDateWithoutGlobalFormat() {
String string = "Sat, 12 Aug 1995 13:30:00 GM"; String string = "Sat, 12 Aug 1995 13:30:00 GM";
Date date = this.conversionService.convert(string, Date.class); Date date = this.conversionService.convert(string, Date.class);
assertThat(date, equalTo(new Date(string))); assertThat(date).isEqualTo(new Date(string));
} }
@Test // SPR-10105 @Test // SPR-10105

View File

@ -20,10 +20,11 @@ import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter; import org.joda.time.format.DateTimeFormatter;
import org.junit.Test; import org.junit.Test;
import static org.hamcrest.MatcherAssert.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.sameInstance;
/** /**
* @author Phillip Webb * @author Phillip Webb
@ -36,28 +37,28 @@ public class DateTimeFormatterFactoryBeanTests {
@Test @Test
public void isSingleton() { public void isSingleton() {
assertThat(factory.isSingleton(), is(true)); assertThat(factory.isSingleton()).isTrue();
} }
@Test @Test
@SuppressWarnings("rawtypes") @SuppressWarnings("rawtypes")
public void getObjectType() { public void getObjectType() {
assertThat(factory.getObjectType(), is(equalTo((Class) DateTimeFormatter.class))); assertThat(factory.getObjectType()).isEqualTo(DateTimeFormatter.class);
} }
@Test @Test
public void getObject() { public void getObject() {
factory.afterPropertiesSet(); factory.afterPropertiesSet();
assertThat(factory.getObject(), is(equalTo(DateTimeFormat.mediumDateTime()))); assertThat(factory.getObject()).isEqualTo(DateTimeFormat.mediumDateTime());
} }
@Test @Test
public void getObjectIsAlwaysSingleton() { public void getObjectIsAlwaysSingleton() {
factory.afterPropertiesSet(); factory.afterPropertiesSet();
DateTimeFormatter formatter = factory.getObject(); DateTimeFormatter formatter = factory.getObject();
assertThat(formatter, is(equalTo(DateTimeFormat.mediumDateTime()))); assertThat(formatter).isEqualTo(DateTimeFormat.mediumDateTime());
factory.setStyle("LL"); factory.setStyle("LL");
assertThat(factory.getObject(), is(sameInstance(formatter))); assertThat(factory.getObject()).isSameAs(formatter);
} }
} }

View File

@ -27,11 +27,7 @@ import org.junit.Test;
import org.springframework.format.annotation.DateTimeFormat.ISO; import org.springframework.format.annotation.DateTimeFormat.ISO;
import static org.hamcrest.MatcherAssert.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.nullValue;
import static org.hamcrest.Matchers.sameInstance;
import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertTrue;
/** /**
@ -55,27 +51,27 @@ public class DateTimeFormatterFactoryTests {
@Test @Test
public void createDateTimeFormatter() { public void createDateTimeFormatter() {
assertThat(factory.createDateTimeFormatter(), is(equalTo(DateTimeFormat.mediumDateTime()))); assertThat(factory.createDateTimeFormatter()).isEqualTo(DateTimeFormat.mediumDateTime());
} }
@Test @Test
public void createDateTimeFormatterWithPattern() { public void createDateTimeFormatterWithPattern() {
factory = new DateTimeFormatterFactory("yyyyMMddHHmmss"); factory = new DateTimeFormatterFactory("yyyyMMddHHmmss");
DateTimeFormatter formatter = factory.createDateTimeFormatter(); DateTimeFormatter formatter = factory.createDateTimeFormatter();
assertThat(formatter.print(dateTime), is("20091021121000")); assertThat(formatter.print(dateTime)).isEqualTo("20091021121000");
} }
@Test @Test
public void createDateTimeFormatterWithNullFallback() { public void createDateTimeFormatterWithNullFallback() {
DateTimeFormatter formatter = factory.createDateTimeFormatter(null); DateTimeFormatter formatter = factory.createDateTimeFormatter(null);
assertThat(formatter, is(nullValue())); assertThat(formatter).isNull();
} }
@Test @Test
public void createDateTimeFormatterWithFallback() { public void createDateTimeFormatterWithFallback() {
DateTimeFormatter fallback = DateTimeFormat.forStyle("LL"); DateTimeFormatter fallback = DateTimeFormat.forStyle("LL");
DateTimeFormatter formatter = factory.createDateTimeFormatter(fallback); DateTimeFormatter formatter = factory.createDateTimeFormatter(fallback);
assertThat(formatter, is(sameInstance(fallback))); assertThat(formatter).isSameAs(fallback);
} }
@Test @Test
@ -86,10 +82,10 @@ public class DateTimeFormatterFactoryTests {
assertTrue(value.endsWith("12:10 PM")); assertTrue(value.endsWith("12:10 PM"));
factory.setIso(ISO.DATE); factory.setIso(ISO.DATE);
assertThat(applyLocale(factory.createDateTimeFormatter()).print(dateTime), is("2009-10-21")); assertThat(applyLocale(factory.createDateTimeFormatter()).print(dateTime)).isEqualTo("2009-10-21");
factory.setPattern("yyyyMMddHHmmss"); factory.setPattern("yyyyMMddHHmmss");
assertThat(factory.createDateTimeFormatter().print(dateTime), is("20091021121000")); assertThat(factory.createDateTimeFormatter().print(dateTime)).isEqualTo("20091021121000");
} }
@Test @Test
@ -99,7 +95,7 @@ public class DateTimeFormatterFactoryTests {
DateTimeZone dateTimeZone = DateTimeZone.forTimeZone(TEST_TIMEZONE); DateTimeZone dateTimeZone = DateTimeZone.forTimeZone(TEST_TIMEZONE);
DateTime dateTime = new DateTime(2009, 10, 21, 12, 10, 00, 00, dateTimeZone); DateTime dateTime = new DateTime(2009, 10, 21, 12, 10, 00, 00, dateTimeZone);
String offset = (TEST_TIMEZONE.equals(NEW_YORK) ? "-0400" : "+0200"); String offset = (TEST_TIMEZONE.equals(NEW_YORK) ? "-0400" : "+0200");
assertThat(factory.createDateTimeFormatter().print(dateTime), is("20091021121000 " + offset)); assertThat(factory.createDateTimeFormatter().print(dateTime)).isEqualTo("20091021121000 " + offset);
} }
private DateTimeFormatter applyLocale(DateTimeFormatter dateTimeFormatter) { private DateTimeFormatter applyLocale(DateTimeFormatter dateTimeFormatter) {

View File

@ -46,8 +46,7 @@ import org.springframework.format.annotation.DateTimeFormat.ISO;
import org.springframework.format.support.FormattingConversionService; import org.springframework.format.support.FormattingConversionService;
import org.springframework.validation.DataBinder; import org.springframework.validation.DataBinder;
import static org.hamcrest.MatcherAssert.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertTrue;
@ -453,7 +452,7 @@ public class JodaTimeFormattingTests {
public void stringToDateWithoutGlobalFormat() { public void stringToDateWithoutGlobalFormat() {
String string = "Sat, 12 Aug 1995 13:30:00 GM"; String string = "Sat, 12 Aug 1995 13:30:00 GM";
Date date = this.conversionService.convert(string, Date.class); Date date = this.conversionService.convert(string, Date.class);
assertThat(date, equalTo(new Date(string))); assertThat(date).isEqualTo(new Date(string));
} }
@Test // SPR-10105 @Test // SPR-10105

View File

@ -21,10 +21,11 @@ import java.time.format.FormatStyle;
import org.junit.Test; import org.junit.Test;
import static org.hamcrest.MatcherAssert.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.sameInstance;
/** /**
* @author Phillip Webb * @author Phillip Webb
@ -37,27 +38,27 @@ public class DateTimeFormatterFactoryBeanTests {
@Test @Test
public void isSingleton() { public void isSingleton() {
assertThat(factory.isSingleton(), is(true)); assertThat(factory.isSingleton()).isTrue();
} }
@Test @Test
public void getObjectType() { public void getObjectType() {
assertThat(factory.getObjectType(), is(equalTo(DateTimeFormatter.class))); assertThat(factory.getObjectType()).isEqualTo(DateTimeFormatter.class);
} }
@Test @Test
public void getObject() { public void getObject() {
factory.afterPropertiesSet(); factory.afterPropertiesSet();
assertThat(factory.getObject().toString(), is(equalTo(DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM).toString()))); assertThat(factory.getObject().toString()).isEqualTo(DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM).toString());
} }
@Test @Test
public void getObjectIsAlwaysSingleton() { public void getObjectIsAlwaysSingleton() {
factory.afterPropertiesSet(); factory.afterPropertiesSet();
DateTimeFormatter formatter = factory.getObject(); DateTimeFormatter formatter = factory.getObject();
assertThat(formatter.toString(), is(equalTo(DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM).toString()))); assertThat(formatter.toString()).isEqualTo(DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM).toString());
factory.setStylePattern("LL"); factory.setStylePattern("LL");
assertThat(factory.getObject(), is(sameInstance(formatter))); assertThat(factory.getObject()).isSameAs(formatter);
} }
} }

View File

@ -28,11 +28,7 @@ import org.junit.Test;
import org.springframework.format.annotation.DateTimeFormat.ISO; import org.springframework.format.annotation.DateTimeFormat.ISO;
import static org.hamcrest.MatcherAssert.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.nullValue;
import static org.hamcrest.Matchers.sameInstance;
import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertTrue;
/** /**
@ -56,27 +52,27 @@ public class DateTimeFormatterFactoryTests {
@Test @Test
public void createDateTimeFormatter() { public void createDateTimeFormatter() {
assertThat(factory.createDateTimeFormatter().toString(), is(equalTo(DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM).toString()))); assertThat(factory.createDateTimeFormatter().toString()).isEqualTo(DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM).toString());
} }
@Test @Test
public void createDateTimeFormatterWithPattern() { public void createDateTimeFormatterWithPattern() {
factory = new DateTimeFormatterFactory("yyyyMMddHHmmss"); factory = new DateTimeFormatterFactory("yyyyMMddHHmmss");
DateTimeFormatter formatter = factory.createDateTimeFormatter(); DateTimeFormatter formatter = factory.createDateTimeFormatter();
assertThat(formatter.format(dateTime), is("20091021121000")); assertThat(formatter.format(dateTime)).isEqualTo("20091021121000");
} }
@Test @Test
public void createDateTimeFormatterWithNullFallback() { public void createDateTimeFormatterWithNullFallback() {
DateTimeFormatter formatter = factory.createDateTimeFormatter(null); DateTimeFormatter formatter = factory.createDateTimeFormatter(null);
assertThat(formatter, is(nullValue())); assertThat(formatter).isNull();
} }
@Test @Test
public void createDateTimeFormatterWithFallback() { public void createDateTimeFormatterWithFallback() {
DateTimeFormatter fallback = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.LONG); DateTimeFormatter fallback = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.LONG);
DateTimeFormatter formatter = factory.createDateTimeFormatter(fallback); DateTimeFormatter formatter = factory.createDateTimeFormatter(fallback);
assertThat(formatter, is(sameInstance(fallback))); assertThat(formatter).isSameAs(fallback);
} }
@Test @Test
@ -87,10 +83,10 @@ public class DateTimeFormatterFactoryTests {
assertTrue(value.endsWith("12:10 PM")); assertTrue(value.endsWith("12:10 PM"));
factory.setIso(ISO.DATE); factory.setIso(ISO.DATE);
assertThat(applyLocale(factory.createDateTimeFormatter()).format(dateTime), is("2009-10-21")); assertThat(applyLocale(factory.createDateTimeFormatter()).format(dateTime)).isEqualTo("2009-10-21");
factory.setPattern("yyyyMMddHHmmss"); factory.setPattern("yyyyMMddHHmmss");
assertThat(factory.createDateTimeFormatter().format(dateTime), is("20091021121000")); assertThat(factory.createDateTimeFormatter().format(dateTime)).isEqualTo("20091021121000");
} }
@Test @Test
@ -100,7 +96,7 @@ public class DateTimeFormatterFactoryTests {
ZoneId dateTimeZone = TEST_TIMEZONE.toZoneId(); ZoneId dateTimeZone = TEST_TIMEZONE.toZoneId();
ZonedDateTime dateTime = ZonedDateTime.of(2009, 10, 21, 12, 10, 00, 00, dateTimeZone); ZonedDateTime dateTime = ZonedDateTime.of(2009, 10, 21, 12, 10, 00, 00, dateTimeZone);
String offset = (TEST_TIMEZONE.equals(NEW_YORK) ? "-0400" : "+0200"); String offset = (TEST_TIMEZONE.equals(NEW_YORK) ? "-0400" : "+0200");
assertThat(factory.createDateTimeFormatter().format(dateTime), is("20091021121000 " + offset)); assertThat(factory.createDateTimeFormatter().format(dateTime)).isEqualTo("20091021121000 " + offset);
} }
private DateTimeFormatter applyLocale(DateTimeFormatter dateTimeFormatter) { private DateTimeFormatter applyLocale(DateTimeFormatter dateTimeFormatter) {

View File

@ -21,8 +21,9 @@ import javax.naming.spi.NamingManager;
import org.junit.Test; import org.junit.Test;
import static org.hamcrest.MatcherAssert.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.equalTo;
/** /**
* Tests for {@link JndiLocatorDelegate}. * Tests for {@link JndiLocatorDelegate}.
@ -40,7 +41,7 @@ public class JndiLocatorDelegateTests {
builderField.set(null, null); builderField.set(null, null);
try { try {
assertThat(JndiLocatorDelegate.isDefaultJndiEnvironmentAvailable(), equalTo(false)); assertThat(JndiLocatorDelegate.isDefaultJndiEnvironmentAvailable()).isEqualTo(false);
} }
finally { finally {
builderField.set(null, oldBuilder); builderField.set(null, oldBuilder);

View File

@ -23,9 +23,7 @@ import org.junit.Test;
import org.springframework.tests.mock.jndi.SimpleNamingContext; import org.springframework.tests.mock.jndi.SimpleNamingContext;
import static org.hamcrest.CoreMatchers.equalTo; import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.CoreMatchers.nullValue;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
/** /**
@ -40,7 +38,7 @@ public class JndiPropertySourceTests {
@Test @Test
public void nonExistentProperty() { public void nonExistentProperty() {
JndiPropertySource ps = new JndiPropertySource("jndiProperties"); JndiPropertySource ps = new JndiPropertySource("jndiProperties");
assertThat(ps.getProperty("bogus"), nullValue()); assertThat(ps.getProperty("bogus")).isNull();
} }
@Test @Test
@ -59,7 +57,7 @@ public class JndiPropertySourceTests {
jndiLocator.setJndiTemplate(jndiTemplate); jndiLocator.setJndiTemplate(jndiTemplate);
JndiPropertySource ps = new JndiPropertySource("jndiProperties", jndiLocator); JndiPropertySource ps = new JndiPropertySource("jndiProperties", jndiLocator);
assertThat(ps.getProperty("p1"), equalTo("v1")); assertThat(ps.getProperty("p1")).isEqualTo("v1");
} }
@Test @Test
@ -78,7 +76,7 @@ public class JndiPropertySourceTests {
jndiLocator.setJndiTemplate(jndiTemplate); jndiLocator.setJndiTemplate(jndiTemplate);
JndiPropertySource ps = new JndiPropertySource("jndiProperties", jndiLocator); JndiPropertySource ps = new JndiPropertySource("jndiProperties", jndiLocator);
assertThat(ps.getProperty("p1"), equalTo("v1")); assertThat(ps.getProperty("p1")).isEqualTo("v1");
} }
@Test @Test
@ -92,7 +90,7 @@ public class JndiPropertySourceTests {
jndiLocator.setResourceRef(true); jndiLocator.setResourceRef(true);
JndiPropertySource ps = new JndiPropertySource("jndiProperties", jndiLocator); JndiPropertySource ps = new JndiPropertySource("jndiProperties", jndiLocator);
assertThat(ps.getProperty("propertyKey:defaultValue"), nullValue()); assertThat(ps.getProperty("propertyKey:defaultValue")).isNull();
} }
@Test @Test
@ -107,7 +105,7 @@ public class JndiPropertySourceTests {
jndiLocator.setResourceRef(false); jndiLocator.setResourceRef(false);
JndiPropertySource ps = new JndiPropertySource("jndiProperties", jndiLocator); JndiPropertySource ps = new JndiPropertySource("jndiProperties", jndiLocator);
assertThat(ps.getProperty("my:key"), equalTo("my:value")); assertThat(ps.getProperty("my:key")).isEqualTo("my:value");
} }
} }

View File

@ -21,8 +21,8 @@ import java.lang.annotation.RetentionPolicy;
import org.junit.Test; import org.junit.Test;
import static org.hamcrest.CoreMatchers.is; import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.MatcherAssert.assertThat;
/** /**
* Unit tests for {@link AnnotationAsyncExecutionInterceptor}. * Unit tests for {@link AnnotationAsyncExecutionInterceptor}.
@ -38,23 +38,23 @@ public class AnnotationAsyncExecutionInterceptorTests {
AnnotationAsyncExecutionInterceptor i = new AnnotationAsyncExecutionInterceptor(null); AnnotationAsyncExecutionInterceptor i = new AnnotationAsyncExecutionInterceptor(null);
{ // method level { // method level
class C { @Async("qMethod") void m() { } } class C { @Async("qMethod") void m() { } }
assertThat(i.getExecutorQualifier(C.class.getDeclaredMethod("m")), is("qMethod")); assertThat(i.getExecutorQualifier(C.class.getDeclaredMethod("m"))).isEqualTo("qMethod");
} }
{ // class level { // class level
@Async("qClass") class C { void m() { } } @Async("qClass") class C { void m() { } }
assertThat(i.getExecutorQualifier(C.class.getDeclaredMethod("m")), is("qClass")); assertThat(i.getExecutorQualifier(C.class.getDeclaredMethod("m"))).isEqualTo("qClass");
} }
{ // method and class level -> method value overrides { // method and class level -> method value overrides
@Async("qClass") class C { @Async("qMethod") void m() { } } @Async("qClass") class C { @Async("qMethod") void m() { } }
assertThat(i.getExecutorQualifier(C.class.getDeclaredMethod("m")), is("qMethod")); assertThat(i.getExecutorQualifier(C.class.getDeclaredMethod("m"))).isEqualTo("qMethod");
} }
{ // method and class level -> method value, even if empty, overrides { // method and class level -> method value, even if empty, overrides
@Async("qClass") class C { @Async void m() { } } @Async("qClass") class C { @Async void m() { } }
assertThat(i.getExecutorQualifier(C.class.getDeclaredMethod("m")), is("")); assertThat(i.getExecutorQualifier(C.class.getDeclaredMethod("m"))).isEqualTo("");
} }
{ // meta annotation with qualifier { // meta annotation with qualifier
@MyAsync class C { void m() { } } @MyAsync class C { void m() { } }
assertThat(i.getExecutorQualifier(C.class.getDeclaredMethod("m")), is("qMeta")); assertThat(i.getExecutorQualifier(C.class.getDeclaredMethod("m"))).isEqualTo("qMeta");
} }
} }

View File

@ -54,12 +54,8 @@ import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import org.springframework.util.ReflectionUtils; import org.springframework.util.ReflectionUtils;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.anyOf;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.Matchers.startsWith;
import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertTrue;
@ -79,7 +75,7 @@ public class EnableAsyncTests {
ctx.refresh(); ctx.refresh();
AsyncBean asyncBean = ctx.getBean(AsyncBean.class); AsyncBean asyncBean = ctx.getBean(AsyncBean.class);
assertThat(AopUtils.isAopProxy(asyncBean), is(true)); assertThat(AopUtils.isAopProxy(asyncBean)).isTrue();
asyncBean.work(); asyncBean.work();
ctx.close(); ctx.close();
} }
@ -92,7 +88,7 @@ public class EnableAsyncTests {
AsyncBeanUser asyncBeanUser = ctx.getBean(AsyncBeanUser.class); AsyncBeanUser asyncBeanUser = ctx.getBean(AsyncBeanUser.class);
AsyncBean asyncBean = asyncBeanUser.getAsyncBean(); AsyncBean asyncBean = asyncBeanUser.getAsyncBean();
assertThat(AopUtils.isAopProxy(asyncBean), is(true)); assertThat(AopUtils.isAopProxy(asyncBean)).isTrue();
asyncBean.work(); asyncBean.work();
ctx.close(); ctx.close();
} }
@ -125,13 +121,13 @@ public class EnableAsyncTests {
AsyncBeanWithExecutorQualifiedByName asyncBean = ctx.getBean(AsyncBeanWithExecutorQualifiedByName.class); AsyncBeanWithExecutorQualifiedByName asyncBean = ctx.getBean(AsyncBeanWithExecutorQualifiedByName.class);
Future<Thread> workerThread0 = asyncBean.work0(); Future<Thread> workerThread0 = asyncBean.work0();
assertThat(workerThread0.get().getName(), not(anyOf(startsWith("e1-"), startsWith("otherExecutor-")))); assertThat(workerThread0.get().getName()).doesNotStartWith("e1-").doesNotStartWith("otherExecutor-");
Future<Thread> workerThread = asyncBean.work(); Future<Thread> workerThread = asyncBean.work();
assertThat(workerThread.get().getName(), startsWith("e1-")); assertThat(workerThread.get().getName()).startsWith("e1-");
Future<Thread> workerThread2 = asyncBean.work2(); Future<Thread> workerThread2 = asyncBean.work2();
assertThat(workerThread2.get().getName(), startsWith("otherExecutor-")); assertThat(workerThread2.get().getName()).startsWith("otherExecutor-");
Future<Thread> workerThread3 = asyncBean.work3(); Future<Thread> workerThread3 = asyncBean.work3();
assertThat(workerThread3.get().getName(), startsWith("otherExecutor-")); assertThat(workerThread3.get().getName()).startsWith("otherExecutor-");
ctx.close(); ctx.close();
} }
@ -143,7 +139,7 @@ public class EnableAsyncTests {
ctx.refresh(); ctx.refresh();
AsyncAnnotationBeanPostProcessor bpp = ctx.getBean(AsyncAnnotationBeanPostProcessor.class); AsyncAnnotationBeanPostProcessor bpp = ctx.getBean(AsyncAnnotationBeanPostProcessor.class);
assertThat(bpp.getOrder(), is(Ordered.LOWEST_PRECEDENCE)); assertThat(bpp.getOrder()).isEqualTo(Ordered.LOWEST_PRECEDENCE);
ctx.close(); ctx.close();
} }
@ -155,7 +151,7 @@ public class EnableAsyncTests {
ctx.refresh(); ctx.refresh();
AsyncAnnotationBeanPostProcessor bpp = ctx.getBean(AsyncAnnotationBeanPostProcessor.class); AsyncAnnotationBeanPostProcessor bpp = ctx.getBean(AsyncAnnotationBeanPostProcessor.class);
assertThat(bpp.getOrder(), is(Ordered.HIGHEST_PRECEDENCE)); assertThat(bpp.getOrder()).isEqualTo(Ordered.HIGHEST_PRECEDENCE);
ctx.close(); ctx.close();
} }
@ -206,7 +202,7 @@ public class EnableAsyncTests {
.atMost(500, TimeUnit.MILLISECONDS) .atMost(500, TimeUnit.MILLISECONDS)
.pollInterval(10, TimeUnit.MILLISECONDS) .pollInterval(10, TimeUnit.MILLISECONDS)
.until(() -> asyncBean.getThreadOfExecution() != null); .until(() -> asyncBean.getThreadOfExecution() != null);
assertThat(asyncBean.getThreadOfExecution().getName(), startsWith("Custom-")); assertThat(asyncBean.getThreadOfExecution().getName()).startsWith("Custom-");
ctx.close(); ctx.close();
} }
@ -224,7 +220,7 @@ public class EnableAsyncTests {
.atMost(500, TimeUnit.MILLISECONDS) .atMost(500, TimeUnit.MILLISECONDS)
.pollInterval(10, TimeUnit.MILLISECONDS) .pollInterval(10, TimeUnit.MILLISECONDS)
.until(() -> asyncBean.getThreadOfExecution() != null); .until(() -> asyncBean.getThreadOfExecution() != null);
assertThat(asyncBean.getThreadOfExecution().getName(), startsWith("Custom-")); assertThat(asyncBean.getThreadOfExecution().getName()).startsWith("Custom-");
ctx.close(); ctx.close();
} }
@ -263,7 +259,7 @@ public class EnableAsyncTests {
.atMost(500, TimeUnit.MILLISECONDS) .atMost(500, TimeUnit.MILLISECONDS)
.pollInterval(10, TimeUnit.MILLISECONDS) .pollInterval(10, TimeUnit.MILLISECONDS)
.until(() -> asyncBean.getThreadOfExecution() != null); .until(() -> asyncBean.getThreadOfExecution() != null);
assertThat(asyncBean.getThreadOfExecution().getName(), startsWith("Post-")); assertThat(asyncBean.getThreadOfExecution().getName()).startsWith("Post-");
ctx.close(); ctx.close();
} }
@ -300,7 +296,7 @@ public class EnableAsyncTests {
.atMost(500, TimeUnit.MILLISECONDS) .atMost(500, TimeUnit.MILLISECONDS)
.pollInterval(10, TimeUnit.MILLISECONDS) .pollInterval(10, TimeUnit.MILLISECONDS)
.until(() -> asyncBean.getThreadOfExecution() != null); .until(() -> asyncBean.getThreadOfExecution() != null);
assertThat(asyncBean.getThreadOfExecution().getName(), startsWith("Custom-")); assertThat(asyncBean.getThreadOfExecution().getName()).startsWith("Custom-");
ctx.close(); ctx.close();
} }
@ -316,7 +312,7 @@ public class EnableAsyncTests {
.atMost(500, TimeUnit.MILLISECONDS) .atMost(500, TimeUnit.MILLISECONDS)
.pollInterval(10, TimeUnit.MILLISECONDS) .pollInterval(10, TimeUnit.MILLISECONDS)
.until(() -> asyncBean.getThreadOfExecution() != null); .until(() -> asyncBean.getThreadOfExecution() != null);
assertThat(asyncBean.getThreadOfExecution().getName(), startsWith("Custom-")); assertThat(asyncBean.getThreadOfExecution().getName()).startsWith("Custom-");
ctx.close(); ctx.close();
} }

View File

@ -35,12 +35,7 @@ import org.springframework.scheduling.config.TaskManagementConfigUtils;
import org.springframework.tests.Assume; import org.springframework.tests.Assume;
import org.springframework.tests.TestGroup; import org.springframework.tests.TestGroup;
import static org.hamcrest.MatcherAssert.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.both;
import static org.hamcrest.Matchers.greaterThan;
import static org.hamcrest.Matchers.greaterThanOrEqualTo;
import static org.hamcrest.Matchers.lessThanOrEqualTo;
import static org.hamcrest.Matchers.startsWith;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertTrue;
@ -72,7 +67,7 @@ public class EnableSchedulingTests {
assertEquals(2, ctx.getBean(ScheduledTaskHolder.class).getScheduledTasks().size()); assertEquals(2, ctx.getBean(ScheduledTaskHolder.class).getScheduledTasks().size());
Thread.sleep(100); Thread.sleep(100);
assertThat(ctx.getBean(AtomicInteger.class).get(), greaterThanOrEqualTo(10)); assertThat(ctx.getBean(AtomicInteger.class).get()).isGreaterThanOrEqualTo(10);
} }
@Test @Test
@ -83,7 +78,7 @@ public class EnableSchedulingTests {
assertEquals(2, ctx.getBean(ScheduledTaskHolder.class).getScheduledTasks().size()); assertEquals(2, ctx.getBean(ScheduledTaskHolder.class).getScheduledTasks().size());
Thread.sleep(100); Thread.sleep(100);
assertThat(ctx.getBean(AtomicInteger.class).get(), greaterThanOrEqualTo(10)); assertThat(ctx.getBean(AtomicInteger.class).get()).isGreaterThanOrEqualTo(10);
} }
@Test @Test
@ -94,8 +89,8 @@ public class EnableSchedulingTests {
assertEquals(1, ctx.getBean(ScheduledTaskHolder.class).getScheduledTasks().size()); assertEquals(1, ctx.getBean(ScheduledTaskHolder.class).getScheduledTasks().size());
Thread.sleep(100); Thread.sleep(100);
assertThat(ctx.getBean(AtomicInteger.class).get(), greaterThanOrEqualTo(10)); assertThat(ctx.getBean(AtomicInteger.class).get()).isGreaterThanOrEqualTo(10);
assertThat(ctx.getBean(ExplicitSchedulerConfig.class).threadName, startsWith("explicitScheduler-")); assertThat(ctx.getBean(ExplicitSchedulerConfig.class).threadName).startsWith("explicitScheduler-");
assertTrue(Arrays.asList(ctx.getDefaultListableBeanFactory().getDependentBeans("myTaskScheduler")).contains( assertTrue(Arrays.asList(ctx.getDefaultListableBeanFactory().getDependentBeans("myTaskScheduler")).contains(
TaskManagementConfigUtils.SCHEDULED_ANNOTATION_PROCESSOR_BEAN_NAME)); TaskManagementConfigUtils.SCHEDULED_ANNOTATION_PROCESSOR_BEAN_NAME));
} }
@ -114,8 +109,8 @@ public class EnableSchedulingTests {
assertEquals(1, ctx.getBean(ScheduledTaskHolder.class).getScheduledTasks().size()); assertEquals(1, ctx.getBean(ScheduledTaskHolder.class).getScheduledTasks().size());
Thread.sleep(100); Thread.sleep(100);
assertThat(ctx.getBean(AtomicInteger.class).get(), greaterThanOrEqualTo(10)); assertThat(ctx.getBean(AtomicInteger.class).get()).isGreaterThanOrEqualTo(10);
assertThat(ctx.getBean(ExplicitScheduledTaskRegistrarConfig.class).threadName, startsWith("explicitScheduler1")); assertThat(ctx.getBean(ExplicitScheduledTaskRegistrarConfig.class).threadName).startsWith("explicitScheduler1");
} }
@Test @Test
@ -137,7 +132,7 @@ public class EnableSchedulingTests {
SchedulingEnabled_withAmbiguousTaskSchedulers_andSingleTask_disambiguatedByScheduledTaskRegistrar.class); SchedulingEnabled_withAmbiguousTaskSchedulers_andSingleTask_disambiguatedByScheduledTaskRegistrar.class);
Thread.sleep(100); Thread.sleep(100);
assertThat(ctx.getBean(ThreadAwareWorker.class).executedByThread, startsWith("explicitScheduler2-")); assertThat(ctx.getBean(ThreadAwareWorker.class).executedByThread).startsWith("explicitScheduler2-");
} }
@Test @Test
@ -148,7 +143,7 @@ public class EnableSchedulingTests {
SchedulingEnabled_withAmbiguousTaskSchedulers_andSingleTask_disambiguatedBySchedulerNameAttribute.class); SchedulingEnabled_withAmbiguousTaskSchedulers_andSingleTask_disambiguatedBySchedulerNameAttribute.class);
Thread.sleep(100); Thread.sleep(100);
assertThat(ctx.getBean(ThreadAwareWorker.class).executedByThread, startsWith("explicitScheduler2-")); assertThat(ctx.getBean(ThreadAwareWorker.class).executedByThread).startsWith("explicitScheduler2-");
} }
@Test @Test
@ -158,7 +153,7 @@ public class EnableSchedulingTests {
ctx = new AnnotationConfigApplicationContext(SchedulingEnabled_withTaskAddedVia_configureTasks.class); ctx = new AnnotationConfigApplicationContext(SchedulingEnabled_withTaskAddedVia_configureTasks.class);
Thread.sleep(100); Thread.sleep(100);
assertThat(ctx.getBean(ThreadAwareWorker.class).executedByThread, startsWith("taskScheduler-")); assertThat(ctx.getBean(ThreadAwareWorker.class).executedByThread).startsWith("taskScheduler-");
} }
@Test @Test
@ -168,7 +163,7 @@ public class EnableSchedulingTests {
ctx = new AnnotationConfigApplicationContext(TriggerTaskConfig.class); ctx = new AnnotationConfigApplicationContext(TriggerTaskConfig.class);
Thread.sleep(100); Thread.sleep(100);
assertThat(ctx.getBean(AtomicInteger.class).get(), greaterThan(1)); assertThat(ctx.getBean(AtomicInteger.class).get()).isGreaterThan(1);
} }
@Test @Test
@ -182,7 +177,7 @@ public class EnableSchedulingTests {
// The @Scheduled method should have been called at least once but // The @Scheduled method should have been called at least once but
// not more times than the delay allows. // not more times than the delay allows.
assertThat(counter.get(), both(greaterThan(0)).and(lessThanOrEqualTo(10))); assertThat(counter.get()).isBetween(1, 10);
} }

View File

@ -30,8 +30,7 @@ import org.springframework.scheduling.Trigger;
import org.springframework.scheduling.TriggerContext; import org.springframework.scheduling.TriggerContext;
import org.springframework.scheduling.support.ScheduledMethodRunnable; import org.springframework.scheduling.support.ScheduledMethodRunnable;
import static org.hamcrest.CoreMatchers.instanceOf; import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
/** /**
@ -110,7 +109,7 @@ public class ScheduledTasksBeanDefinitionParserTests {
List<TriggerTask> tasks = (List<TriggerTask>) new DirectFieldAccessor( List<TriggerTask> tasks = (List<TriggerTask>) new DirectFieldAccessor(
this.registrar).getPropertyValue("triggerTasks"); this.registrar).getPropertyValue("triggerTasks");
assertEquals(1, tasks.size()); assertEquals(1, tasks.size());
assertThat(tasks.get(0).getTrigger(), instanceOf(TestTrigger.class)); assertThat(tasks.get(0).getTrigger()).isInstanceOf(TestTrigger.class);
} }

View File

@ -21,9 +21,10 @@ import org.junit.Test;
import org.springframework.tests.sample.beans.TestBean; import org.springframework.tests.sample.beans.TestBean;
import org.springframework.validation.DefaultMessageCodesResolver.Format; import org.springframework.validation.DefaultMessageCodesResolver.Format;
import static org.hamcrest.MatcherAssert.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.is;
/** /**
* Tests for {@link DefaultMessageCodesResolver}. * Tests for {@link DefaultMessageCodesResolver}.
@ -37,27 +38,27 @@ public class DefaultMessageCodesResolverTests {
@Test @Test
public void shouldResolveMessageCode() throws Exception { public void shouldResolveMessageCode() throws Exception {
String[] codes = resolver.resolveMessageCodes("errorCode", "objectName"); String[] codes = resolver.resolveMessageCodes("errorCode", "objectName");
assertThat(codes, is(equalTo(new String[] { assertThat(codes).containsExactly(
"errorCode.objectName", "errorCode.objectName",
"errorCode" }))); "errorCode");
} }
@Test @Test
public void shouldResolveFieldMessageCode() throws Exception { public void shouldResolveFieldMessageCode() throws Exception {
String[] codes = resolver.resolveMessageCodes("errorCode", "objectName", "field", String[] codes = resolver.resolveMessageCodes("errorCode", "objectName", "field",
TestBean.class); TestBean.class);
assertThat(codes, is(equalTo(new String[] { assertThat(codes).containsExactly(
"errorCode.objectName.field", "errorCode.objectName.field",
"errorCode.field", "errorCode.field",
"errorCode.org.springframework.tests.sample.beans.TestBean", "errorCode.org.springframework.tests.sample.beans.TestBean",
"errorCode" }))); "errorCode");
} }
@Test @Test
public void shouldResolveIndexedFieldMessageCode() throws Exception { public void shouldResolveIndexedFieldMessageCode() throws Exception {
String[] codes = resolver.resolveMessageCodes("errorCode", "objectName", "a.b[3].c[5].d", String[] codes = resolver.resolveMessageCodes("errorCode", "objectName", "a.b[3].c[5].d",
TestBean.class); TestBean.class);
assertThat(codes, is(equalTo(new String[] { assertThat(codes).containsExactly(
"errorCode.objectName.a.b[3].c[5].d", "errorCode.objectName.a.b[3].c[5].d",
"errorCode.objectName.a.b[3].c.d", "errorCode.objectName.a.b[3].c.d",
"errorCode.objectName.a.b.c.d", "errorCode.objectName.a.b.c.d",
@ -66,16 +67,16 @@ public class DefaultMessageCodesResolverTests {
"errorCode.a.b.c.d", "errorCode.a.b.c.d",
"errorCode.d", "errorCode.d",
"errorCode.org.springframework.tests.sample.beans.TestBean", "errorCode.org.springframework.tests.sample.beans.TestBean",
"errorCode" }))); "errorCode");
} }
@Test @Test
public void shouldResolveMessageCodeWithPrefix() throws Exception { public void shouldResolveMessageCodeWithPrefix() throws Exception {
resolver.setPrefix("prefix."); resolver.setPrefix("prefix.");
String[] codes = resolver.resolveMessageCodes("errorCode", "objectName"); String[] codes = resolver.resolveMessageCodes("errorCode", "objectName");
assertThat(codes, is(equalTo(new String[] { assertThat(codes).containsExactly(
"prefix.errorCode.objectName", "prefix.errorCode.objectName",
"prefix.errorCode" }))); "prefix.errorCode");
} }
@Test @Test
@ -83,11 +84,11 @@ public class DefaultMessageCodesResolverTests {
resolver.setPrefix("prefix."); resolver.setPrefix("prefix.");
String[] codes = resolver.resolveMessageCodes("errorCode", "objectName", "field", String[] codes = resolver.resolveMessageCodes("errorCode", "objectName", "field",
TestBean.class); TestBean.class);
assertThat(codes, is(equalTo(new String[] { assertThat(codes).containsExactly(
"prefix.errorCode.objectName.field", "prefix.errorCode.objectName.field",
"prefix.errorCode.field", "prefix.errorCode.field",
"prefix.errorCode.org.springframework.tests.sample.beans.TestBean", "prefix.errorCode.org.springframework.tests.sample.beans.TestBean",
"prefix.errorCode" }))); "prefix.errorCode");
} }
@Test @Test
@ -95,41 +96,41 @@ public class DefaultMessageCodesResolverTests {
resolver.setPrefix(null); resolver.setPrefix(null);
String[] codes = resolver.resolveMessageCodes("errorCode", "objectName", "field", String[] codes = resolver.resolveMessageCodes("errorCode", "objectName", "field",
TestBean.class); TestBean.class);
assertThat(codes, is(equalTo(new String[] { assertThat(codes).containsExactly(
"errorCode.objectName.field", "errorCode.objectName.field",
"errorCode.field", "errorCode.field",
"errorCode.org.springframework.tests.sample.beans.TestBean", "errorCode.org.springframework.tests.sample.beans.TestBean",
"errorCode" }))); "errorCode");
} }
@Test @Test
public void shouldSupportMalformedIndexField() throws Exception { public void shouldSupportMalformedIndexField() throws Exception {
String[] codes = resolver.resolveMessageCodes("errorCode", "objectName", "field[", String[] codes = resolver.resolveMessageCodes("errorCode", "objectName", "field[",
TestBean.class); TestBean.class);
assertThat(codes, is(equalTo(new String[] { assertThat(codes).containsExactly(
"errorCode.objectName.field[", "errorCode.objectName.field[",
"errorCode.field[", "errorCode.field[",
"errorCode.org.springframework.tests.sample.beans.TestBean", "errorCode.org.springframework.tests.sample.beans.TestBean",
"errorCode" }))); "errorCode");
} }
@Test @Test
public void shouldSupportNullFieldType() throws Exception { public void shouldSupportNullFieldType() throws Exception {
String[] codes = resolver.resolveMessageCodes("errorCode", "objectName", "field", String[] codes = resolver.resolveMessageCodes("errorCode", "objectName", "field",
null); null);
assertThat(codes, is(equalTo(new String[] { assertThat(codes).containsExactly(
"errorCode.objectName.field", "errorCode.objectName.field",
"errorCode.field", "errorCode.field",
"errorCode" }))); "errorCode");
} }
@Test @Test
public void shouldSupportPostfixFormat() throws Exception { public void shouldSupportPostfixFormat() throws Exception {
resolver.setMessageCodeFormatter(Format.POSTFIX_ERROR_CODE); resolver.setMessageCodeFormatter(Format.POSTFIX_ERROR_CODE);
String[] codes = resolver.resolveMessageCodes("errorCode", "objectName"); String[] codes = resolver.resolveMessageCodes("errorCode", "objectName");
assertThat(codes, is(equalTo(new String[] { assertThat(codes).containsExactly(
"objectName.errorCode", "objectName.errorCode",
"errorCode" }))); "errorCode");
} }
@Test @Test
@ -137,11 +138,11 @@ public class DefaultMessageCodesResolverTests {
resolver.setMessageCodeFormatter(Format.POSTFIX_ERROR_CODE); resolver.setMessageCodeFormatter(Format.POSTFIX_ERROR_CODE);
String[] codes = resolver.resolveMessageCodes("errorCode", "objectName", "field", String[] codes = resolver.resolveMessageCodes("errorCode", "objectName", "field",
TestBean.class); TestBean.class);
assertThat(codes, is(equalTo(new String[] { assertThat(codes).containsExactly(
"objectName.field.errorCode", "objectName.field.errorCode",
"field.errorCode", "field.errorCode",
"org.springframework.tests.sample.beans.TestBean.errorCode", "org.springframework.tests.sample.beans.TestBean.errorCode",
"errorCode" }))); "errorCode");
} }
@Test @Test
@ -154,9 +155,9 @@ public class DefaultMessageCodesResolverTests {
} }
}); });
String[] codes = resolver.resolveMessageCodes("errorCode", "objectName"); String[] codes = resolver.resolveMessageCodes("errorCode", "objectName");
assertThat(codes, is(equalTo(new String[] { assertThat(codes).containsExactly(
"CUSTOM-errorCode.objectName", "CUSTOM-errorCode.objectName",
"CUSTOM-errorCode" }))); "CUSTOM-errorCode");
} }
} }

View File

@ -54,9 +54,7 @@ import org.springframework.validation.FieldError;
import static java.lang.annotation.ElementType.ANNOTATION_TYPE; import static java.lang.annotation.ElementType.ANNOTATION_TYPE;
import static java.lang.annotation.ElementType.TYPE; import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.RetentionPolicy.RUNTIME; import static java.lang.annotation.RetentionPolicy.RUNTIME;
import static org.hamcrest.MatcherAssert.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.core.Is.is;
import static org.hamcrest.core.StringContains.containsString;
import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertSame; import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertTrue;
@ -98,13 +96,13 @@ public class SpringValidatorAdapterTests {
BeanPropertyBindingResult errors = new BeanPropertyBindingResult(testBean, "testBean"); BeanPropertyBindingResult errors = new BeanPropertyBindingResult(testBean, "testBean");
validatorAdapter.validate(testBean, errors); validatorAdapter.validate(testBean, errors);
assertThat(errors.getFieldErrorCount("password"), is(1)); assertThat(errors.getFieldErrorCount("password")).isEqualTo(1);
assertThat(errors.getFieldValue("password"), is("pass")); assertThat(errors.getFieldValue("password")).isEqualTo("pass");
FieldError error = errors.getFieldError("password"); FieldError error = errors.getFieldError("password");
assertNotNull(error); assertNotNull(error);
assertThat(messageSource.getMessage(error, Locale.ENGLISH), is("Size of Password is must be between 8 and 128")); assertThat(messageSource.getMessage(error, Locale.ENGLISH)).isEqualTo("Size of Password is must be between 8 and 128");
assertTrue(error.contains(ConstraintViolation.class)); assertTrue(error.contains(ConstraintViolation.class));
assertThat(error.unwrap(ConstraintViolation.class).getPropertyPath().toString(), is("password")); assertThat(error.unwrap(ConstraintViolation.class).getPropertyPath().toString()).isEqualTo("password");
} }
@Test // SPR-13406 @Test // SPR-13406
@ -116,13 +114,13 @@ public class SpringValidatorAdapterTests {
BeanPropertyBindingResult errors = new BeanPropertyBindingResult(testBean, "testBean"); BeanPropertyBindingResult errors = new BeanPropertyBindingResult(testBean, "testBean");
validatorAdapter.validate(testBean, errors); validatorAdapter.validate(testBean, errors);
assertThat(errors.getFieldErrorCount("password"), is(1)); assertThat(errors.getFieldErrorCount("password")).isEqualTo(1);
assertThat(errors.getFieldValue("password"), is("password")); assertThat(errors.getFieldValue("password")).isEqualTo("password");
FieldError error = errors.getFieldError("password"); FieldError error = errors.getFieldError("password");
assertNotNull(error); assertNotNull(error);
assertThat(messageSource.getMessage(error, Locale.ENGLISH), is("Password must be same value as Password(Confirm)")); assertThat(messageSource.getMessage(error, Locale.ENGLISH)).isEqualTo("Password must be same value as Password(Confirm)");
assertTrue(error.contains(ConstraintViolation.class)); assertTrue(error.contains(ConstraintViolation.class));
assertThat(error.unwrap(ConstraintViolation.class).getPropertyPath().toString(), is("password")); assertThat(error.unwrap(ConstraintViolation.class).getPropertyPath().toString()).isEqualTo("password");
} }
@Test // SPR-13406 @Test // SPR-13406
@ -134,19 +132,19 @@ public class SpringValidatorAdapterTests {
BeanPropertyBindingResult errors = new BeanPropertyBindingResult(testBean, "testBean"); BeanPropertyBindingResult errors = new BeanPropertyBindingResult(testBean, "testBean");
validatorAdapter.validate(testBean, errors); validatorAdapter.validate(testBean, errors);
assertThat(errors.getFieldErrorCount("email"), is(1)); assertThat(errors.getFieldErrorCount("email")).isEqualTo(1);
assertThat(errors.getFieldValue("email"), is("test@example.com")); assertThat(errors.getFieldValue("email")).isEqualTo("test@example.com");
assertThat(errors.getFieldErrorCount("confirmEmail"), is(1)); assertThat(errors.getFieldErrorCount("confirmEmail")).isEqualTo(1);
FieldError error1 = errors.getFieldError("email"); FieldError error1 = errors.getFieldError("email");
FieldError error2 = errors.getFieldError("confirmEmail"); FieldError error2 = errors.getFieldError("confirmEmail");
assertNotNull(error1); assertNotNull(error1);
assertNotNull(error2); assertNotNull(error2);
assertThat(messageSource.getMessage(error1, Locale.ENGLISH), is("email must be same value as confirmEmail")); assertThat(messageSource.getMessage(error1, Locale.ENGLISH)).isEqualTo("email must be same value as confirmEmail");
assertThat(messageSource.getMessage(error2, Locale.ENGLISH), is("Email required")); assertThat(messageSource.getMessage(error2, Locale.ENGLISH)).isEqualTo("Email required");
assertTrue(error1.contains(ConstraintViolation.class)); assertTrue(error1.contains(ConstraintViolation.class));
assertThat(error1.unwrap(ConstraintViolation.class).getPropertyPath().toString(), is("email")); assertThat(error1.unwrap(ConstraintViolation.class).getPropertyPath().toString()).isEqualTo("email");
assertTrue(error2.contains(ConstraintViolation.class)); assertTrue(error2.contains(ConstraintViolation.class));
assertThat(error2.unwrap(ConstraintViolation.class).getPropertyPath().toString(), is("confirmEmail")); assertThat(error2.unwrap(ConstraintViolation.class).getPropertyPath().toString()).isEqualTo("confirmEmail");
} }
@Test // SPR-15123 @Test // SPR-15123
@ -160,19 +158,19 @@ public class SpringValidatorAdapterTests {
BeanPropertyBindingResult errors = new BeanPropertyBindingResult(testBean, "testBean"); BeanPropertyBindingResult errors = new BeanPropertyBindingResult(testBean, "testBean");
validatorAdapter.validate(testBean, errors); validatorAdapter.validate(testBean, errors);
assertThat(errors.getFieldErrorCount("email"), is(1)); assertThat(errors.getFieldErrorCount("email")).isEqualTo(1);
assertThat(errors.getFieldValue("email"), is("test@example.com")); assertThat(errors.getFieldValue("email")).isEqualTo("test@example.com");
assertThat(errors.getFieldErrorCount("confirmEmail"), is(1)); assertThat(errors.getFieldErrorCount("confirmEmail")).isEqualTo(1);
FieldError error1 = errors.getFieldError("email"); FieldError error1 = errors.getFieldError("email");
FieldError error2 = errors.getFieldError("confirmEmail"); FieldError error2 = errors.getFieldError("confirmEmail");
assertNotNull(error1); assertNotNull(error1);
assertNotNull(error2); assertNotNull(error2);
assertThat(messageSource.getMessage(error1, Locale.ENGLISH), is("email must be same value as confirmEmail")); assertThat(messageSource.getMessage(error1, Locale.ENGLISH)).isEqualTo("email must be same value as confirmEmail");
assertThat(messageSource.getMessage(error2, Locale.ENGLISH), is("Email required")); assertThat(messageSource.getMessage(error2, Locale.ENGLISH)).isEqualTo("Email required");
assertTrue(error1.contains(ConstraintViolation.class)); assertTrue(error1.contains(ConstraintViolation.class));
assertThat(error1.unwrap(ConstraintViolation.class).getPropertyPath().toString(), is("email")); assertThat(error1.unwrap(ConstraintViolation.class).getPropertyPath().toString()).isEqualTo("email");
assertTrue(error2.contains(ConstraintViolation.class)); assertTrue(error2.contains(ConstraintViolation.class));
assertThat(error2.unwrap(ConstraintViolation.class).getPropertyPath().toString(), is("confirmEmail")); assertThat(error2.unwrap(ConstraintViolation.class).getPropertyPath().toString()).isEqualTo("confirmEmail");
} }
@Test @Test
@ -184,13 +182,13 @@ public class SpringValidatorAdapterTests {
BeanPropertyBindingResult errors = new BeanPropertyBindingResult(testBean, "testBean"); BeanPropertyBindingResult errors = new BeanPropertyBindingResult(testBean, "testBean");
validatorAdapter.validate(testBean, errors); validatorAdapter.validate(testBean, errors);
assertThat(errors.getFieldErrorCount("email"), is(1)); assertThat(errors.getFieldErrorCount("email")).isEqualTo(1);
assertThat(errors.getFieldValue("email"), is("X")); assertThat(errors.getFieldValue("email")).isEqualTo("X");
FieldError error = errors.getFieldError("email"); FieldError error = errors.getFieldError("email");
assertNotNull(error); assertNotNull(error);
assertThat(messageSource.getMessage(error, Locale.ENGLISH), containsString("[\\w.'-]{1,}@[\\w.'-]{1,}")); assertThat(messageSource.getMessage(error, Locale.ENGLISH)).contains("[\\w.'-]{1,}@[\\w.'-]{1,}");
assertTrue(error.contains(ConstraintViolation.class)); assertTrue(error.contains(ConstraintViolation.class));
assertThat(error.unwrap(ConstraintViolation.class).getPropertyPath().toString(), is("email")); assertThat(error.unwrap(ConstraintViolation.class).getPropertyPath().toString()).isEqualTo("email");
} }
@Test // SPR-16177 @Test // SPR-16177

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