Migrate JUnit 4 assertions to AssertJ

Migrate all existing JUnit 4 `assert...` based assertions to AssertJ
and add a checkstyle rule to ensure they don't return.

See gh-23022
This commit is contained in:
Phillip Webb 2019-05-23 15:51:39 -07:00
parent 95a9d46a87
commit 9d74da006c
1636 changed files with 37861 additions and 40390 deletions

View File

@ -23,9 +23,8 @@ import org.junit.Test;
import org.springframework.aop.aspectj.AspectJAdviceParameterNameDiscoverer.AmbiguousBindingException; import org.springframework.aop.aspectj.AspectJAdviceParameterNameDiscoverer.AmbiguousBindingException;
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.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
/** /**
* Unit tests for the {@link AspectJAdviceParameterNameDiscoverer} class. * Unit tests for the {@link AspectJAdviceParameterNameDiscoverer} class.
@ -236,8 +235,7 @@ public class AspectJAdviceParameterNameDiscovererTests {
protected void assertParameterNames( protected void assertParameterNames(
Method method, String pointcut, String returning, String throwing, String[] parameterNames) { Method method, String pointcut, String returning, String throwing, String[] parameterNames) {
assertEquals("bad test specification, must have same number of parameter names as method arguments", assertThat(parameterNames.length).as("bad test specification, must have same number of parameter names as method arguments").isEqualTo(method.getParameterCount());
method.getParameterCount(), parameterNames.length);
AspectJAdviceParameterNameDiscoverer discoverer = new AspectJAdviceParameterNameDiscoverer(pointcut); AspectJAdviceParameterNameDiscoverer discoverer = new AspectJAdviceParameterNameDiscoverer(pointcut);
discoverer.setRaiseExceptions(true); discoverer.setRaiseExceptions(true);
@ -248,16 +246,14 @@ public class AspectJAdviceParameterNameDiscovererTests {
String formattedExpectedNames = format(parameterNames); String formattedExpectedNames = format(parameterNames);
String formattedActualNames = format(discoveredNames); String formattedActualNames = format(discoveredNames);
assertEquals("Expecting " + parameterNames.length + " parameter names in return set '" + assertThat(discoveredNames.length).as("Expecting " + parameterNames.length + " parameter names in return set '" +
formattedExpectedNames + "', but found " + discoveredNames.length + formattedExpectedNames + "', but found " + discoveredNames.length +
" '" + formattedActualNames + "'", " '" + formattedActualNames + "'").isEqualTo(parameterNames.length);
parameterNames.length, discoveredNames.length);
for (int i = 0; i < discoveredNames.length; i++) { for (int i = 0; i < discoveredNames.length; i++) {
assertNotNull("Parameter names must never be null", discoveredNames[i]); assertThat(discoveredNames[i]).as("Parameter names must never be null").isNotNull();
assertEquals("Expecting parameter " + i + " to be named '" + assertThat(discoveredNames[i]).as("Expecting parameter " + i + " to be named '" +
parameterNames[i] + "' but was '" + discoveredNames[i] + "'", parameterNames[i] + "' but was '" + discoveredNames[i] + "'").isEqualTo(parameterNames[i]);
parameterNames[i], discoveredNames[i]);
} }
} }

View File

@ -40,9 +40,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.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
/** /**
* @author Rob Harrop * @author Rob Harrop
@ -81,9 +78,9 @@ public class AspectJExpressionPointcutTests {
// not currently testable in a reliable fashion // not currently testable in a reliable fashion
//assertDoesNotMatchStringClass(classFilter); //assertDoesNotMatchStringClass(classFilter);
assertFalse("Should not be a runtime match", methodMatcher.isRuntime()); assertThat(methodMatcher.isRuntime()).as("Should not be a runtime match").isFalse();
assertMatchesGetAge(methodMatcher); assertMatchesGetAge(methodMatcher);
assertFalse("Expression should match setAge() method", methodMatcher.matches(setAge, TestBean.class)); assertThat(methodMatcher.matches(setAge, TestBean.class)).as("Expression should match setAge() method").isFalse();
} }
@Test @Test
@ -99,9 +96,9 @@ public class AspectJExpressionPointcutTests {
// not currently testable in a reliable fashion // not currently testable in a reliable fashion
//assertDoesNotMatchStringClass(classFilter); //assertDoesNotMatchStringClass(classFilter);
assertFalse("Should not be a runtime match", methodMatcher.isRuntime()); assertThat(methodMatcher.isRuntime()).as("Should not be a runtime match").isFalse();
assertMatchesGetAge(methodMatcher); assertMatchesGetAge(methodMatcher);
assertTrue("Expression should match setAge(int) method", methodMatcher.matches(setAge, TestBean.class)); assertThat(methodMatcher.matches(setAge, TestBean.class)).as("Expression should match setAge(int) method").isTrue();
} }
@ -128,10 +125,10 @@ public class AspectJExpressionPointcutTests {
AspectJExpressionPointcut iOtherPc = new AspectJExpressionPointcut(); AspectJExpressionPointcut iOtherPc = new AspectJExpressionPointcut();
iOtherPc.setExpression(matchesIOther); iOtherPc.setExpression(matchesIOther);
assertTrue(testBeanPc.matches(TestBean.class)); assertThat(testBeanPc.matches(TestBean.class)).isTrue();
assertTrue(testBeanPc.matches(getAge, TestBean.class)); assertThat(testBeanPc.matches(getAge, TestBean.class)).isTrue();
assertTrue(iOtherPc.matches(OtherIOther.class.getMethod("absquatulate"), OtherIOther.class)); assertThat(iOtherPc.matches(OtherIOther.class.getMethod("absquatulate"), OtherIOther.class)).isTrue();
assertFalse(testBeanPc.matches(OtherIOther.class.getMethod("absquatulate"), OtherIOther.class)); assertThat(testBeanPc.matches(OtherIOther.class.getMethod("absquatulate"), OtherIOther.class)).isFalse();
} }
@Test @Test
@ -154,13 +151,13 @@ public class AspectJExpressionPointcutTests {
AspectJExpressionPointcut withinBeansPc = new AspectJExpressionPointcut(); AspectJExpressionPointcut withinBeansPc = new AspectJExpressionPointcut();
withinBeansPc.setExpression(withinBeansPackage); withinBeansPc.setExpression(withinBeansPackage);
assertTrue(withinBeansPc.matches(TestBean.class)); assertThat(withinBeansPc.matches(TestBean.class)).isTrue();
assertTrue(withinBeansPc.matches(getAge, TestBean.class)); assertThat(withinBeansPc.matches(getAge, TestBean.class)).isTrue();
assertEquals(matchSubpackages, withinBeansPc.matches(DeepBean.class)); assertThat(withinBeansPc.matches(DeepBean.class)).isEqualTo(matchSubpackages);
assertEquals(matchSubpackages, withinBeansPc.matches( assertThat(withinBeansPc.matches(
DeepBean.class.getMethod("aMethod", String.class), DeepBean.class)); DeepBean.class.getMethod("aMethod", String.class), DeepBean.class)).isEqualTo(matchSubpackages);
assertFalse(withinBeansPc.matches(String.class)); assertThat(withinBeansPc.matches(String.class)).isFalse();
assertFalse(withinBeansPc.matches(OtherIOther.class.getMethod("absquatulate"), OtherIOther.class)); assertThat(withinBeansPc.matches(OtherIOther.class.getMethod("absquatulate"), OtherIOther.class)).isFalse();
} }
@Test @Test
@ -201,12 +198,10 @@ public class AspectJExpressionPointcutTests {
// not currently testable in a reliable fashion // not currently testable in a reliable fashion
//assertDoesNotMatchStringClass(classFilter); //assertDoesNotMatchStringClass(classFilter);
assertTrue("Should match with setSomeNumber with Double input", assertThat(methodMatcher.matches(setSomeNumber, TestBean.class, new Double(12))).as("Should match with setSomeNumber with Double input").isTrue();
methodMatcher.matches(setSomeNumber, TestBean.class, new Double(12))); assertThat(methodMatcher.matches(setSomeNumber, TestBean.class, new Integer(11))).as("Should not match setSomeNumber with Integer input").isFalse();
assertFalse("Should not match setSomeNumber with Integer input", assertThat(methodMatcher.matches(getAge, TestBean.class)).as("Should not match getAge").isFalse();
methodMatcher.matches(setSomeNumber, TestBean.class, new Integer(11))); assertThat(methodMatcher.isRuntime()).as("Should be a runtime match").isTrue();
assertFalse("Should not match getAge", methodMatcher.matches(getAge, TestBean.class));
assertTrue("Should be a runtime match", methodMatcher.isRuntime());
} }
@Test @Test
@ -215,11 +210,11 @@ public class AspectJExpressionPointcutTests {
CallCountingInterceptor interceptor = new CallCountingInterceptor(); CallCountingInterceptor interceptor = new CallCountingInterceptor();
TestBean testBean = getAdvisedProxy(expression, interceptor); TestBean testBean = getAdvisedProxy(expression, interceptor);
assertEquals("Calls should be 0", 0, interceptor.getCount()); assertThat(interceptor.getCount()).as("Calls should be 0").isEqualTo(0);
testBean.getAge(); testBean.getAge();
assertEquals("Calls should be 1", 1, interceptor.getCount()); assertThat(interceptor.getCount()).as("Calls should be 1").isEqualTo(1);
testBean.setAge(90); testBean.setAge(90);
assertEquals("Calls should still be 1", 1, interceptor.getCount()); assertThat(interceptor.getCount()).as("Calls should still be 1").isEqualTo(1);
} }
@Test @Test
@ -228,12 +223,12 @@ public class AspectJExpressionPointcutTests {
CallCountingInterceptor interceptor = new CallCountingInterceptor(); CallCountingInterceptor interceptor = new CallCountingInterceptor();
TestBean testBean = getAdvisedProxy(expression, interceptor); TestBean testBean = getAdvisedProxy(expression, interceptor);
assertEquals("Calls should be 0", 0, interceptor.getCount()); assertThat(interceptor.getCount()).as("Calls should be 0").isEqualTo(0);
testBean.setSomeNumber(new Double(30)); testBean.setSomeNumber(new Double(30));
assertEquals("Calls should be 1", 1, interceptor.getCount()); assertThat(interceptor.getCount()).as("Calls should be 1").isEqualTo(1);
testBean.setSomeNumber(new Integer(90)); testBean.setSomeNumber(new Integer(90));
assertEquals("Calls should be 1", 1, interceptor.getCount()); assertThat(interceptor.getCount()).as("Calls should be 1").isEqualTo(1);
} }
@Test @Test
@ -260,11 +255,11 @@ public class AspectJExpressionPointcutTests {
} }
private void assertMatchesGetAge(MethodMatcher methodMatcher) { private void assertMatchesGetAge(MethodMatcher methodMatcher) {
assertTrue("Expression should match getAge() method", methodMatcher.matches(getAge, TestBean.class)); assertThat(methodMatcher.matches(getAge, TestBean.class)).as("Expression should match getAge() method").isTrue();
} }
private void assertMatchesTestBeanClass(ClassFilter classFilter) { private void assertMatchesTestBeanClass(ClassFilter classFilter) {
assertTrue("Expression should match TestBean class", classFilter.matches(TestBean.class)); assertThat(classFilter.matches(TestBean.class)).as("Expression should match TestBean class").isTrue();
} }
@Test @Test
@ -279,14 +274,14 @@ public class AspectJExpressionPointcutTests {
public void testAndSubstitution() { public void testAndSubstitution() {
Pointcut pc = getPointcut("execution(* *(..)) and args(String)"); Pointcut pc = getPointcut("execution(* *(..)) and args(String)");
PointcutExpression expr = ((AspectJExpressionPointcut) pc).getPointcutExpression(); PointcutExpression expr = ((AspectJExpressionPointcut) pc).getPointcutExpression();
assertEquals("execution(* *(..)) && args(String)",expr.getPointcutExpression()); assertThat(expr.getPointcutExpression()).isEqualTo("execution(* *(..)) && args(String)");
} }
@Test @Test
public void testMultipleAndSubstitutions() { public void testMultipleAndSubstitutions() {
Pointcut pc = getPointcut("execution(* *(..)) and args(String) and this(Object)"); Pointcut pc = getPointcut("execution(* *(..)) and args(String) and this(Object)");
PointcutExpression expr = ((AspectJExpressionPointcut) pc).getPointcutExpression(); PointcutExpression expr = ((AspectJExpressionPointcut) pc).getPointcutExpression();
assertEquals("execution(* *(..)) && args(String) && this(Object)",expr.getPointcutExpression()); assertThat(expr.getPointcutExpression()).isEqualTo("execution(* *(..)) && args(String) && this(Object)");
} }
private Pointcut getPointcut(String expression) { private Pointcut getPointcut(String expression) {

View File

@ -20,8 +20,7 @@ import org.junit.Test;
import org.springframework.tests.sample.beans.TestBean; import org.springframework.tests.sample.beans.TestBean;
import static org.junit.Assert.assertFalse; import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertTrue;
/** /**
* Tests for matching of bean() pointcut designator. * Tests for matching of bean() pointcut designator.
@ -80,13 +79,11 @@ public class BeanNamePointcutMatchingTests {
private void assertMatch(String beanName, String pcExpression) { private void assertMatch(String beanName, String pcExpression) {
assertTrue("Unexpected mismatch for bean \"" + beanName + "\" for pcExpression \"" + pcExpression + "\"", assertThat(matches(beanName, pcExpression)).as("Unexpected mismatch for bean \"" + beanName + "\" for pcExpression \"" + pcExpression + "\"").isTrue();
matches(beanName, pcExpression));
} }
private void assertMisMatch(String beanName, String pcExpression) { private void assertMisMatch(String beanName, String pcExpression) {
assertFalse("Unexpected match for bean \"" + beanName + "\" for pcExpression \"" + pcExpression + "\"", assertThat(matches(beanName, pcExpression)).as("Unexpected match for bean \"" + beanName + "\" for pcExpression \"" + pcExpression + "\"").isFalse();
matches(beanName, pcExpression));
} }
private static boolean matches(final String beanName, String pcExpression) { private static boolean matches(final String beanName, String pcExpression) {

View File

@ -37,13 +37,9 @@ import org.springframework.lang.Nullable;
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.assertThatIllegalStateException; import static org.assertj.core.api.Assertions.assertThatIllegalStateException;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotSame;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
/** /**
* @author Rod Johnson * @author Rod Johnson
@ -80,21 +76,21 @@ public class MethodInvocationProceedingJoinPointTests {
@Override @Override
public void before(Method method, Object[] args, @Nullable Object target) throws Throwable { public void before(Method method, Object[] args, @Nullable Object target) throws Throwable {
JoinPoint jp = AbstractAspectJAdvice.currentJoinPoint(); JoinPoint jp = AbstractAspectJAdvice.currentJoinPoint();
assertTrue("Method named in toString", jp.toString().contains(method.getName())); assertThat(jp.toString().contains(method.getName())).as("Method named in toString").isTrue();
// Ensure that these don't cause problems // Ensure that these don't cause problems
jp.toShortString(); jp.toShortString();
jp.toLongString(); jp.toLongString();
assertSame(target, AbstractAspectJAdvice.currentJoinPoint().getTarget()); assertThat(AbstractAspectJAdvice.currentJoinPoint().getTarget()).isSameAs(target);
assertFalse(AopUtils.isAopProxy(AbstractAspectJAdvice.currentJoinPoint().getTarget())); assertThat(AopUtils.isAopProxy(AbstractAspectJAdvice.currentJoinPoint().getTarget())).isFalse();
ITestBean thisProxy = (ITestBean) AbstractAspectJAdvice.currentJoinPoint().getThis(); ITestBean thisProxy = (ITestBean) AbstractAspectJAdvice.currentJoinPoint().getThis();
assertTrue(AopUtils.isAopProxy(AbstractAspectJAdvice.currentJoinPoint().getThis())); assertThat(AopUtils.isAopProxy(AbstractAspectJAdvice.currentJoinPoint().getThis())).isTrue();
assertNotSame(target, thisProxy); assertThat(thisProxy).isNotSameAs(target);
// Check getting again doesn't cause a problem // Check getting again doesn't cause a problem
assertSame(thisProxy, AbstractAspectJAdvice.currentJoinPoint().getThis()); assertThat(AbstractAspectJAdvice.currentJoinPoint().getThis()).isSameAs(thisProxy);
// Try reentrant call--will go through this advice. // Try reentrant call--will go through this advice.
// Be sure to increment depth to avoid infinite recursion // Be sure to increment depth to avoid infinite recursion
@ -103,29 +99,29 @@ public class MethodInvocationProceedingJoinPointTests {
thisProxy.toString(); thisProxy.toString();
// Change age, so this will be returned by invocation // Change age, so this will be returned by invocation
thisProxy.setAge(newAge); thisProxy.setAge(newAge);
assertEquals(newAge, thisProxy.getAge()); assertThat(thisProxy.getAge()).isEqualTo(newAge);
} }
assertSame(AopContext.currentProxy(), thisProxy); assertThat(thisProxy).isSameAs(AopContext.currentProxy());
assertSame(target, raw); assertThat(raw).isSameAs(target);
assertSame(method.getName(), AbstractAspectJAdvice.currentJoinPoint().getSignature().getName()); assertThat(AbstractAspectJAdvice.currentJoinPoint().getSignature().getName()).isSameAs(method.getName());
assertEquals(method.getModifiers(), AbstractAspectJAdvice.currentJoinPoint().getSignature().getModifiers()); assertThat(AbstractAspectJAdvice.currentJoinPoint().getSignature().getModifiers()).isEqualTo(method.getModifiers());
MethodSignature msig = (MethodSignature) AbstractAspectJAdvice.currentJoinPoint().getSignature(); MethodSignature msig = (MethodSignature) AbstractAspectJAdvice.currentJoinPoint().getSignature();
assertSame("Return same MethodSignature repeatedly", msig, AbstractAspectJAdvice.currentJoinPoint().getSignature()); assertThat(AbstractAspectJAdvice.currentJoinPoint().getSignature()).as("Return same MethodSignature repeatedly").isSameAs(msig);
assertSame("Return same JoinPoint repeatedly", AbstractAspectJAdvice.currentJoinPoint(), AbstractAspectJAdvice.currentJoinPoint()); assertThat(AbstractAspectJAdvice.currentJoinPoint()).as("Return same JoinPoint repeatedly").isSameAs(AbstractAspectJAdvice.currentJoinPoint());
assertEquals(method.getDeclaringClass(), msig.getDeclaringType()); assertThat(msig.getDeclaringType()).isEqualTo(method.getDeclaringClass());
assertTrue(Arrays.equals(method.getParameterTypes(), msig.getParameterTypes())); assertThat(Arrays.equals(method.getParameterTypes(), msig.getParameterTypes())).isTrue();
assertEquals(method.getReturnType(), msig.getReturnType()); assertThat(msig.getReturnType()).isEqualTo(method.getReturnType());
assertTrue(Arrays.equals(method.getExceptionTypes(), msig.getExceptionTypes())); assertThat(Arrays.equals(method.getExceptionTypes(), msig.getExceptionTypes())).isTrue();
msig.toLongString(); msig.toLongString();
msig.toShortString(); msig.toShortString();
} }
}); });
ITestBean itb = (ITestBean) pf.getProxy(); ITestBean itb = (ITestBean) pf.getProxy();
// Any call will do // Any call will do
assertEquals("Advice reentrantly set age", newAge, itb.getAge()); assertThat(itb.getAge()).as("Advice reentrantly set age").isEqualTo(newAge);
} }
@Test @Test
@ -137,8 +133,8 @@ public class MethodInvocationProceedingJoinPointTests {
@Override @Override
public void before(Method method, Object[] args, @Nullable Object target) throws Throwable { public void before(Method method, Object[] args, @Nullable Object target) throws Throwable {
SourceLocation sloc = AbstractAspectJAdvice.currentJoinPoint().getSourceLocation(); SourceLocation sloc = AbstractAspectJAdvice.currentJoinPoint().getSourceLocation();
assertEquals("Same source location must be returned on subsequent requests", sloc, AbstractAspectJAdvice.currentJoinPoint().getSourceLocation()); assertThat(AbstractAspectJAdvice.currentJoinPoint().getSourceLocation()).as("Same source location must be returned on subsequent requests").isEqualTo(sloc);
assertEquals(TestBean.class, sloc.getWithinType()); assertThat(sloc.getWithinType()).isEqualTo(TestBean.class);
assertThatExceptionOfType(UnsupportedOperationException.class).isThrownBy(sloc::getLine); assertThatExceptionOfType(UnsupportedOperationException.class).isThrownBy(sloc::getLine);
assertThatExceptionOfType(UnsupportedOperationException.class).isThrownBy(sloc::getFileName); assertThatExceptionOfType(UnsupportedOperationException.class).isThrownBy(sloc::getFileName);
} }
@ -157,10 +153,10 @@ public class MethodInvocationProceedingJoinPointTests {
@Override @Override
public void before(Method method, Object[] args, @Nullable Object target) throws Throwable { public void before(Method method, Object[] args, @Nullable Object target) throws Throwable {
StaticPart staticPart = AbstractAspectJAdvice.currentJoinPoint().getStaticPart(); StaticPart staticPart = AbstractAspectJAdvice.currentJoinPoint().getStaticPart();
assertEquals("Same static part must be returned on subsequent requests", staticPart, AbstractAspectJAdvice.currentJoinPoint().getStaticPart()); assertThat(AbstractAspectJAdvice.currentJoinPoint().getStaticPart()).as("Same static part must be returned on subsequent requests").isEqualTo(staticPart);
assertEquals(ProceedingJoinPoint.METHOD_EXECUTION, staticPart.getKind()); assertThat(staticPart.getKind()).isEqualTo(ProceedingJoinPoint.METHOD_EXECUTION);
assertSame(AbstractAspectJAdvice.currentJoinPoint().getSignature(), staticPart.getSignature()); assertThat(staticPart.getSignature()).isSameAs(AbstractAspectJAdvice.currentJoinPoint().getSignature());
assertEquals(AbstractAspectJAdvice.currentJoinPoint().getSourceLocation(), staticPart.getSourceLocation()); assertThat(staticPart.getSourceLocation()).isEqualTo(AbstractAspectJAdvice.currentJoinPoint().getSourceLocation());
} }
}); });
ITestBean itb = (ITestBean) pf.getProxy(); ITestBean itb = (ITestBean) pf.getProxy();
@ -181,13 +177,13 @@ public class MethodInvocationProceedingJoinPointTests {
JoinPoint.StaticPart aspectJVersionJp = Factory.makeEncSJP(method); JoinPoint.StaticPart aspectJVersionJp = Factory.makeEncSJP(method);
JoinPoint jp = AbstractAspectJAdvice.currentJoinPoint(); JoinPoint jp = AbstractAspectJAdvice.currentJoinPoint();
assertEquals(aspectJVersionJp.getSignature().toLongString(), jp.getSignature().toLongString()); assertThat(jp.getSignature().toLongString()).isEqualTo(aspectJVersionJp.getSignature().toLongString());
assertEquals(aspectJVersionJp.getSignature().toShortString(), jp.getSignature().toShortString()); assertThat(jp.getSignature().toShortString()).isEqualTo(aspectJVersionJp.getSignature().toShortString());
assertEquals(aspectJVersionJp.getSignature().toString(), jp.getSignature().toString()); assertThat(jp.getSignature().toString()).isEqualTo(aspectJVersionJp.getSignature().toString());
assertEquals(aspectJVersionJp.toLongString(), jp.toLongString()); assertThat(jp.toLongString()).isEqualTo(aspectJVersionJp.toLongString());
assertEquals(aspectJVersionJp.toShortString(), jp.toShortString()); assertThat(jp.toShortString()).isEqualTo(aspectJVersionJp.toShortString());
assertEquals(aspectJVersionJp.toString(), jp.toString()); assertThat(jp.toString()).isEqualTo(aspectJVersionJp.toString());
} }
}); });
ITestBean itb = (ITestBean) pf.getProxy(); ITestBean itb = (ITestBean) pf.getProxy();

View File

@ -29,8 +29,7 @@ import test.annotation.transaction.Tx;
import org.springframework.aop.framework.ProxyFactory; import org.springframework.aop.framework.ProxyFactory;
import org.springframework.tests.sample.beans.TestBean; import org.springframework.tests.sample.beans.TestBean;
import static org.junit.Assert.assertFalse; import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertTrue;
/** /**
* Java 5 specific {@link AspectJExpressionPointcutTests}. * Java 5 specific {@link AspectJExpressionPointcutTests}.
@ -66,12 +65,12 @@ public class TigerAspectJExpressionPointcutTests {
//assertFalse(ajexp.matches(TestBean.class)); //assertFalse(ajexp.matches(TestBean.class));
Method takesGenericList = methodsOnHasGeneric.get("setFriends"); Method takesGenericList = methodsOnHasGeneric.get("setFriends");
assertTrue(ajexp.matches(takesGenericList, HasGeneric.class)); assertThat(ajexp.matches(takesGenericList, HasGeneric.class)).isTrue();
assertTrue(ajexp.matches(methodsOnHasGeneric.get("setEnemies"), HasGeneric.class)); assertThat(ajexp.matches(methodsOnHasGeneric.get("setEnemies"), HasGeneric.class)).isTrue();
assertFalse(ajexp.matches(methodsOnHasGeneric.get("setPartners"), HasGeneric.class)); assertThat(ajexp.matches(methodsOnHasGeneric.get("setPartners"), HasGeneric.class)).isFalse();
assertFalse(ajexp.matches(methodsOnHasGeneric.get("setPhoneNumbers"), HasGeneric.class)); assertThat(ajexp.matches(methodsOnHasGeneric.get("setPhoneNumbers"), HasGeneric.class)).isFalse();
assertFalse(ajexp.matches(getAge, TestBean.class)); assertThat(ajexp.matches(getAge, TestBean.class)).isFalse();
} }
@Test @Test
@ -88,16 +87,16 @@ public class TigerAspectJExpressionPointcutTests {
AspectJExpressionPointcut jdbcVarArgs = new AspectJExpressionPointcut(); AspectJExpressionPointcut jdbcVarArgs = new AspectJExpressionPointcut();
jdbcVarArgs.setExpression(expression); jdbcVarArgs.setExpression(expression);
assertTrue(jdbcVarArgs.matches( assertThat(jdbcVarArgs.matches(
MyTemplate.class.getMethod("queryForInt", String.class, Object[].class), MyTemplate.class.getMethod("queryForInt", String.class, Object[].class),
MyTemplate.class)); MyTemplate.class)).isTrue();
Method takesGenericList = methodsOnHasGeneric.get("setFriends"); Method takesGenericList = methodsOnHasGeneric.get("setFriends");
assertFalse(jdbcVarArgs.matches(takesGenericList, HasGeneric.class)); assertThat(jdbcVarArgs.matches(takesGenericList, HasGeneric.class)).isFalse();
assertFalse(jdbcVarArgs.matches(methodsOnHasGeneric.get("setEnemies"), HasGeneric.class)); assertThat(jdbcVarArgs.matches(methodsOnHasGeneric.get("setEnemies"), HasGeneric.class)).isFalse();
assertFalse(jdbcVarArgs.matches(methodsOnHasGeneric.get("setPartners"), HasGeneric.class)); assertThat(jdbcVarArgs.matches(methodsOnHasGeneric.get("setPartners"), HasGeneric.class)).isFalse();
assertFalse(jdbcVarArgs.matches(methodsOnHasGeneric.get("setPhoneNumbers"), HasGeneric.class)); assertThat(jdbcVarArgs.matches(methodsOnHasGeneric.get("setPhoneNumbers"), HasGeneric.class)).isFalse();
assertFalse(jdbcVarArgs.matches(getAge, TestBean.class)); assertThat(jdbcVarArgs.matches(getAge, TestBean.class)).isFalse();
} }
@Test @Test
@ -116,12 +115,12 @@ public class TigerAspectJExpressionPointcutTests {
public void testMatchAnnotationOnClassWithSubpackageWildcard() throws Exception { public void testMatchAnnotationOnClassWithSubpackageWildcard() throws Exception {
String expression = "within(@(test.annotation..*) *)"; String expression = "within(@(test.annotation..*) *)";
AspectJExpressionPointcut springAnnotatedPc = testMatchAnnotationOnClass(expression); AspectJExpressionPointcut springAnnotatedPc = testMatchAnnotationOnClass(expression);
assertFalse(springAnnotatedPc.matches(TestBean.class.getMethod("setName", String.class), TestBean.class)); assertThat(springAnnotatedPc.matches(TestBean.class.getMethod("setName", String.class), TestBean.class)).isFalse();
assertTrue(springAnnotatedPc.matches(SpringAnnotated.class.getMethod("foo"), SpringAnnotated.class)); assertThat(springAnnotatedPc.matches(SpringAnnotated.class.getMethod("foo"), SpringAnnotated.class)).isTrue();
expression = "within(@(test.annotation.transaction..*) *)"; expression = "within(@(test.annotation.transaction..*) *)";
AspectJExpressionPointcut springTxAnnotatedPc = testMatchAnnotationOnClass(expression); AspectJExpressionPointcut springTxAnnotatedPc = testMatchAnnotationOnClass(expression);
assertFalse(springTxAnnotatedPc.matches(SpringAnnotated.class.getMethod("foo"), SpringAnnotated.class)); assertThat(springTxAnnotatedPc.matches(SpringAnnotated.class.getMethod("foo"), SpringAnnotated.class)).isFalse();
} }
@Test @Test
@ -134,11 +133,11 @@ public class TigerAspectJExpressionPointcutTests {
AspectJExpressionPointcut ajexp = new AspectJExpressionPointcut(); AspectJExpressionPointcut ajexp = new AspectJExpressionPointcut();
ajexp.setExpression(expression); ajexp.setExpression(expression);
assertFalse(ajexp.matches(getAge, TestBean.class)); assertThat(ajexp.matches(getAge, TestBean.class)).isFalse();
assertTrue(ajexp.matches(HasTransactionalAnnotation.class.getMethod("foo"), HasTransactionalAnnotation.class)); assertThat(ajexp.matches(HasTransactionalAnnotation.class.getMethod("foo"), HasTransactionalAnnotation.class)).isTrue();
assertTrue(ajexp.matches(HasTransactionalAnnotation.class.getMethod("bar", String.class), HasTransactionalAnnotation.class)); assertThat(ajexp.matches(HasTransactionalAnnotation.class.getMethod("bar", String.class), HasTransactionalAnnotation.class)).isTrue();
assertTrue(ajexp.matches(BeanB.class.getMethod("setName", String.class), BeanB.class)); assertThat(ajexp.matches(BeanB.class.getMethod("setName", String.class), BeanB.class)).isTrue();
assertFalse(ajexp.matches(BeanA.class.getMethod("setName", String.class), BeanA.class)); assertThat(ajexp.matches(BeanA.class.getMethod("setName", String.class), BeanA.class)).isFalse();
return ajexp; return ajexp;
} }
@ -148,12 +147,12 @@ public class TigerAspectJExpressionPointcutTests {
AspectJExpressionPointcut ajexp = new AspectJExpressionPointcut(); AspectJExpressionPointcut ajexp = new AspectJExpressionPointcut();
ajexp.setExpression(expression); ajexp.setExpression(expression);
assertFalse(ajexp.matches(getAge, TestBean.class)); assertThat(ajexp.matches(getAge, TestBean.class)).isFalse();
assertFalse(ajexp.matches(HasTransactionalAnnotation.class.getMethod("foo"), HasTransactionalAnnotation.class)); assertThat(ajexp.matches(HasTransactionalAnnotation.class.getMethod("foo"), HasTransactionalAnnotation.class)).isFalse();
assertFalse(ajexp.matches(HasTransactionalAnnotation.class.getMethod("bar", String.class), HasTransactionalAnnotation.class)); assertThat(ajexp.matches(HasTransactionalAnnotation.class.getMethod("bar", String.class), HasTransactionalAnnotation.class)).isFalse();
assertFalse(ajexp.matches(BeanA.class.getMethod("setName", String.class), BeanA.class)); assertThat(ajexp.matches(BeanA.class.getMethod("setName", String.class), BeanA.class)).isFalse();
assertTrue(ajexp.matches(BeanA.class.getMethod("getAge"), BeanA.class)); assertThat(ajexp.matches(BeanA.class.getMethod("getAge"), BeanA.class)).isTrue();
assertFalse(ajexp.matches(BeanA.class.getMethod("setName", String.class), BeanA.class)); assertThat(ajexp.matches(BeanA.class.getMethod("setName", String.class), BeanA.class)).isFalse();
} }
@Test @Test
@ -165,7 +164,7 @@ public class TigerAspectJExpressionPointcutTests {
ProxyFactory factory = new ProxyFactory(new BeanA()); ProxyFactory factory = new ProxyFactory(new BeanA());
factory.setProxyTargetClass(true); factory.setProxyTargetClass(true);
BeanA proxy = (BeanA) factory.getProxy(); BeanA proxy = (BeanA) factory.getProxy();
assertTrue(ajexp.matches(BeanA.class.getMethod("getAge"), proxy.getClass())); assertThat(ajexp.matches(BeanA.class.getMethod("getAge"), proxy.getClass())).isTrue();
} }
@Test @Test
@ -177,7 +176,7 @@ public class TigerAspectJExpressionPointcutTests {
ProxyFactory factory = new ProxyFactory(new BeanA()); ProxyFactory factory = new ProxyFactory(new BeanA());
factory.setProxyTargetClass(false); factory.setProxyTargetClass(false);
IBeanA proxy = (IBeanA) factory.getProxy(); IBeanA proxy = (IBeanA) factory.getProxy();
assertTrue(ajexp.matches(IBeanA.class.getMethod("getAge"), proxy.getClass())); assertThat(ajexp.matches(IBeanA.class.getMethod("getAge"), proxy.getClass())).isTrue();
} }
@Test @Test
@ -186,14 +185,14 @@ public class TigerAspectJExpressionPointcutTests {
AspectJExpressionPointcut anySpringMethodAnnotation = new AspectJExpressionPointcut(); AspectJExpressionPointcut anySpringMethodAnnotation = new AspectJExpressionPointcut();
anySpringMethodAnnotation.setExpression(expression); anySpringMethodAnnotation.setExpression(expression);
assertFalse(anySpringMethodAnnotation.matches(getAge, TestBean.class)); assertThat(anySpringMethodAnnotation.matches(getAge, TestBean.class)).isFalse();
assertFalse(anySpringMethodAnnotation.matches( assertThat(anySpringMethodAnnotation.matches(
HasTransactionalAnnotation.class.getMethod("foo"), HasTransactionalAnnotation.class)); HasTransactionalAnnotation.class.getMethod("foo"), HasTransactionalAnnotation.class)).isFalse();
assertFalse(anySpringMethodAnnotation.matches( assertThat(anySpringMethodAnnotation.matches(
HasTransactionalAnnotation.class.getMethod("bar", String.class), HasTransactionalAnnotation.class)); HasTransactionalAnnotation.class.getMethod("bar", String.class), HasTransactionalAnnotation.class)).isFalse();
assertFalse(anySpringMethodAnnotation.matches(BeanA.class.getMethod("setName", String.class), BeanA.class)); assertThat(anySpringMethodAnnotation.matches(BeanA.class.getMethod("setName", String.class), BeanA.class)).isFalse();
assertTrue(anySpringMethodAnnotation.matches(BeanA.class.getMethod("getAge"), BeanA.class)); assertThat(anySpringMethodAnnotation.matches(BeanA.class.getMethod("getAge"), BeanA.class)).isTrue();
assertFalse(anySpringMethodAnnotation.matches(BeanA.class.getMethod("setName", String.class), BeanA.class)); assertThat(anySpringMethodAnnotation.matches(BeanA.class.getMethod("setName", String.class), BeanA.class)).isFalse();
} }
@Test @Test
@ -202,28 +201,27 @@ public class TigerAspectJExpressionPointcutTests {
AspectJExpressionPointcut takesSpringAnnotatedArgument2 = new AspectJExpressionPointcut(); AspectJExpressionPointcut takesSpringAnnotatedArgument2 = new AspectJExpressionPointcut();
takesSpringAnnotatedArgument2.setExpression(expression); takesSpringAnnotatedArgument2.setExpression(expression);
assertFalse(takesSpringAnnotatedArgument2.matches(getAge, TestBean.class)); assertThat(takesSpringAnnotatedArgument2.matches(getAge, TestBean.class)).isFalse();
assertFalse(takesSpringAnnotatedArgument2.matches( assertThat(takesSpringAnnotatedArgument2.matches(
HasTransactionalAnnotation.class.getMethod("foo"), HasTransactionalAnnotation.class)); HasTransactionalAnnotation.class.getMethod("foo"), HasTransactionalAnnotation.class)).isFalse();
assertFalse(takesSpringAnnotatedArgument2.matches( assertThat(takesSpringAnnotatedArgument2.matches(
HasTransactionalAnnotation.class.getMethod("bar", String.class), HasTransactionalAnnotation.class)); HasTransactionalAnnotation.class.getMethod("bar", String.class), HasTransactionalAnnotation.class)).isFalse();
assertFalse(takesSpringAnnotatedArgument2.matches(BeanA.class.getMethod("setName", String.class), BeanA.class)); assertThat(takesSpringAnnotatedArgument2.matches(BeanA.class.getMethod("setName", String.class), BeanA.class)).isFalse();
assertFalse(takesSpringAnnotatedArgument2.matches(BeanA.class.getMethod("getAge"), BeanA.class)); assertThat(takesSpringAnnotatedArgument2.matches(BeanA.class.getMethod("getAge"), BeanA.class)).isFalse();
assertFalse(takesSpringAnnotatedArgument2.matches(BeanA.class.getMethod("setName", String.class), BeanA.class)); assertThat(takesSpringAnnotatedArgument2.matches(BeanA.class.getMethod("setName", String.class), BeanA.class)).isFalse();
assertTrue(takesSpringAnnotatedArgument2.matches( assertThat(takesSpringAnnotatedArgument2.matches(
ProcessesSpringAnnotatedParameters.class.getMethod("takesAnnotatedParameters", TestBean.class, SpringAnnotated.class), ProcessesSpringAnnotatedParameters.class.getMethod("takesAnnotatedParameters", TestBean.class, SpringAnnotated.class),
ProcessesSpringAnnotatedParameters.class)); ProcessesSpringAnnotatedParameters.class)).isTrue();
// True because it maybeMatches with potential argument subtypes // True because it maybeMatches with potential argument subtypes
assertTrue(takesSpringAnnotatedArgument2.matches( assertThat(takesSpringAnnotatedArgument2.matches(
ProcessesSpringAnnotatedParameters.class.getMethod("takesNoAnnotatedParameters", TestBean.class, BeanA.class), ProcessesSpringAnnotatedParameters.class.getMethod("takesNoAnnotatedParameters", TestBean.class, BeanA.class),
ProcessesSpringAnnotatedParameters.class)); ProcessesSpringAnnotatedParameters.class)).isTrue();
assertFalse(takesSpringAnnotatedArgument2.matches( assertThat(takesSpringAnnotatedArgument2.matches(
ProcessesSpringAnnotatedParameters.class.getMethod("takesNoAnnotatedParameters", TestBean.class, BeanA.class), ProcessesSpringAnnotatedParameters.class.getMethod("takesNoAnnotatedParameters", TestBean.class, BeanA.class),
ProcessesSpringAnnotatedParameters.class, new TestBean(), new BeanA()) ProcessesSpringAnnotatedParameters.class, new TestBean(), new BeanA())).isFalse();
);
} }
@Test @Test
@ -232,21 +230,21 @@ public class TigerAspectJExpressionPointcutTests {
AspectJExpressionPointcut takesSpringAnnotatedArgument2 = new AspectJExpressionPointcut(); AspectJExpressionPointcut takesSpringAnnotatedArgument2 = new AspectJExpressionPointcut();
takesSpringAnnotatedArgument2.setExpression(expression); takesSpringAnnotatedArgument2.setExpression(expression);
assertFalse(takesSpringAnnotatedArgument2.matches(getAge, TestBean.class)); assertThat(takesSpringAnnotatedArgument2.matches(getAge, TestBean.class)).isFalse();
assertFalse(takesSpringAnnotatedArgument2.matches( assertThat(takesSpringAnnotatedArgument2.matches(
HasTransactionalAnnotation.class.getMethod("foo"), HasTransactionalAnnotation.class)); HasTransactionalAnnotation.class.getMethod("foo"), HasTransactionalAnnotation.class)).isFalse();
assertFalse(takesSpringAnnotatedArgument2.matches( assertThat(takesSpringAnnotatedArgument2.matches(
HasTransactionalAnnotation.class.getMethod("bar", String.class), HasTransactionalAnnotation.class)); HasTransactionalAnnotation.class.getMethod("bar", String.class), HasTransactionalAnnotation.class)).isFalse();
assertFalse(takesSpringAnnotatedArgument2.matches(BeanA.class.getMethod("setName", String.class), BeanA.class)); assertThat(takesSpringAnnotatedArgument2.matches(BeanA.class.getMethod("setName", String.class), BeanA.class)).isFalse();
assertFalse(takesSpringAnnotatedArgument2.matches(BeanA.class.getMethod("getAge"), BeanA.class)); assertThat(takesSpringAnnotatedArgument2.matches(BeanA.class.getMethod("getAge"), BeanA.class)).isFalse();
assertFalse(takesSpringAnnotatedArgument2.matches(BeanA.class.getMethod("setName", String.class), BeanA.class)); assertThat(takesSpringAnnotatedArgument2.matches(BeanA.class.getMethod("setName", String.class), BeanA.class)).isFalse();
assertTrue(takesSpringAnnotatedArgument2.matches( assertThat(takesSpringAnnotatedArgument2.matches(
ProcessesSpringAnnotatedParameters.class.getMethod("takesAnnotatedParameters", TestBean.class, SpringAnnotated.class), ProcessesSpringAnnotatedParameters.class.getMethod("takesAnnotatedParameters", TestBean.class, SpringAnnotated.class),
ProcessesSpringAnnotatedParameters.class)); ProcessesSpringAnnotatedParameters.class)).isTrue();
assertFalse(takesSpringAnnotatedArgument2.matches( assertThat(takesSpringAnnotatedArgument2.matches(
ProcessesSpringAnnotatedParameters.class.getMethod("takesNoAnnotatedParameters", TestBean.class, BeanA.class), ProcessesSpringAnnotatedParameters.class.getMethod("takesNoAnnotatedParameters", TestBean.class, BeanA.class),
ProcessesSpringAnnotatedParameters.class)); ProcessesSpringAnnotatedParameters.class)).isFalse();
} }
@ -301,6 +299,7 @@ public class TigerAspectJExpressionPointcutTests {
static class BeanA implements IBeanA { static class BeanA implements IBeanA {
@SuppressWarnings("unused")
private String name; private String name;
private int age; private int age;
@ -320,6 +319,7 @@ public class TigerAspectJExpressionPointcutTests {
@Tx @Tx
static class BeanB { static class BeanB {
@SuppressWarnings("unused")
private String name; private String name;
public void setName(String name) { public void setName(String name) {

View File

@ -34,8 +34,8 @@ import org.springframework.aop.support.DefaultPointcutAdvisor;
import org.springframework.core.OverridingClassLoader; import org.springframework.core.OverridingClassLoader;
import org.springframework.lang.Nullable; import org.springframework.lang.Nullable;
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.junit.Assert.assertEquals;
/** /**
* @author Dave Syer * @author Dave Syer
@ -111,10 +111,10 @@ public class TrickyAspectJPointcutExpressionTests {
factory.addAdvisor(advisor); factory.addAdvisor(advisor);
TestService bean = (TestService) factory.getProxy(); TestService bean = (TestService) factory.getProxy();
assertEquals(0, logAdvice.getCountThrows()); assertThat(logAdvice.getCountThrows()).isEqualTo(0);
assertThatExceptionOfType(TestException.class).isThrownBy( assertThatExceptionOfType(TestException.class).isThrownBy(
bean::sayHello).withMessageContaining(message); bean::sayHello).withMessageContaining(message);
assertEquals(1, logAdvice.getCountThrows()); assertThat(logAdvice.getCountThrows()).isEqualTo(1);
} }

View File

@ -26,10 +26,9 @@ import org.springframework.tests.sample.beans.ITestBean;
import org.springframework.tests.sample.beans.TestBean; import org.springframework.tests.sample.beans.TestBean;
import org.springframework.tests.sample.beans.subpkg.DeepBean; import org.springframework.tests.sample.beans.subpkg.DeepBean;
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.assertj.core.api.Assertions.assertThatIllegalStateException; import static org.assertj.core.api.Assertions.assertThatIllegalStateException;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
/** /**
* Unit tests for the {@link TypePatternClassFilter} class. * Unit tests for the {@link TypePatternClassFilter} class.
@ -50,36 +49,36 @@ public class TypePatternClassFilterTests {
@Test @Test
public void testValidPatternMatching() { public void testValidPatternMatching() {
TypePatternClassFilter tpcf = new TypePatternClassFilter("org.springframework.tests.sample.beans.*"); TypePatternClassFilter tpcf = new TypePatternClassFilter("org.springframework.tests.sample.beans.*");
assertTrue("Must match: in package", tpcf.matches(TestBean.class)); assertThat(tpcf.matches(TestBean.class)).as("Must match: in package").isTrue();
assertTrue("Must match: in package", tpcf.matches(ITestBean.class)); assertThat(tpcf.matches(ITestBean.class)).as("Must match: in package").isTrue();
assertTrue("Must match: in package", tpcf.matches(IOther.class)); assertThat(tpcf.matches(IOther.class)).as("Must match: in package").isTrue();
assertFalse("Must be excluded: in wrong package", tpcf.matches(DeepBean.class)); assertThat(tpcf.matches(DeepBean.class)).as("Must be excluded: in wrong package").isFalse();
assertFalse("Must be excluded: in wrong package", tpcf.matches(BeanFactory.class)); assertThat(tpcf.matches(BeanFactory.class)).as("Must be excluded: in wrong package").isFalse();
assertFalse("Must be excluded: in wrong package", tpcf.matches(DefaultListableBeanFactory.class)); assertThat(tpcf.matches(DefaultListableBeanFactory.class)).as("Must be excluded: in wrong package").isFalse();
} }
@Test @Test
public void testSubclassMatching() { public void testSubclassMatching() {
TypePatternClassFilter tpcf = new TypePatternClassFilter("org.springframework.tests.sample.beans.ITestBean+"); TypePatternClassFilter tpcf = new TypePatternClassFilter("org.springframework.tests.sample.beans.ITestBean+");
assertTrue("Must match: in package", tpcf.matches(TestBean.class)); assertThat(tpcf.matches(TestBean.class)).as("Must match: in package").isTrue();
assertTrue("Must match: in package", tpcf.matches(ITestBean.class)); assertThat(tpcf.matches(ITestBean.class)).as("Must match: in package").isTrue();
assertTrue("Must match: in package", tpcf.matches(CountingTestBean.class)); assertThat(tpcf.matches(CountingTestBean.class)).as("Must match: in package").isTrue();
assertFalse("Must be excluded: not subclass", tpcf.matches(IOther.class)); assertThat(tpcf.matches(IOther.class)).as("Must be excluded: not subclass").isFalse();
assertFalse("Must be excluded: not subclass", tpcf.matches(DefaultListableBeanFactory.class)); assertThat(tpcf.matches(DefaultListableBeanFactory.class)).as("Must be excluded: not subclass").isFalse();
} }
@Test @Test
public void testAndOrNotReplacement() { public void testAndOrNotReplacement() {
TypePatternClassFilter tpcf = new TypePatternClassFilter("java.lang.Object or java.lang.String"); TypePatternClassFilter tpcf = new TypePatternClassFilter("java.lang.Object or java.lang.String");
assertFalse("matches Number",tpcf.matches(Number.class)); assertThat(tpcf.matches(Number.class)).as("matches Number").isFalse();
assertTrue("matches Object",tpcf.matches(Object.class)); assertThat(tpcf.matches(Object.class)).as("matches Object").isTrue();
assertTrue("matchesString",tpcf.matches(String.class)); assertThat(tpcf.matches(String.class)).as("matchesString").isTrue();
tpcf = new TypePatternClassFilter("java.lang.Number+ and java.lang.Float"); tpcf = new TypePatternClassFilter("java.lang.Number+ and java.lang.Float");
assertTrue("matches Float",tpcf.matches(Float.class)); assertThat(tpcf.matches(Float.class)).as("matches Float").isTrue();
assertFalse("matches Double",tpcf.matches(Double.class)); assertThat(tpcf.matches(Double.class)).as("matches Double").isFalse();
tpcf = new TypePatternClassFilter("java.lang.Number+ and not java.lang.Float"); tpcf = new TypePatternClassFilter("java.lang.Number+ and not java.lang.Float");
assertFalse("matches Float",tpcf.matches(Float.class)); assertThat(tpcf.matches(Float.class)).as("matches Float").isFalse();
assertTrue("matches Double",tpcf.matches(Double.class)); assertThat(tpcf.matches(Double.class)).as("matches Double").isTrue();
} }
@Test @Test

View File

@ -62,10 +62,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.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotSame;
import static org.junit.Assert.assertTrue;
/** /**
* Abstract tests for AspectJAdvisorFactory. * Abstract tests for AspectJAdvisorFactory.
@ -108,28 +104,28 @@ public abstract class AbstractAspectJAdvisorFactoryTests {
TestBean itb = (TestBean) createProxy(target, TestBean itb = (TestBean) createProxy(target,
getFixture().getAdvisors(new SingletonMetadataAwareAspectInstanceFactory(new PerTargetAspect(), "someBean")), getFixture().getAdvisors(new SingletonMetadataAwareAspectInstanceFactory(new PerTargetAspect(), "someBean")),
TestBean.class); TestBean.class);
assertEquals("Around advice must NOT apply", realAge, itb.getAge()); assertThat(itb.getAge()).as("Around advice must NOT apply").isEqualTo(realAge);
Advised advised = (Advised) itb; Advised advised = (Advised) itb;
ReflectiveAspectJAdvisorFactory.SyntheticInstantiationAdvisor sia = ReflectiveAspectJAdvisorFactory.SyntheticInstantiationAdvisor sia =
(ReflectiveAspectJAdvisorFactory.SyntheticInstantiationAdvisor) advised.getAdvisors()[1]; (ReflectiveAspectJAdvisorFactory.SyntheticInstantiationAdvisor) advised.getAdvisors()[1];
assertTrue(sia.getPointcut().getMethodMatcher().matches(TestBean.class.getMethod("getSpouse"), null)); assertThat(sia.getPointcut().getMethodMatcher().matches(TestBean.class.getMethod("getSpouse"), null)).isTrue();
InstantiationModelAwarePointcutAdvisorImpl imapa = (InstantiationModelAwarePointcutAdvisorImpl) advised.getAdvisors()[3]; InstantiationModelAwarePointcutAdvisorImpl imapa = (InstantiationModelAwarePointcutAdvisorImpl) advised.getAdvisors()[3];
LazySingletonAspectInstanceFactoryDecorator maaif = LazySingletonAspectInstanceFactoryDecorator maaif =
(LazySingletonAspectInstanceFactoryDecorator) imapa.getAspectInstanceFactory(); (LazySingletonAspectInstanceFactoryDecorator) imapa.getAspectInstanceFactory();
assertFalse(maaif.isMaterialized()); assertThat(maaif.isMaterialized()).isFalse();
// Check that the perclause pointcut is valid // Check that the perclause pointcut is valid
assertTrue(maaif.getAspectMetadata().getPerClausePointcut().getMethodMatcher().matches(TestBean.class.getMethod("getSpouse"), null)); assertThat(maaif.getAspectMetadata().getPerClausePointcut().getMethodMatcher().matches(TestBean.class.getMethod("getSpouse"), null)).isTrue();
assertNotSame(imapa.getDeclaredPointcut(), imapa.getPointcut()); assertThat(imapa.getPointcut()).isNotSameAs(imapa.getDeclaredPointcut());
// Hit the method in the per clause to instantiate the aspect // Hit the method in the per clause to instantiate the aspect
itb.getSpouse(); itb.getSpouse();
assertTrue(maaif.isMaterialized()); assertThat(maaif.isMaterialized()).isTrue();
assertEquals("Around advice must apply", 0, itb.getAge()); assertThat(itb.getAge()).as("Around advice must apply").isEqualTo(0);
assertEquals("Around advice must apply", 1, itb.getAge()); assertThat(itb.getAge()).as("Around advice must apply").isEqualTo(1);
} }
@Test @Test
@ -151,13 +147,13 @@ public abstract class AbstractAspectJAdvisorFactoryTests {
Collections.sort(advisors, new OrderComparator()); Collections.sort(advisors, new OrderComparator());
TestBean itb = (TestBean) createProxy(target, advisors, TestBean.class); TestBean itb = (TestBean) createProxy(target, advisors, TestBean.class);
assertEquals("Around advice must NOT apply", realAge, itb.getAge()); assertThat(itb.getAge()).as("Around advice must NOT apply").isEqualTo(realAge);
// Hit the method in the per clause to instantiate the aspect // Hit the method in the per clause to instantiate the aspect
itb.getSpouse(); itb.getSpouse();
assertEquals("Around advice must apply", 0, itb.getAge()); assertThat(itb.getAge()).as("Around advice must apply").isEqualTo(0);
assertEquals("Around advice must apply", 1, itb.getAge()); assertThat(itb.getAge()).as("Around advice must apply").isEqualTo(1);
} }
@Test @Test
@ -177,13 +173,13 @@ public abstract class AbstractAspectJAdvisorFactoryTests {
Collections.sort(advisors, new OrderComparator()); Collections.sort(advisors, new OrderComparator());
TestBean itb = (TestBean) createProxy(target, advisors, TestBean.class); TestBean itb = (TestBean) createProxy(target, advisors, TestBean.class);
assertEquals("Around advice must NOT apply", realAge, itb.getAge()); assertThat(itb.getAge()).as("Around advice must NOT apply").isEqualTo(realAge);
// Hit the method in the per clause to instantiate the aspect // Hit the method in the per clause to instantiate the aspect
itb.getSpouse(); itb.getSpouse();
assertEquals("Around advice must apply", 0, itb.getAge()); assertThat(itb.getAge()).as("Around advice must apply").isEqualTo(0);
assertEquals("Around advice must apply", 1, itb.getAge()); assertThat(itb.getAge()).as("Around advice must apply").isEqualTo(1);
} }
@Test @Test
@ -194,32 +190,32 @@ public abstract class AbstractAspectJAdvisorFactoryTests {
TestBean itb = (TestBean) createProxy(target, TestBean itb = (TestBean) createProxy(target,
getFixture().getAdvisors(new SingletonMetadataAwareAspectInstanceFactory(new PerThisAspect(), "someBean")), getFixture().getAdvisors(new SingletonMetadataAwareAspectInstanceFactory(new PerThisAspect(), "someBean")),
TestBean.class); TestBean.class);
assertEquals("Around advice must NOT apply", realAge, itb.getAge()); assertThat(itb.getAge()).as("Around advice must NOT apply").isEqualTo(realAge);
Advised advised = (Advised) itb; Advised advised = (Advised) itb;
// Will be ExposeInvocationInterceptor, synthetic instantiation advisor, 2 method advisors // Will be ExposeInvocationInterceptor, synthetic instantiation advisor, 2 method advisors
assertEquals(4, advised.getAdvisors().length); assertThat(advised.getAdvisors().length).isEqualTo(4);
ReflectiveAspectJAdvisorFactory.SyntheticInstantiationAdvisor sia = ReflectiveAspectJAdvisorFactory.SyntheticInstantiationAdvisor sia =
(ReflectiveAspectJAdvisorFactory.SyntheticInstantiationAdvisor) advised.getAdvisors()[1]; (ReflectiveAspectJAdvisorFactory.SyntheticInstantiationAdvisor) advised.getAdvisors()[1];
assertTrue(sia.getPointcut().getMethodMatcher().matches(TestBean.class.getMethod("getSpouse"), null)); assertThat(sia.getPointcut().getMethodMatcher().matches(TestBean.class.getMethod("getSpouse"), null)).isTrue();
InstantiationModelAwarePointcutAdvisorImpl imapa = (InstantiationModelAwarePointcutAdvisorImpl) advised.getAdvisors()[2]; InstantiationModelAwarePointcutAdvisorImpl imapa = (InstantiationModelAwarePointcutAdvisorImpl) advised.getAdvisors()[2];
LazySingletonAspectInstanceFactoryDecorator maaif = LazySingletonAspectInstanceFactoryDecorator maaif =
(LazySingletonAspectInstanceFactoryDecorator) imapa.getAspectInstanceFactory(); (LazySingletonAspectInstanceFactoryDecorator) imapa.getAspectInstanceFactory();
assertFalse(maaif.isMaterialized()); assertThat(maaif.isMaterialized()).isFalse();
// Check that the perclause pointcut is valid // Check that the perclause pointcut is valid
assertTrue(maaif.getAspectMetadata().getPerClausePointcut().getMethodMatcher().matches(TestBean.class.getMethod("getSpouse"), null)); assertThat(maaif.getAspectMetadata().getPerClausePointcut().getMethodMatcher().matches(TestBean.class.getMethod("getSpouse"), null)).isTrue();
assertNotSame(imapa.getDeclaredPointcut(), imapa.getPointcut()); assertThat(imapa.getPointcut()).isNotSameAs(imapa.getDeclaredPointcut());
// Hit the method in the per clause to instantiate the aspect // Hit the method in the per clause to instantiate the aspect
itb.getSpouse(); itb.getSpouse();
assertTrue(maaif.isMaterialized()); assertThat(maaif.isMaterialized()).isTrue();
assertTrue(imapa.getDeclaredPointcut().getMethodMatcher().matches(TestBean.class.getMethod("getAge"), null)); assertThat(imapa.getDeclaredPointcut().getMethodMatcher().matches(TestBean.class.getMethod("getAge"), null)).isTrue();
assertEquals("Around advice must apply", 0, itb.getAge()); assertThat(itb.getAge()).as("Around advice must apply").isEqualTo(0);
assertEquals("Around advice must apply", 1, itb.getAge()); assertThat(itb.getAge()).as("Around advice must apply").isEqualTo(1);
} }
@Test @Test
@ -229,38 +225,38 @@ public abstract class AbstractAspectJAdvisorFactoryTests {
target.setAge(realAge); target.setAge(realAge);
PerTypeWithinAspectInstanceFactory aif = new PerTypeWithinAspectInstanceFactory(); PerTypeWithinAspectInstanceFactory aif = new PerTypeWithinAspectInstanceFactory();
TestBean itb = (TestBean) createProxy(target, getFixture().getAdvisors(aif), TestBean.class); TestBean itb = (TestBean) createProxy(target, getFixture().getAdvisors(aif), TestBean.class);
assertEquals("No method calls", 0, aif.getInstantiationCount()); assertThat(aif.getInstantiationCount()).as("No method calls").isEqualTo(0);
assertEquals("Around advice must now apply", 0, itb.getAge()); assertThat(itb.getAge()).as("Around advice must now apply").isEqualTo(0);
Advised advised = (Advised) itb; Advised advised = (Advised) itb;
// Will be ExposeInvocationInterceptor, synthetic instantiation advisor, 2 method advisors // Will be ExposeInvocationInterceptor, synthetic instantiation advisor, 2 method advisors
assertEquals(4, advised.getAdvisors().length); assertThat(advised.getAdvisors().length).isEqualTo(4);
ReflectiveAspectJAdvisorFactory.SyntheticInstantiationAdvisor sia = ReflectiveAspectJAdvisorFactory.SyntheticInstantiationAdvisor sia =
(ReflectiveAspectJAdvisorFactory.SyntheticInstantiationAdvisor) advised.getAdvisors()[1]; (ReflectiveAspectJAdvisorFactory.SyntheticInstantiationAdvisor) advised.getAdvisors()[1];
assertTrue(sia.getPointcut().getMethodMatcher().matches(TestBean.class.getMethod("getSpouse"), null)); assertThat(sia.getPointcut().getMethodMatcher().matches(TestBean.class.getMethod("getSpouse"), null)).isTrue();
InstantiationModelAwarePointcutAdvisorImpl imapa = (InstantiationModelAwarePointcutAdvisorImpl) advised.getAdvisors()[2]; InstantiationModelAwarePointcutAdvisorImpl imapa = (InstantiationModelAwarePointcutAdvisorImpl) advised.getAdvisors()[2];
LazySingletonAspectInstanceFactoryDecorator maaif = LazySingletonAspectInstanceFactoryDecorator maaif =
(LazySingletonAspectInstanceFactoryDecorator) imapa.getAspectInstanceFactory(); (LazySingletonAspectInstanceFactoryDecorator) imapa.getAspectInstanceFactory();
assertTrue(maaif.isMaterialized()); assertThat(maaif.isMaterialized()).isTrue();
// Check that the perclause pointcut is valid // Check that the perclause pointcut is valid
assertTrue(maaif.getAspectMetadata().getPerClausePointcut().getMethodMatcher().matches(TestBean.class.getMethod("getSpouse"), null)); assertThat(maaif.getAspectMetadata().getPerClausePointcut().getMethodMatcher().matches(TestBean.class.getMethod("getSpouse"), null)).isTrue();
assertNotSame(imapa.getDeclaredPointcut(), imapa.getPointcut()); assertThat(imapa.getPointcut()).isNotSameAs(imapa.getDeclaredPointcut());
// Hit the method in the per clause to instantiate the aspect // Hit the method in the per clause to instantiate the aspect
itb.getSpouse(); itb.getSpouse();
assertTrue(maaif.isMaterialized()); assertThat(maaif.isMaterialized()).isTrue();
assertTrue(imapa.getDeclaredPointcut().getMethodMatcher().matches(TestBean.class.getMethod("getAge"), null)); assertThat(imapa.getDeclaredPointcut().getMethodMatcher().matches(TestBean.class.getMethod("getAge"), null)).isTrue();
assertEquals("Around advice must still apply", 1, itb.getAge()); assertThat(itb.getAge()).as("Around advice must still apply").isEqualTo(1);
assertEquals("Around advice must still apply", 2, itb.getAge()); assertThat(itb.getAge()).as("Around advice must still apply").isEqualTo(2);
TestBean itb2 = (TestBean) createProxy(target, getFixture().getAdvisors(aif), TestBean.class); TestBean itb2 = (TestBean) createProxy(target, getFixture().getAdvisors(aif), TestBean.class);
assertEquals(1, aif.getInstantiationCount()); assertThat(aif.getInstantiationCount()).isEqualTo(1);
assertEquals("Around advice be independent for second instance", 0, itb2.getAge()); assertThat(itb2.getAge()).as("Around advice be independent for second instance").isEqualTo(0);
assertEquals(2, aif.getInstantiationCount()); assertThat(aif.getInstantiationCount()).isEqualTo(2);
} }
@Test @Test
@ -286,8 +282,8 @@ public abstract class AbstractAspectJAdvisorFactoryTests {
new NamedPointcutAspectFromLibraryWithBinding(), "someBean")), new NamedPointcutAspectFromLibraryWithBinding(), "someBean")),
ITestBean.class); ITestBean.class);
itb.setAge(10); itb.setAge(10);
assertEquals("Around advice must apply", 20, itb.getAge()); assertThat(itb.getAge()).as("Around advice must apply").isEqualTo(20);
assertEquals(20,target.getAge()); assertThat(target.getAge()).isEqualTo(20);
} }
private void testNamedPointcuts(Object aspectInstance) { private void testNamedPointcuts(Object aspectInstance) {
@ -297,8 +293,8 @@ public abstract class AbstractAspectJAdvisorFactoryTests {
ITestBean itb = (ITestBean) createProxy(target, ITestBean itb = (ITestBean) createProxy(target,
getFixture().getAdvisors(new SingletonMetadataAwareAspectInstanceFactory(aspectInstance, "someBean")), getFixture().getAdvisors(new SingletonMetadataAwareAspectInstanceFactory(aspectInstance, "someBean")),
ITestBean.class); ITestBean.class);
assertEquals("Around advice must apply", -1, itb.getAge()); assertThat(itb.getAge()).as("Around advice must apply").isEqualTo(-1);
assertEquals(realAge, target.getAge()); assertThat(target.getAge()).isEqualTo(realAge);
} }
@Test @Test
@ -309,8 +305,8 @@ public abstract class AbstractAspectJAdvisorFactoryTests {
new SingletonMetadataAwareAspectInstanceFactory(new BindingAspectWithSingleArg(), "someBean")), new SingletonMetadataAwareAspectInstanceFactory(new BindingAspectWithSingleArg(), "someBean")),
ITestBean.class); ITestBean.class);
itb.setAge(10); itb.setAge(10);
assertEquals("Around advice must apply", 20, itb.getAge()); assertThat(itb.getAge()).as("Around advice must apply").isEqualTo(20);
assertEquals(20,target.getAge()); assertThat(target.getAge()).isEqualTo(20);
} }
@Test @Test
@ -327,7 +323,7 @@ public abstract class AbstractAspectJAdvisorFactoryTests {
String d = "d"; String d = "d";
StringBuffer e = new StringBuffer("stringbuf"); StringBuffer e = new StringBuffer("stringbuf");
String expectedResult = a + b+ c + d + e; String expectedResult = a + b+ c + d + e;
assertEquals(expectedResult, mva.mungeArgs(a, b, c, d, e)); assertThat(mva.mungeArgs(a, b, c, d, e)).isEqualTo(expectedResult);
} }
/** /**
@ -336,40 +332,40 @@ public abstract class AbstractAspectJAdvisorFactoryTests {
@Test @Test
public void testIntroductionOnTargetNotImplementingInterface() { public void testIntroductionOnTargetNotImplementingInterface() {
NotLockable notLockableTarget = new NotLockable(); NotLockable notLockableTarget = new NotLockable();
assertFalse(notLockableTarget instanceof Lockable); assertThat(notLockableTarget instanceof Lockable).isFalse();
NotLockable notLockable1 = (NotLockable) createProxy(notLockableTarget, NotLockable notLockable1 = (NotLockable) createProxy(notLockableTarget,
getFixture().getAdvisors( getFixture().getAdvisors(
new SingletonMetadataAwareAspectInstanceFactory(new MakeLockable(), "someBean")), new SingletonMetadataAwareAspectInstanceFactory(new MakeLockable(), "someBean")),
NotLockable.class); NotLockable.class);
assertTrue(notLockable1 instanceof Lockable); assertThat(notLockable1 instanceof Lockable).isTrue();
Lockable lockable = (Lockable) notLockable1; Lockable lockable = (Lockable) notLockable1;
assertFalse(lockable.locked()); assertThat(lockable.locked()).isFalse();
lockable.lock(); lockable.lock();
assertTrue(lockable.locked()); assertThat(lockable.locked()).isTrue();
NotLockable notLockable2Target = new NotLockable(); NotLockable notLockable2Target = new NotLockable();
NotLockable notLockable2 = (NotLockable) createProxy(notLockable2Target, NotLockable notLockable2 = (NotLockable) createProxy(notLockable2Target,
getFixture().getAdvisors( getFixture().getAdvisors(
new SingletonMetadataAwareAspectInstanceFactory(new MakeLockable(), "someBean")), new SingletonMetadataAwareAspectInstanceFactory(new MakeLockable(), "someBean")),
NotLockable.class); NotLockable.class);
assertTrue(notLockable2 instanceof Lockable); assertThat(notLockable2 instanceof Lockable).isTrue();
Lockable lockable2 = (Lockable) notLockable2; Lockable lockable2 = (Lockable) notLockable2;
assertFalse(lockable2.locked()); assertThat(lockable2.locked()).isFalse();
notLockable2.setIntValue(1); notLockable2.setIntValue(1);
lockable2.lock(); lockable2.lock();
assertThatIllegalStateException().isThrownBy(() -> assertThatIllegalStateException().isThrownBy(() ->
notLockable2.setIntValue(32)); notLockable2.setIntValue(32));
assertTrue(lockable2.locked()); assertThat(lockable2.locked()).isTrue();
} }
@Test @Test
public void testIntroductionAdvisorExcludedFromTargetImplementingInterface() { public void testIntroductionAdvisorExcludedFromTargetImplementingInterface() {
assertTrue(AopUtils.findAdvisorsThatCanApply( assertThat(AopUtils.findAdvisorsThatCanApply(
getFixture().getAdvisors( getFixture().getAdvisors(
new SingletonMetadataAwareAspectInstanceFactory(new MakeLockable(), "someBean")), new SingletonMetadataAwareAspectInstanceFactory(new MakeLockable(), "someBean")),
CannotBeUnlocked.class).isEmpty()); CannotBeUnlocked.class).isEmpty()).isTrue();
assertEquals(2, AopUtils.findAdvisorsThatCanApply(getFixture().getAdvisors( assertThat(AopUtils.findAdvisorsThatCanApply(getFixture().getAdvisors(
new SingletonMetadataAwareAspectInstanceFactory(new MakeLockable(),"someBean")), NotLockable.class).size()); new SingletonMetadataAwareAspectInstanceFactory(new MakeLockable(),"someBean")), NotLockable.class).size()).isEqualTo(2);
} }
@Test @Test
@ -385,9 +381,9 @@ public abstract class AbstractAspectJAdvisorFactoryTests {
CannotBeUnlocked.class); CannotBeUnlocked.class);
assertThat(proxy).isInstanceOf(Lockable.class); assertThat(proxy).isInstanceOf(Lockable.class);
Lockable lockable = proxy; Lockable lockable = proxy;
assertTrue("Already locked", lockable.locked()); assertThat(lockable.locked()).as("Already locked").isTrue();
lockable.lock(); lockable.lock();
assertTrue("Real target ignores locking", lockable.locked()); assertThat(lockable.locked()).as("Real target ignores locking").isTrue();
assertThatExceptionOfType(UnsupportedOperationException.class).isThrownBy(() -> assertThatExceptionOfType(UnsupportedOperationException.class).isThrownBy(() ->
lockable.unlock()); lockable.unlock());
} }
@ -401,7 +397,7 @@ public abstract class AbstractAspectJAdvisorFactoryTests {
List.class List.class
), ),
List.class); List.class);
assertFalse("Type pattern must have excluded mixin", proxy instanceof Lockable); assertThat(proxy instanceof Lockable).as("Type pattern must have excluded mixin").isFalse();
} }
@Test @Test
@ -411,7 +407,7 @@ public abstract class AbstractAspectJAdvisorFactoryTests {
new SingletonMetadataAwareAspectInstanceFactory(new MakeAnnotatedTypeModifiable(), "someBean")); new SingletonMetadataAwareAspectInstanceFactory(new MakeAnnotatedTypeModifiable(), "someBean"));
Object proxy = createProxy(target, advisors, AnnotatedTarget.class); Object proxy = createProxy(target, advisors, AnnotatedTarget.class);
System.out.println(advisors.get(1)); System.out.println(advisors.get(1));
assertTrue(proxy instanceof Lockable); assertThat(proxy instanceof Lockable).isTrue();
Lockable lockable = (Lockable)proxy; Lockable lockable = (Lockable)proxy;
lockable.locked(); lockable.locked();
} }
@ -430,22 +426,22 @@ public abstract class AbstractAspectJAdvisorFactoryTests {
Modifiable modifiable = (Modifiable) createProxy(target, advisors, ITestBean.class); Modifiable modifiable = (Modifiable) createProxy(target, advisors, ITestBean.class);
assertThat(modifiable).isInstanceOf(Modifiable.class); assertThat(modifiable).isInstanceOf(Modifiable.class);
Lockable lockable = (Lockable) modifiable; Lockable lockable = (Lockable) modifiable;
assertFalse(lockable.locked()); assertThat(lockable.locked()).isFalse();
ITestBean itb = (ITestBean) modifiable; ITestBean itb = (ITestBean) modifiable;
assertFalse(modifiable.isModified()); assertThat(modifiable.isModified()).isFalse();
int oldAge = itb.getAge(); int oldAge = itb.getAge();
itb.setAge(oldAge + 1); itb.setAge(oldAge + 1);
assertTrue(modifiable.isModified()); assertThat(modifiable.isModified()).isTrue();
modifiable.acceptChanges(); modifiable.acceptChanges();
assertFalse(modifiable.isModified()); assertThat(modifiable.isModified()).isFalse();
itb.setAge(itb.getAge()); itb.setAge(itb.getAge());
assertFalse("Setting same value does not modify", modifiable.isModified()); assertThat(modifiable.isModified()).as("Setting same value does not modify").isFalse();
itb.setName("And now for something completely different"); itb.setName("And now for something completely different");
assertTrue(modifiable.isModified()); assertThat(modifiable.isModified()).isTrue();
lockable.lock(); lockable.lock();
assertTrue(lockable.locked()); assertThat(lockable.locked()).isTrue();
assertThatIllegalStateException().as("Should be locked").isThrownBy(() -> assertThatIllegalStateException().as("Should be locked").isThrownBy(() ->
itb.setName("Else")); itb.setName("Else"));
lockable.unlock(); lockable.unlock();
@ -458,7 +454,7 @@ public abstract class AbstractAspectJAdvisorFactoryTests {
UnsupportedOperationException expectedException = new UnsupportedOperationException(); UnsupportedOperationException expectedException = new UnsupportedOperationException();
List<Advisor> advisors = getFixture().getAdvisors( List<Advisor> advisors = getFixture().getAdvisors(
new SingletonMetadataAwareAspectInstanceFactory(new ExceptionAspect(expectedException), "someBean")); new SingletonMetadataAwareAspectInstanceFactory(new ExceptionAspect(expectedException), "someBean"));
assertEquals("One advice method was found", 1, advisors.size()); assertThat(advisors.size()).as("One advice method was found").isEqualTo(1);
ITestBean itb = (ITestBean) createProxy(target, advisors, ITestBean.class); ITestBean itb = (ITestBean) createProxy(target, advisors, ITestBean.class);
assertThatExceptionOfType(UnsupportedOperationException.class).isThrownBy( assertThatExceptionOfType(UnsupportedOperationException.class).isThrownBy(
itb::getAge); itb::getAge);
@ -472,7 +468,7 @@ public abstract class AbstractAspectJAdvisorFactoryTests {
RemoteException expectedException = new RemoteException(); RemoteException expectedException = new RemoteException();
List<Advisor> advisors = getFixture().getAdvisors( List<Advisor> advisors = getFixture().getAdvisors(
new SingletonMetadataAwareAspectInstanceFactory(new ExceptionAspect(expectedException), "someBean")); new SingletonMetadataAwareAspectInstanceFactory(new ExceptionAspect(expectedException), "someBean"));
assertEquals("One advice method was found", 1, advisors.size()); assertThat(advisors.size()).as("One advice method was found").isEqualTo(1);
ITestBean itb = (ITestBean) createProxy(target, advisors, ITestBean.class); ITestBean itb = (ITestBean) createProxy(target, advisors, ITestBean.class);
assertThatExceptionOfType(UndeclaredThrowableException.class).isThrownBy( assertThatExceptionOfType(UndeclaredThrowableException.class).isThrownBy(
itb::getAge).withCause(expectedException); itb::getAge).withCause(expectedException);
@ -501,13 +497,13 @@ public abstract class AbstractAspectJAdvisorFactoryTests {
TwoAdviceAspect twoAdviceAspect = new TwoAdviceAspect(); TwoAdviceAspect twoAdviceAspect = new TwoAdviceAspect();
List<Advisor> advisors = getFixture().getAdvisors( List<Advisor> advisors = getFixture().getAdvisors(
new SingletonMetadataAwareAspectInstanceFactory(twoAdviceAspect, "someBean")); new SingletonMetadataAwareAspectInstanceFactory(twoAdviceAspect, "someBean"));
assertEquals("Two advice methods found", 2, advisors.size()); assertThat(advisors.size()).as("Two advice methods found").isEqualTo(2);
ITestBean itb = (ITestBean) createProxy(target, advisors, ITestBean.class); ITestBean itb = (ITestBean) createProxy(target, advisors, ITestBean.class);
itb.setName(""); itb.setName("");
assertEquals(0, itb.getAge()); assertThat(itb.getAge()).isEqualTo(0);
int newAge = 32; int newAge = 32;
itb.setAge(newAge); itb.setAge(newAge);
assertEquals(1, itb.getAge()); assertThat(itb.getAge()).isEqualTo(1);
} }
@Test @Test
@ -517,15 +513,15 @@ public abstract class AbstractAspectJAdvisorFactoryTests {
List<Advisor> advisors = getFixture().getAdvisors( List<Advisor> advisors = getFixture().getAdvisors(
new SingletonMetadataAwareAspectInstanceFactory(afterReturningAspect, "someBean")); new SingletonMetadataAwareAspectInstanceFactory(afterReturningAspect, "someBean"));
Echo echo = (Echo) createProxy(target, advisors, Echo.class); Echo echo = (Echo) createProxy(target, advisors, Echo.class);
assertEquals(0, afterReturningAspect.successCount); assertThat(afterReturningAspect.successCount).isEqualTo(0);
assertEquals("", echo.echo("")); assertThat(echo.echo("")).isEqualTo("");
assertEquals(1, afterReturningAspect.successCount); assertThat(afterReturningAspect.successCount).isEqualTo(1);
assertEquals(0, afterReturningAspect.failureCount); assertThat(afterReturningAspect.failureCount).isEqualTo(0);
assertThatExceptionOfType(FileNotFoundException.class).isThrownBy(() -> assertThatExceptionOfType(FileNotFoundException.class).isThrownBy(() ->
echo.echo(new FileNotFoundException())); echo.echo(new FileNotFoundException()));
assertEquals(1, afterReturningAspect.successCount); assertThat(afterReturningAspect.successCount).isEqualTo(1);
assertEquals(1, afterReturningAspect.failureCount); assertThat(afterReturningAspect.failureCount).isEqualTo(1);
assertEquals(afterReturningAspect.failureCount + afterReturningAspect.successCount, afterReturningAspect.afterCount); assertThat(afterReturningAspect.afterCount).isEqualTo(afterReturningAspect.failureCount + afterReturningAspect.successCount);
} }
@Test @Test
@ -651,6 +647,7 @@ public abstract class AbstractAspectJAdvisorFactoryTests {
@Aspect @Aspect
public static class NamedPointcutAspectWithFQN { public static class NamedPointcutAspectWithFQN {
@SuppressWarnings("unused")
private ITestBean fieldThatShouldBeIgnoredBySpringAtAspectJProcessing = new TestBean(); private ITestBean fieldThatShouldBeIgnoredBySpringAtAspectJProcessing = new TestBean();
@Pointcut("execution(* getAge())") @Pointcut("execution(* getAge())")
@ -739,7 +736,7 @@ public abstract class AbstractAspectJAdvisorFactoryTests {
@Around(value="execution(String mungeArgs(..)) && args(a, b, c, d, e)", argNames="b,c,d,e,a") @Around(value="execution(String mungeArgs(..)) && args(a, b, c, d, e)", argNames="b,c,d,e,a")
public String reverseAdvice(ProceedingJoinPoint pjp, int b, int c, String d, StringBuffer e, String a) throws Throwable { public String reverseAdvice(ProceedingJoinPoint pjp, int b, int c, String d, StringBuffer e, String a) throws Throwable {
assertEquals(a + b+ c+ d+ e, pjp.proceed()); assertThat(pjp.proceed()).isEqualTo(a + b+ c+ d+ e);
return a + b + c + d + e; return a + b + c + d + e;
} }
} }
@ -1053,6 +1050,7 @@ class PerThisAspect {
public int count; public int count;
// Just to check that this doesn't cause problems with introduction processing // Just to check that this doesn't cause problems with introduction processing
@SuppressWarnings("unused")
private ITestBean fieldThatShouldBeIgnoredBySpringAtAspectJProcessing = new TestBean(); private ITestBean fieldThatShouldBeIgnoredBySpringAtAspectJProcessing = new TestBean();
@Around("execution(int *.getAge())") @Around("execution(int *.getAge())")

View File

@ -30,9 +30,9 @@ import org.springframework.aop.aspectj.AspectJAdviceParameterNameDiscoverer;
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.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.junit.Assert.assertEquals;
/** /**
* @author Adrian Colyer * @author Adrian Colyer
@ -71,8 +71,8 @@ public class ArgumentBindingTests {
Method methodUsedForParameterTypeDiscovery = Method methodUsedForParameterTypeDiscovery =
getClass().getMethod("methodWithOneParam", String.class); getClass().getMethod("methodWithOneParam", String.class);
String[] pnames = discoverer.getParameterNames(methodUsedForParameterTypeDiscovery); String[] pnames = discoverer.getParameterNames(methodUsedForParameterTypeDiscovery);
assertEquals("one parameter name", 1, pnames.length); assertThat(pnames.length).as("one parameter name").isEqualTo(1);
assertEquals("formal", pnames[0]); assertThat(pnames[0]).isEqualTo("formal");
} }

View File

@ -25,11 +25,8 @@ import org.springframework.aop.aspectj.AspectJExpressionPointcutTests;
import org.springframework.aop.framework.AopConfigException; import org.springframework.aop.framework.AopConfigException;
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.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotSame;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
/** /**
* @author Rod Johnson * @author Rod Johnson
@ -50,8 +47,8 @@ public class AspectJPointcutAdvisorTests {
new SingletonMetadataAwareAspectInstanceFactory(new AbstractAspectJAdvisorFactoryTests.ExceptionAspect(null), "someBean"), new SingletonMetadataAwareAspectInstanceFactory(new AbstractAspectJAdvisorFactoryTests.ExceptionAspect(null), "someBean"),
1, "someBean"); 1, "someBean");
assertSame(Pointcut.TRUE, ajpa.getAspectMetadata().getPerClausePointcut()); assertThat(ajpa.getAspectMetadata().getPerClausePointcut()).isSameAs(Pointcut.TRUE);
assertFalse(ajpa.isPerInstance()); assertThat(ajpa.isPerInstance()).isFalse();
} }
@Test @Test
@ -64,16 +61,17 @@ public class AspectJPointcutAdvisorTests {
new SingletonMetadataAwareAspectInstanceFactory(new PerTargetAspect(), "someBean"), new SingletonMetadataAwareAspectInstanceFactory(new PerTargetAspect(), "someBean"),
1, "someBean"); 1, "someBean");
assertNotSame(Pointcut.TRUE, ajpa.getAspectMetadata().getPerClausePointcut()); assertThat(ajpa.getAspectMetadata().getPerClausePointcut()).isNotSameAs(Pointcut.TRUE);
assertTrue(ajpa.getAspectMetadata().getPerClausePointcut() instanceof AspectJExpressionPointcut); boolean condition = ajpa.getAspectMetadata().getPerClausePointcut() instanceof AspectJExpressionPointcut;
assertTrue(ajpa.isPerInstance()); assertThat(condition).isTrue();
assertThat(ajpa.isPerInstance()).isTrue();
assertTrue(ajpa.getAspectMetadata().getPerClausePointcut().getClassFilter().matches(TestBean.class)); assertThat(ajpa.getAspectMetadata().getPerClausePointcut().getClassFilter().matches(TestBean.class)).isTrue();
assertFalse(ajpa.getAspectMetadata().getPerClausePointcut().getMethodMatcher().matches( assertThat(ajpa.getAspectMetadata().getPerClausePointcut().getMethodMatcher().matches(
TestBean.class.getMethod("getAge"), TestBean.class)); TestBean.class.getMethod("getAge"), TestBean.class)).isFalse();
assertTrue(ajpa.getAspectMetadata().getPerClausePointcut().getMethodMatcher().matches( assertThat(ajpa.getAspectMetadata().getPerClausePointcut().getMethodMatcher().matches(
TestBean.class.getMethod("getSpouse"), TestBean.class)); TestBean.class.getMethod("getSpouse"), TestBean.class)).isTrue();
} }
@Test @Test

View File

@ -23,12 +23,8 @@ import test.aop.PerTargetAspect;
import org.springframework.aop.Pointcut; import org.springframework.aop.Pointcut;
import org.springframework.aop.aspectj.annotation.AbstractAspectJAdvisorFactoryTests.ExceptionAspect; import org.springframework.aop.aspectj.annotation.AbstractAspectJAdvisorFactoryTests.ExceptionAspect;
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.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotSame;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
/** /**
* @since 2.0 * @since 2.0
@ -46,24 +42,24 @@ public class AspectMetadataTests {
@Test @Test
public void testSingletonAspect() { public void testSingletonAspect() {
AspectMetadata am = new AspectMetadata(ExceptionAspect.class,"someBean"); AspectMetadata am = new AspectMetadata(ExceptionAspect.class,"someBean");
assertFalse(am.isPerThisOrPerTarget()); assertThat(am.isPerThisOrPerTarget()).isFalse();
assertSame(Pointcut.TRUE, am.getPerClausePointcut()); assertThat(am.getPerClausePointcut()).isSameAs(Pointcut.TRUE);
assertEquals(PerClauseKind.SINGLETON, am.getAjType().getPerClause().getKind()); assertThat(am.getAjType().getPerClause().getKind()).isEqualTo(PerClauseKind.SINGLETON);
} }
@Test @Test
public void testPerTargetAspect() { public void testPerTargetAspect() {
AspectMetadata am = new AspectMetadata(PerTargetAspect.class,"someBean"); AspectMetadata am = new AspectMetadata(PerTargetAspect.class,"someBean");
assertTrue(am.isPerThisOrPerTarget()); assertThat(am.isPerThisOrPerTarget()).isTrue();
assertNotSame(Pointcut.TRUE, am.getPerClausePointcut()); assertThat(am.getPerClausePointcut()).isNotSameAs(Pointcut.TRUE);
assertEquals(PerClauseKind.PERTARGET, am.getAjType().getPerClause().getKind()); assertThat(am.getAjType().getPerClause().getKind()).isEqualTo(PerClauseKind.PERTARGET);
} }
@Test @Test
public void testPerThisAspect() { public void testPerThisAspect() {
AspectMetadata am = new AspectMetadata(PerThisAspect.class,"someBean"); AspectMetadata am = new AspectMetadata(PerThisAspect.class,"someBean");
assertTrue(am.isPerThisOrPerTarget()); assertThat(am.isPerThisOrPerTarget()).isTrue();
assertNotSame(Pointcut.TRUE, am.getPerClausePointcut()); assertThat(am.getPerClausePointcut()).isNotSameAs(Pointcut.TRUE);
assertEquals(PerClauseKind.PERTHIS, am.getAjType().getPerClause().getKind()); assertThat(am.getAjType().getPerClause().getKind()).isEqualTo(PerClauseKind.PERTHIS);
} }
} }

View File

@ -28,9 +28,8 @@ import test.aop.PerThisAspect;
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.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
/** /**
* @author Rob Harrop * @author Rob Harrop
@ -53,7 +52,7 @@ public class AspectProxyFactoryTests {
AspectJProxyFactory proxyFactory = new AspectJProxyFactory(bean); AspectJProxyFactory proxyFactory = new AspectJProxyFactory(bean);
proxyFactory.addAspect(MultiplyReturnValue.class); proxyFactory.addAspect(MultiplyReturnValue.class);
ITestBean proxy = proxyFactory.getProxy(); ITestBean proxy = proxyFactory.getProxy();
assertEquals("Multiplication did not occur", bean.getAge() * 2, proxy.getAge()); assertThat(proxy.getAge()).as("Multiplication did not occur").isEqualTo((bean.getAge() * 2));
} }
@Test @Test
@ -70,10 +69,10 @@ public class AspectProxyFactoryTests {
ITestBean proxy1 = pf1.getProxy(); ITestBean proxy1 = pf1.getProxy();
ITestBean proxy2 = pf2.getProxy(); ITestBean proxy2 = pf2.getProxy();
assertEquals(0, proxy1.getAge()); assertThat(proxy1.getAge()).isEqualTo(0);
assertEquals(1, proxy1.getAge()); assertThat(proxy1.getAge()).isEqualTo(1);
assertEquals(0, proxy2.getAge()); assertThat(proxy2.getAge()).isEqualTo(0);
assertEquals(2, proxy1.getAge()); assertThat(proxy1.getAge()).isEqualTo(2);
} }
@Test @Test
@ -84,18 +83,16 @@ public class AspectProxyFactoryTests {
} }
@Test @Test
@SuppressWarnings("unchecked")
public void testSerializable() throws Exception { public void testSerializable() throws Exception {
AspectJProxyFactory proxyFactory = new AspectJProxyFactory(new TestBean()); AspectJProxyFactory proxyFactory = new AspectJProxyFactory(new TestBean());
proxyFactory.addAspect(LoggingAspectOnVarargs.class); proxyFactory.addAspect(LoggingAspectOnVarargs.class);
ITestBean proxy = proxyFactory.getProxy(); ITestBean proxy = proxyFactory.getProxy();
assertTrue(proxy.doWithVarargs(MyEnum.A, MyOtherEnum.C)); assertThat(proxy.doWithVarargs(MyEnum.A, MyOtherEnum.C)).isTrue();
ITestBean tb = (ITestBean) SerializationTestUtils.serializeAndDeserialize(proxy); ITestBean tb = (ITestBean) SerializationTestUtils.serializeAndDeserialize(proxy);
assertTrue(tb.doWithVarargs(MyEnum.A, MyOtherEnum.C)); assertThat(tb.doWithVarargs(MyEnum.A, MyOtherEnum.C)).isTrue();
} }
@Test @Test
@SuppressWarnings("unchecked")
public void testWithInstance() throws Exception { public void testWithInstance() throws Exception {
MultiplyReturnValue aspect = new MultiplyReturnValue(); MultiplyReturnValue aspect = new MultiplyReturnValue();
int multiple = 3; int multiple = 3;
@ -108,10 +105,10 @@ public class AspectProxyFactoryTests {
proxyFactory.addAspect(aspect); proxyFactory.addAspect(aspect);
ITestBean proxy = proxyFactory.getProxy(); ITestBean proxy = proxyFactory.getProxy();
assertEquals(target.getAge() * multiple, proxy.getAge()); assertThat(proxy.getAge()).isEqualTo((target.getAge() * multiple));
ITestBean serializedProxy = (ITestBean) SerializationTestUtils.serializeAndDeserialize(proxy); ITestBean serializedProxy = (ITestBean) SerializationTestUtils.serializeAndDeserialize(proxy);
assertEquals(target.getAge() * multiple, serializedProxy.getAge()); assertThat(serializedProxy.getAge()).isEqualTo((target.getAge() * multiple));
} }
@Test @Test
@ -122,21 +119,19 @@ public class AspectProxyFactoryTests {
} }
@Test // SPR-13328 @Test // SPR-13328
@SuppressWarnings("unchecked")
public void testProxiedVarargsWithEnumArray() throws Exception { public void testProxiedVarargsWithEnumArray() throws Exception {
AspectJProxyFactory proxyFactory = new AspectJProxyFactory(new TestBean()); AspectJProxyFactory proxyFactory = new AspectJProxyFactory(new TestBean());
proxyFactory.addAspect(LoggingAspectOnVarargs.class); proxyFactory.addAspect(LoggingAspectOnVarargs.class);
ITestBean proxy = proxyFactory.getProxy(); ITestBean proxy = proxyFactory.getProxy();
assertTrue(proxy.doWithVarargs(MyEnum.A, MyOtherEnum.C)); assertThat(proxy.doWithVarargs(MyEnum.A, MyOtherEnum.C)).isTrue();
} }
@Test // SPR-13328 @Test // SPR-13328
@SuppressWarnings("unchecked")
public void testUnproxiedVarargsWithEnumArray() throws Exception { public void testUnproxiedVarargsWithEnumArray() throws Exception {
AspectJProxyFactory proxyFactory = new AspectJProxyFactory(new TestBean()); AspectJProxyFactory proxyFactory = new AspectJProxyFactory(new TestBean());
proxyFactory.addAspect(LoggingAspectOnSetter.class); proxyFactory.addAspect(LoggingAspectOnSetter.class);
ITestBean proxy = proxyFactory.getProxy(); ITestBean proxy = proxyFactory.getProxy();
assertTrue(proxy.doWithVarargs(MyEnum.A, MyOtherEnum.C)); assertThat(proxy.doWithVarargs(MyEnum.A, MyOtherEnum.C)).isTrue();
} }

View File

@ -31,7 +31,7 @@ import org.springframework.beans.factory.xml.XmlBeanDefinitionReader;
import org.springframework.beans.factory.xml.XmlReaderContext; import org.springframework.beans.factory.xml.XmlReaderContext;
import org.springframework.tests.beans.CollectingReaderEventListener; import org.springframework.tests.beans.CollectingReaderEventListener;
import static org.junit.Assert.assertEquals; import static org.assertj.core.api.Assertions.assertThat;
/** /**
* @author Rob Harrop * @author Rob Harrop
@ -58,49 +58,46 @@ public class AspectJNamespaceHandlerTests {
@Test @Test
public void testRegisterAutoProxyCreator() throws Exception { public void testRegisterAutoProxyCreator() throws Exception {
AopNamespaceUtils.registerAutoProxyCreatorIfNecessary(this.parserContext, null); AopNamespaceUtils.registerAutoProxyCreatorIfNecessary(this.parserContext, null);
assertEquals("Incorrect number of definitions registered", 1, registry.getBeanDefinitionCount()); assertThat(registry.getBeanDefinitionCount()).as("Incorrect number of definitions registered").isEqualTo(1);
AopNamespaceUtils.registerAspectJAutoProxyCreatorIfNecessary(this.parserContext, null); AopNamespaceUtils.registerAspectJAutoProxyCreatorIfNecessary(this.parserContext, null);
assertEquals("Incorrect number of definitions registered", 1, registry.getBeanDefinitionCount()); assertThat(registry.getBeanDefinitionCount()).as("Incorrect number of definitions registered").isEqualTo(1);
} }
@Test @Test
public void testRegisterAspectJAutoProxyCreator() throws Exception { public void testRegisterAspectJAutoProxyCreator() throws Exception {
AopNamespaceUtils.registerAspectJAutoProxyCreatorIfNecessary(this.parserContext, null); AopNamespaceUtils.registerAspectJAutoProxyCreatorIfNecessary(this.parserContext, null);
assertEquals("Incorrect number of definitions registered", 1, registry.getBeanDefinitionCount()); assertThat(registry.getBeanDefinitionCount()).as("Incorrect number of definitions registered").isEqualTo(1);
AopNamespaceUtils.registerAspectJAutoProxyCreatorIfNecessary(this.parserContext, null); AopNamespaceUtils.registerAspectJAutoProxyCreatorIfNecessary(this.parserContext, null);
assertEquals("Incorrect number of definitions registered", 1, registry.getBeanDefinitionCount()); assertThat(registry.getBeanDefinitionCount()).as("Incorrect number of definitions registered").isEqualTo(1);
BeanDefinition definition = registry.getBeanDefinition(AopConfigUtils.AUTO_PROXY_CREATOR_BEAN_NAME); BeanDefinition definition = registry.getBeanDefinition(AopConfigUtils.AUTO_PROXY_CREATOR_BEAN_NAME);
assertEquals("Incorrect APC class", assertThat(definition.getBeanClassName()).as("Incorrect APC class").isEqualTo(AspectJAwareAdvisorAutoProxyCreator.class.getName());
AspectJAwareAdvisorAutoProxyCreator.class.getName(), definition.getBeanClassName());
} }
@Test @Test
public void testRegisterAspectJAutoProxyCreatorWithExistingAutoProxyCreator() throws Exception { public void testRegisterAspectJAutoProxyCreatorWithExistingAutoProxyCreator() throws Exception {
AopNamespaceUtils.registerAutoProxyCreatorIfNecessary(this.parserContext, null); AopNamespaceUtils.registerAutoProxyCreatorIfNecessary(this.parserContext, null);
assertEquals(1, registry.getBeanDefinitionCount()); assertThat(registry.getBeanDefinitionCount()).isEqualTo(1);
AopNamespaceUtils.registerAspectJAutoProxyCreatorIfNecessary(this.parserContext, null); AopNamespaceUtils.registerAspectJAutoProxyCreatorIfNecessary(this.parserContext, null);
assertEquals("Incorrect definition count", 1, registry.getBeanDefinitionCount()); assertThat(registry.getBeanDefinitionCount()).as("Incorrect definition count").isEqualTo(1);
BeanDefinition definition = registry.getBeanDefinition(AopConfigUtils.AUTO_PROXY_CREATOR_BEAN_NAME); BeanDefinition definition = registry.getBeanDefinition(AopConfigUtils.AUTO_PROXY_CREATOR_BEAN_NAME);
assertEquals("APC class not switched", assertThat(definition.getBeanClassName()).as("APC class not switched").isEqualTo(AspectJAwareAdvisorAutoProxyCreator.class.getName());
AspectJAwareAdvisorAutoProxyCreator.class.getName(), definition.getBeanClassName());
} }
@Test @Test
public void testRegisterAutoProxyCreatorWhenAspectJAutoProxyCreatorAlreadyExists() throws Exception { public void testRegisterAutoProxyCreatorWhenAspectJAutoProxyCreatorAlreadyExists() throws Exception {
AopNamespaceUtils.registerAspectJAutoProxyCreatorIfNecessary(this.parserContext, null); AopNamespaceUtils.registerAspectJAutoProxyCreatorIfNecessary(this.parserContext, null);
assertEquals(1, registry.getBeanDefinitionCount()); assertThat(registry.getBeanDefinitionCount()).isEqualTo(1);
AopNamespaceUtils.registerAutoProxyCreatorIfNecessary(this.parserContext, null); AopNamespaceUtils.registerAutoProxyCreatorIfNecessary(this.parserContext, null);
assertEquals("Incorrect definition count", 1, registry.getBeanDefinitionCount()); assertThat(registry.getBeanDefinitionCount()).as("Incorrect definition count").isEqualTo(1);
BeanDefinition definition = registry.getBeanDefinition(AopConfigUtils.AUTO_PROXY_CREATOR_BEAN_NAME); BeanDefinition definition = registry.getBeanDefinition(AopConfigUtils.AUTO_PROXY_CREATOR_BEAN_NAME);
assertEquals("Incorrect APC class", assertThat(definition.getBeanClassName()).as("Incorrect APC class").isEqualTo(AspectJAwareAdvisorAutoProxyCreator.class.getName());
AspectJAwareAdvisorAutoProxyCreator.class.getName(), definition.getBeanClassName());
} }
} }

View File

@ -35,7 +35,7 @@ import org.springframework.aop.aspectj.AspectJPointcutAdvisor;
import org.springframework.aop.support.DefaultPointcutAdvisor; import org.springframework.aop.support.DefaultPointcutAdvisor;
import org.springframework.lang.Nullable; import org.springframework.lang.Nullable;
import static org.junit.Assert.assertEquals; import static org.assertj.core.api.Assertions.assertThat;
/** /**
* @author Adrian Colyer * @author Adrian Colyer
@ -69,95 +69,95 @@ public class AspectJPrecedenceComparatorTests {
public void testSameAspectNoAfterAdvice() { public void testSameAspectNoAfterAdvice() {
Advisor advisor1 = createAspectJBeforeAdvice(HIGH_PRECEDENCE_ADVISOR_ORDER, EARLY_ADVICE_DECLARATION_ORDER, "someAspect"); Advisor advisor1 = createAspectJBeforeAdvice(HIGH_PRECEDENCE_ADVISOR_ORDER, EARLY_ADVICE_DECLARATION_ORDER, "someAspect");
Advisor advisor2 = createAspectJBeforeAdvice(HIGH_PRECEDENCE_ADVISOR_ORDER, LATE_ADVICE_DECLARATION_ORDER, "someAspect"); Advisor advisor2 = createAspectJBeforeAdvice(HIGH_PRECEDENCE_ADVISOR_ORDER, LATE_ADVICE_DECLARATION_ORDER, "someAspect");
assertEquals("advisor1 sorted before advisor2", -1, this.comparator.compare(advisor1, advisor2)); assertThat(this.comparator.compare(advisor1, advisor2)).as("advisor1 sorted before advisor2").isEqualTo(-1);
advisor1 = createAspectJBeforeAdvice(HIGH_PRECEDENCE_ADVISOR_ORDER, LATE_ADVICE_DECLARATION_ORDER, "someAspect"); advisor1 = createAspectJBeforeAdvice(HIGH_PRECEDENCE_ADVISOR_ORDER, LATE_ADVICE_DECLARATION_ORDER, "someAspect");
advisor2 = createAspectJAroundAdvice(HIGH_PRECEDENCE_ADVISOR_ORDER, EARLY_ADVICE_DECLARATION_ORDER, "someAspect"); advisor2 = createAspectJAroundAdvice(HIGH_PRECEDENCE_ADVISOR_ORDER, EARLY_ADVICE_DECLARATION_ORDER, "someAspect");
assertEquals("advisor2 sorted before advisor1", 1, this.comparator.compare(advisor1, advisor2)); assertThat(this.comparator.compare(advisor1, advisor2)).as("advisor2 sorted before advisor1").isEqualTo(1);
} }
@Test @Test
public void testSameAspectAfterAdvice() { public void testSameAspectAfterAdvice() {
Advisor advisor1 = createAspectJAfterAdvice(HIGH_PRECEDENCE_ADVISOR_ORDER, EARLY_ADVICE_DECLARATION_ORDER, "someAspect"); Advisor advisor1 = createAspectJAfterAdvice(HIGH_PRECEDENCE_ADVISOR_ORDER, EARLY_ADVICE_DECLARATION_ORDER, "someAspect");
Advisor advisor2 = createAspectJAroundAdvice(HIGH_PRECEDENCE_ADVISOR_ORDER, LATE_ADVICE_DECLARATION_ORDER, "someAspect"); Advisor advisor2 = createAspectJAroundAdvice(HIGH_PRECEDENCE_ADVISOR_ORDER, LATE_ADVICE_DECLARATION_ORDER, "someAspect");
assertEquals("advisor2 sorted before advisor1", 1, this.comparator.compare(advisor1, advisor2)); assertThat(this.comparator.compare(advisor1, advisor2)).as("advisor2 sorted before advisor1").isEqualTo(1);
advisor1 = createAspectJAfterReturningAdvice(HIGH_PRECEDENCE_ADVISOR_ORDER, LATE_ADVICE_DECLARATION_ORDER, "someAspect"); advisor1 = createAspectJAfterReturningAdvice(HIGH_PRECEDENCE_ADVISOR_ORDER, LATE_ADVICE_DECLARATION_ORDER, "someAspect");
advisor2 = createAspectJAfterThrowingAdvice(HIGH_PRECEDENCE_ADVISOR_ORDER, EARLY_ADVICE_DECLARATION_ORDER, "someAspect"); advisor2 = createAspectJAfterThrowingAdvice(HIGH_PRECEDENCE_ADVISOR_ORDER, EARLY_ADVICE_DECLARATION_ORDER, "someAspect");
assertEquals("advisor1 sorted before advisor2", -1, this.comparator.compare(advisor1, advisor2)); assertThat(this.comparator.compare(advisor1, advisor2)).as("advisor1 sorted before advisor2").isEqualTo(-1);
} }
@Test @Test
public void testSameAspectOneOfEach() { public void testSameAspectOneOfEach() {
Advisor advisor1 = createAspectJAfterAdvice(HIGH_PRECEDENCE_ADVISOR_ORDER, EARLY_ADVICE_DECLARATION_ORDER, "someAspect"); Advisor advisor1 = createAspectJAfterAdvice(HIGH_PRECEDENCE_ADVISOR_ORDER, EARLY_ADVICE_DECLARATION_ORDER, "someAspect");
Advisor advisor2 = createAspectJBeforeAdvice(HIGH_PRECEDENCE_ADVISOR_ORDER, LATE_ADVICE_DECLARATION_ORDER, "someAspect"); Advisor advisor2 = createAspectJBeforeAdvice(HIGH_PRECEDENCE_ADVISOR_ORDER, LATE_ADVICE_DECLARATION_ORDER, "someAspect");
assertEquals("advisor1 and advisor2 not comparable", 1, this.comparator.compare(advisor1, advisor2)); assertThat(this.comparator.compare(advisor1, advisor2)).as("advisor1 and advisor2 not comparable").isEqualTo(1);
} }
@Test @Test
public void testSameAdvisorPrecedenceDifferentAspectNoAfterAdvice() { public void testSameAdvisorPrecedenceDifferentAspectNoAfterAdvice() {
Advisor advisor1 = createAspectJBeforeAdvice(HIGH_PRECEDENCE_ADVISOR_ORDER, EARLY_ADVICE_DECLARATION_ORDER, "someAspect"); Advisor advisor1 = createAspectJBeforeAdvice(HIGH_PRECEDENCE_ADVISOR_ORDER, EARLY_ADVICE_DECLARATION_ORDER, "someAspect");
Advisor advisor2 = createAspectJBeforeAdvice(HIGH_PRECEDENCE_ADVISOR_ORDER, LATE_ADVICE_DECLARATION_ORDER, "someOtherAspect"); Advisor advisor2 = createAspectJBeforeAdvice(HIGH_PRECEDENCE_ADVISOR_ORDER, LATE_ADVICE_DECLARATION_ORDER, "someOtherAspect");
assertEquals("nothing to say about order here", 0, this.comparator.compare(advisor1, advisor2)); assertThat(this.comparator.compare(advisor1, advisor2)).as("nothing to say about order here").isEqualTo(0);
advisor1 = createAspectJBeforeAdvice(HIGH_PRECEDENCE_ADVISOR_ORDER, LATE_ADVICE_DECLARATION_ORDER, "someAspect"); advisor1 = createAspectJBeforeAdvice(HIGH_PRECEDENCE_ADVISOR_ORDER, LATE_ADVICE_DECLARATION_ORDER, "someAspect");
advisor2 = createAspectJAroundAdvice(HIGH_PRECEDENCE_ADVISOR_ORDER, EARLY_ADVICE_DECLARATION_ORDER, "someOtherAspect"); advisor2 = createAspectJAroundAdvice(HIGH_PRECEDENCE_ADVISOR_ORDER, EARLY_ADVICE_DECLARATION_ORDER, "someOtherAspect");
assertEquals("nothing to say about order here", 0, this.comparator.compare(advisor1, advisor2)); assertThat(this.comparator.compare(advisor1, advisor2)).as("nothing to say about order here").isEqualTo(0);
} }
@Test @Test
public void testSameAdvisorPrecedenceDifferentAspectAfterAdvice() { public void testSameAdvisorPrecedenceDifferentAspectAfterAdvice() {
Advisor advisor1 = createAspectJAfterAdvice(HIGH_PRECEDENCE_ADVISOR_ORDER, EARLY_ADVICE_DECLARATION_ORDER, "someAspect"); Advisor advisor1 = createAspectJAfterAdvice(HIGH_PRECEDENCE_ADVISOR_ORDER, EARLY_ADVICE_DECLARATION_ORDER, "someAspect");
Advisor advisor2 = createAspectJAroundAdvice(HIGH_PRECEDENCE_ADVISOR_ORDER, LATE_ADVICE_DECLARATION_ORDER, "someOtherAspect"); Advisor advisor2 = createAspectJAroundAdvice(HIGH_PRECEDENCE_ADVISOR_ORDER, LATE_ADVICE_DECLARATION_ORDER, "someOtherAspect");
assertEquals("nothing to say about order here", 0, this.comparator.compare(advisor1, advisor2)); assertThat(this.comparator.compare(advisor1, advisor2)).as("nothing to say about order here").isEqualTo(0);
advisor1 = createAspectJAfterReturningAdvice(HIGH_PRECEDENCE_ADVISOR_ORDER, LATE_ADVICE_DECLARATION_ORDER, "someAspect"); advisor1 = createAspectJAfterReturningAdvice(HIGH_PRECEDENCE_ADVISOR_ORDER, LATE_ADVICE_DECLARATION_ORDER, "someAspect");
advisor2 = createAspectJAfterThrowingAdvice(HIGH_PRECEDENCE_ADVISOR_ORDER, EARLY_ADVICE_DECLARATION_ORDER, "someOtherAspect"); advisor2 = createAspectJAfterThrowingAdvice(HIGH_PRECEDENCE_ADVISOR_ORDER, EARLY_ADVICE_DECLARATION_ORDER, "someOtherAspect");
assertEquals("nothing to say about order here", 0, this.comparator.compare(advisor1, advisor2)); assertThat(this.comparator.compare(advisor1, advisor2)).as("nothing to say about order here").isEqualTo(0);
} }
@Test @Test
public void testHigherAdvisorPrecedenceNoAfterAdvice() { public void testHigherAdvisorPrecedenceNoAfterAdvice() {
Advisor advisor1 = createSpringAOPBeforeAdvice(HIGH_PRECEDENCE_ADVISOR_ORDER); Advisor advisor1 = createSpringAOPBeforeAdvice(HIGH_PRECEDENCE_ADVISOR_ORDER);
Advisor advisor2 = createAspectJBeforeAdvice(LOW_PRECEDENCE_ADVISOR_ORDER, EARLY_ADVICE_DECLARATION_ORDER, "someOtherAspect"); Advisor advisor2 = createAspectJBeforeAdvice(LOW_PRECEDENCE_ADVISOR_ORDER, EARLY_ADVICE_DECLARATION_ORDER, "someOtherAspect");
assertEquals("advisor1 sorted before advisor2", -1, this.comparator.compare(advisor1, advisor2)); assertThat(this.comparator.compare(advisor1, advisor2)).as("advisor1 sorted before advisor2").isEqualTo(-1);
advisor1 = createAspectJBeforeAdvice(HIGH_PRECEDENCE_ADVISOR_ORDER, LATE_ADVICE_DECLARATION_ORDER, "someAspect"); advisor1 = createAspectJBeforeAdvice(HIGH_PRECEDENCE_ADVISOR_ORDER, LATE_ADVICE_DECLARATION_ORDER, "someAspect");
advisor2 = createAspectJAroundAdvice(LOW_PRECEDENCE_ADVISOR_ORDER, EARLY_ADVICE_DECLARATION_ORDER, "someOtherAspect"); advisor2 = createAspectJAroundAdvice(LOW_PRECEDENCE_ADVISOR_ORDER, EARLY_ADVICE_DECLARATION_ORDER, "someOtherAspect");
assertEquals("advisor1 sorted before advisor2", -1, this.comparator.compare(advisor1, advisor2)); assertThat(this.comparator.compare(advisor1, advisor2)).as("advisor1 sorted before advisor2").isEqualTo(-1);
} }
@Test @Test
public void testHigherAdvisorPrecedenceAfterAdvice() { public void testHigherAdvisorPrecedenceAfterAdvice() {
Advisor advisor1 = createAspectJAfterAdvice(HIGH_PRECEDENCE_ADVISOR_ORDER, EARLY_ADVICE_DECLARATION_ORDER, "someAspect"); Advisor advisor1 = createAspectJAfterAdvice(HIGH_PRECEDENCE_ADVISOR_ORDER, EARLY_ADVICE_DECLARATION_ORDER, "someAspect");
Advisor advisor2 = createAspectJAroundAdvice(LOW_PRECEDENCE_ADVISOR_ORDER, LATE_ADVICE_DECLARATION_ORDER, "someOtherAspect"); Advisor advisor2 = createAspectJAroundAdvice(LOW_PRECEDENCE_ADVISOR_ORDER, LATE_ADVICE_DECLARATION_ORDER, "someOtherAspect");
assertEquals("advisor1 sorted before advisor2", -1, this.comparator.compare(advisor1, advisor2)); assertThat(this.comparator.compare(advisor1, advisor2)).as("advisor1 sorted before advisor2").isEqualTo(-1);
advisor1 = createAspectJAfterReturningAdvice(HIGH_PRECEDENCE_ADVISOR_ORDER, LATE_ADVICE_DECLARATION_ORDER, "someAspect"); advisor1 = createAspectJAfterReturningAdvice(HIGH_PRECEDENCE_ADVISOR_ORDER, LATE_ADVICE_DECLARATION_ORDER, "someAspect");
advisor2 = createAspectJAfterThrowingAdvice(LOW_PRECEDENCE_ADVISOR_ORDER, EARLY_ADVICE_DECLARATION_ORDER, "someOtherAspect"); advisor2 = createAspectJAfterThrowingAdvice(LOW_PRECEDENCE_ADVISOR_ORDER, EARLY_ADVICE_DECLARATION_ORDER, "someOtherAspect");
assertEquals("advisor2 sorted after advisor1", -1, this.comparator.compare(advisor1, advisor2)); assertThat(this.comparator.compare(advisor1, advisor2)).as("advisor2 sorted after advisor1").isEqualTo(-1);
} }
@Test @Test
public void testLowerAdvisorPrecedenceNoAfterAdvice() { public void testLowerAdvisorPrecedenceNoAfterAdvice() {
Advisor advisor1 = createAspectJBeforeAdvice(LOW_PRECEDENCE_ADVISOR_ORDER, EARLY_ADVICE_DECLARATION_ORDER, "someAspect"); Advisor advisor1 = createAspectJBeforeAdvice(LOW_PRECEDENCE_ADVISOR_ORDER, EARLY_ADVICE_DECLARATION_ORDER, "someAspect");
Advisor advisor2 = createAspectJBeforeAdvice(HIGH_PRECEDENCE_ADVISOR_ORDER, EARLY_ADVICE_DECLARATION_ORDER, "someOtherAspect"); Advisor advisor2 = createAspectJBeforeAdvice(HIGH_PRECEDENCE_ADVISOR_ORDER, EARLY_ADVICE_DECLARATION_ORDER, "someOtherAspect");
assertEquals("advisor1 sorted after advisor2", 1, this.comparator.compare(advisor1, advisor2)); assertThat(this.comparator.compare(advisor1, advisor2)).as("advisor1 sorted after advisor2").isEqualTo(1);
advisor1 = createAspectJBeforeAdvice(LOW_PRECEDENCE_ADVISOR_ORDER, LATE_ADVICE_DECLARATION_ORDER, "someAspect"); advisor1 = createAspectJBeforeAdvice(LOW_PRECEDENCE_ADVISOR_ORDER, LATE_ADVICE_DECLARATION_ORDER, "someAspect");
advisor2 = createAspectJAroundAdvice(HIGH_PRECEDENCE_ADVISOR_ORDER, EARLY_ADVICE_DECLARATION_ORDER, "someOtherAspect"); advisor2 = createAspectJAroundAdvice(HIGH_PRECEDENCE_ADVISOR_ORDER, EARLY_ADVICE_DECLARATION_ORDER, "someOtherAspect");
assertEquals("advisor1 sorted after advisor2", 1, this.comparator.compare(advisor1, advisor2)); assertThat(this.comparator.compare(advisor1, advisor2)).as("advisor1 sorted after advisor2").isEqualTo(1);
} }
@Test @Test
public void testLowerAdvisorPrecedenceAfterAdvice() { public void testLowerAdvisorPrecedenceAfterAdvice() {
Advisor advisor1 = createAspectJAfterAdvice(LOW_PRECEDENCE_ADVISOR_ORDER, EARLY_ADVICE_DECLARATION_ORDER, "someAspect"); Advisor advisor1 = createAspectJAfterAdvice(LOW_PRECEDENCE_ADVISOR_ORDER, EARLY_ADVICE_DECLARATION_ORDER, "someAspect");
Advisor advisor2 = createAspectJAroundAdvice(HIGH_PRECEDENCE_ADVISOR_ORDER, LATE_ADVICE_DECLARATION_ORDER, "someOtherAspect"); Advisor advisor2 = createAspectJAroundAdvice(HIGH_PRECEDENCE_ADVISOR_ORDER, LATE_ADVICE_DECLARATION_ORDER, "someOtherAspect");
assertEquals("advisor1 sorted after advisor2", 1, this.comparator.compare(advisor1, advisor2)); assertThat(this.comparator.compare(advisor1, advisor2)).as("advisor1 sorted after advisor2").isEqualTo(1);
advisor1 = createSpringAOPAfterAdvice(LOW_PRECEDENCE_ADVISOR_ORDER); advisor1 = createSpringAOPAfterAdvice(LOW_PRECEDENCE_ADVISOR_ORDER);
advisor2 = createAspectJAfterThrowingAdvice(HIGH_PRECEDENCE_ADVISOR_ORDER, EARLY_ADVICE_DECLARATION_ORDER, "someOtherAspect"); advisor2 = createAspectJAfterThrowingAdvice(HIGH_PRECEDENCE_ADVISOR_ORDER, EARLY_ADVICE_DECLARATION_ORDER, "someOtherAspect");
assertEquals("advisor1 sorted after advisor2", 1, this.comparator.compare(advisor1, advisor2)); assertThat(this.comparator.compare(advisor1, advisor2)).as("advisor1 sorted after advisor2").isEqualTo(1);
} }

View File

@ -32,9 +32,7 @@ import org.springframework.beans.factory.xml.XmlBeanDefinitionReader;
import org.springframework.core.io.Resource; import org.springframework.core.io.Resource;
import org.springframework.tests.beans.CollectingReaderEventListener; import org.springframework.tests.beans.CollectingReaderEventListener;
import static org.junit.Assert.assertEquals; import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.springframework.tests.TestResourceUtils.qualifiedResource; import static org.springframework.tests.TestResourceUtils.qualifiedResource;
/** /**
@ -69,14 +67,15 @@ public class AopNamespaceHandlerEventTests {
public void testPointcutEvents() { public void testPointcutEvents() {
this.reader.loadBeanDefinitions(POINTCUT_EVENTS_CONTEXT); this.reader.loadBeanDefinitions(POINTCUT_EVENTS_CONTEXT);
ComponentDefinition[] componentDefinitions = this.eventListener.getComponentDefinitions(); ComponentDefinition[] componentDefinitions = this.eventListener.getComponentDefinitions();
assertEquals("Incorrect number of events fired", 1, componentDefinitions.length); assertThat(componentDefinitions.length).as("Incorrect number of events fired").isEqualTo(1);
assertTrue("No holder with nested components", componentDefinitions[0] instanceof CompositeComponentDefinition); boolean condition = componentDefinitions[0] instanceof CompositeComponentDefinition;
assertThat(condition).as("No holder with nested components").isTrue();
CompositeComponentDefinition compositeDef = (CompositeComponentDefinition) componentDefinitions[0]; CompositeComponentDefinition compositeDef = (CompositeComponentDefinition) componentDefinitions[0];
assertEquals("aop:config", compositeDef.getName()); assertThat(compositeDef.getName()).isEqualTo("aop:config");
ComponentDefinition[] nestedComponentDefs = compositeDef.getNestedComponents(); ComponentDefinition[] nestedComponentDefs = compositeDef.getNestedComponents();
assertEquals("Incorrect number of inner components", 2, nestedComponentDefs.length); assertThat(nestedComponentDefs.length).as("Incorrect number of inner components").isEqualTo(2);
PointcutComponentDefinition pcd = null; PointcutComponentDefinition pcd = null;
for (ComponentDefinition componentDefinition : nestedComponentDefs) { for (ComponentDefinition componentDefinition : nestedComponentDefs) {
if (componentDefinition instanceof PointcutComponentDefinition) { if (componentDefinition instanceof PointcutComponentDefinition) {
@ -84,22 +83,23 @@ public class AopNamespaceHandlerEventTests {
break; break;
} }
} }
assertNotNull("PointcutComponentDefinition not found", pcd); assertThat(pcd).as("PointcutComponentDefinition not found").isNotNull();
assertEquals("Incorrect number of BeanDefinitions", 1, pcd.getBeanDefinitions().length); assertThat(pcd.getBeanDefinitions().length).as("Incorrect number of BeanDefinitions").isEqualTo(1);
} }
@Test @Test
public void testAdvisorEventsWithPointcutRef() { public void testAdvisorEventsWithPointcutRef() {
this.reader.loadBeanDefinitions(POINTCUT_REF_CONTEXT); this.reader.loadBeanDefinitions(POINTCUT_REF_CONTEXT);
ComponentDefinition[] componentDefinitions = this.eventListener.getComponentDefinitions(); ComponentDefinition[] componentDefinitions = this.eventListener.getComponentDefinitions();
assertEquals("Incorrect number of events fired", 2, componentDefinitions.length); assertThat(componentDefinitions.length).as("Incorrect number of events fired").isEqualTo(2);
assertTrue("No holder with nested components", componentDefinitions[0] instanceof CompositeComponentDefinition); boolean condition1 = componentDefinitions[0] instanceof CompositeComponentDefinition;
assertThat(condition1).as("No holder with nested components").isTrue();
CompositeComponentDefinition compositeDef = (CompositeComponentDefinition) componentDefinitions[0]; CompositeComponentDefinition compositeDef = (CompositeComponentDefinition) componentDefinitions[0];
assertEquals("aop:config", compositeDef.getName()); assertThat(compositeDef.getName()).isEqualTo("aop:config");
ComponentDefinition[] nestedComponentDefs = compositeDef.getNestedComponents(); ComponentDefinition[] nestedComponentDefs = compositeDef.getNestedComponents();
assertEquals("Incorrect number of inner components", 3, nestedComponentDefs.length); assertThat(nestedComponentDefs.length).as("Incorrect number of inner components").isEqualTo(3);
AdvisorComponentDefinition acd = null; AdvisorComponentDefinition acd = null;
for (int i = 0; i < nestedComponentDefs.length; i++) { for (int i = 0; i < nestedComponentDefs.length; i++) {
ComponentDefinition componentDefinition = nestedComponentDefs[i]; ComponentDefinition componentDefinition = nestedComponentDefs[i];
@ -108,27 +108,29 @@ public class AopNamespaceHandlerEventTests {
break; break;
} }
} }
assertNotNull("AdvisorComponentDefinition not found", acd); assertThat(acd).as("AdvisorComponentDefinition not found").isNotNull();
assertEquals(1, acd.getBeanDefinitions().length); assertThat(acd.getBeanDefinitions().length).isEqualTo(1);
assertEquals(2, acd.getBeanReferences().length); assertThat(acd.getBeanReferences().length).isEqualTo(2);
assertTrue("No advice bean found", componentDefinitions[1] instanceof BeanComponentDefinition); boolean condition = componentDefinitions[1] instanceof BeanComponentDefinition;
assertThat(condition).as("No advice bean found").isTrue();
BeanComponentDefinition adviceDef = (BeanComponentDefinition) componentDefinitions[1]; BeanComponentDefinition adviceDef = (BeanComponentDefinition) componentDefinitions[1];
assertEquals("countingAdvice", adviceDef.getBeanName()); assertThat(adviceDef.getBeanName()).isEqualTo("countingAdvice");
} }
@Test @Test
public void testAdvisorEventsWithDirectPointcut() { public void testAdvisorEventsWithDirectPointcut() {
this.reader.loadBeanDefinitions(DIRECT_POINTCUT_EVENTS_CONTEXT); this.reader.loadBeanDefinitions(DIRECT_POINTCUT_EVENTS_CONTEXT);
ComponentDefinition[] componentDefinitions = this.eventListener.getComponentDefinitions(); ComponentDefinition[] componentDefinitions = this.eventListener.getComponentDefinitions();
assertEquals("Incorrect number of events fired", 2, componentDefinitions.length); assertThat(componentDefinitions.length).as("Incorrect number of events fired").isEqualTo(2);
assertTrue("No holder with nested components", componentDefinitions[0] instanceof CompositeComponentDefinition); boolean condition1 = componentDefinitions[0] instanceof CompositeComponentDefinition;
assertThat(condition1).as("No holder with nested components").isTrue();
CompositeComponentDefinition compositeDef = (CompositeComponentDefinition) componentDefinitions[0]; CompositeComponentDefinition compositeDef = (CompositeComponentDefinition) componentDefinitions[0];
assertEquals("aop:config", compositeDef.getName()); assertThat(compositeDef.getName()).isEqualTo("aop:config");
ComponentDefinition[] nestedComponentDefs = compositeDef.getNestedComponents(); ComponentDefinition[] nestedComponentDefs = compositeDef.getNestedComponents();
assertEquals("Incorrect number of inner components", 2, nestedComponentDefs.length); assertThat(nestedComponentDefs.length).as("Incorrect number of inner components").isEqualTo(2);
AdvisorComponentDefinition acd = null; AdvisorComponentDefinition acd = null;
for (int i = 0; i < nestedComponentDefs.length; i++) { for (int i = 0; i < nestedComponentDefs.length; i++) {
ComponentDefinition componentDefinition = nestedComponentDefs[i]; ComponentDefinition componentDefinition = nestedComponentDefs[i];
@ -137,27 +139,29 @@ public class AopNamespaceHandlerEventTests {
break; break;
} }
} }
assertNotNull("AdvisorComponentDefinition not found", acd); assertThat(acd).as("AdvisorComponentDefinition not found").isNotNull();
assertEquals(2, acd.getBeanDefinitions().length); assertThat(acd.getBeanDefinitions().length).isEqualTo(2);
assertEquals(1, acd.getBeanReferences().length); assertThat(acd.getBeanReferences().length).isEqualTo(1);
assertTrue("No advice bean found", componentDefinitions[1] instanceof BeanComponentDefinition); boolean condition = componentDefinitions[1] instanceof BeanComponentDefinition;
assertThat(condition).as("No advice bean found").isTrue();
BeanComponentDefinition adviceDef = (BeanComponentDefinition) componentDefinitions[1]; BeanComponentDefinition adviceDef = (BeanComponentDefinition) componentDefinitions[1];
assertEquals("countingAdvice", adviceDef.getBeanName()); assertThat(adviceDef.getBeanName()).isEqualTo("countingAdvice");
} }
@Test @Test
public void testAspectEvent() { public void testAspectEvent() {
this.reader.loadBeanDefinitions(CONTEXT); this.reader.loadBeanDefinitions(CONTEXT);
ComponentDefinition[] componentDefinitions = this.eventListener.getComponentDefinitions(); ComponentDefinition[] componentDefinitions = this.eventListener.getComponentDefinitions();
assertEquals("Incorrect number of events fired", 5, componentDefinitions.length); assertThat(componentDefinitions.length).as("Incorrect number of events fired").isEqualTo(5);
assertTrue("No holder with nested components", componentDefinitions[0] instanceof CompositeComponentDefinition); boolean condition = componentDefinitions[0] instanceof CompositeComponentDefinition;
assertThat(condition).as("No holder with nested components").isTrue();
CompositeComponentDefinition compositeDef = (CompositeComponentDefinition) componentDefinitions[0]; CompositeComponentDefinition compositeDef = (CompositeComponentDefinition) componentDefinitions[0];
assertEquals("aop:config", compositeDef.getName()); assertThat(compositeDef.getName()).isEqualTo("aop:config");
ComponentDefinition[] nestedComponentDefs = compositeDef.getNestedComponents(); ComponentDefinition[] nestedComponentDefs = compositeDef.getNestedComponents();
assertEquals("Incorrect number of inner components", 2, nestedComponentDefs.length); assertThat(nestedComponentDefs.length).as("Incorrect number of inner components").isEqualTo(2);
AspectComponentDefinition acd = null; AspectComponentDefinition acd = null;
for (ComponentDefinition componentDefinition : nestedComponentDefs) { for (ComponentDefinition componentDefinition : nestedComponentDefs) {
if (componentDefinition instanceof AspectComponentDefinition) { if (componentDefinition instanceof AspectComponentDefinition) {
@ -166,11 +170,11 @@ public class AopNamespaceHandlerEventTests {
} }
} }
assertNotNull("AspectComponentDefinition not found", acd); assertThat(acd).as("AspectComponentDefinition not found").isNotNull();
BeanDefinition[] beanDefinitions = acd.getBeanDefinitions(); BeanDefinition[] beanDefinitions = acd.getBeanDefinitions();
assertEquals(5, beanDefinitions.length); assertThat(beanDefinitions.length).isEqualTo(5);
BeanReference[] beanReferences = acd.getBeanReferences(); BeanReference[] beanReferences = acd.getBeanReferences();
assertEquals(6, beanReferences.length); assertThat(beanReferences.length).isEqualTo(6);
Set<String> expectedReferences = new HashSet<>(); Set<String> expectedReferences = new HashSet<>();
expectedReferences.add("pc"); expectedReferences.add("pc");
@ -178,17 +182,19 @@ public class AopNamespaceHandlerEventTests {
for (BeanReference beanReference : beanReferences) { for (BeanReference beanReference : beanReferences) {
expectedReferences.remove(beanReference.getBeanName()); expectedReferences.remove(beanReference.getBeanName());
} }
assertEquals("Incorrect references found", 0, expectedReferences.size()); assertThat(expectedReferences.size()).as("Incorrect references found").isEqualTo(0);
for (int i = 1; i < componentDefinitions.length; i++) { for (int i = 1; i < componentDefinitions.length; i++) {
assertTrue(componentDefinitions[i] instanceof BeanComponentDefinition); boolean condition1 = componentDefinitions[i] instanceof BeanComponentDefinition;
assertThat(condition1).isTrue();
} }
ComponentDefinition[] nestedComponentDefs2 = acd.getNestedComponents(); ComponentDefinition[] nestedComponentDefs2 = acd.getNestedComponents();
assertEquals("Inner PointcutComponentDefinition not found", 1, nestedComponentDefs2.length); assertThat(nestedComponentDefs2.length).as("Inner PointcutComponentDefinition not found").isEqualTo(1);
assertTrue(nestedComponentDefs2[0] instanceof PointcutComponentDefinition); boolean condition1 = nestedComponentDefs2[0] instanceof PointcutComponentDefinition;
assertThat(condition1).isTrue();
PointcutComponentDefinition pcd = (PointcutComponentDefinition) nestedComponentDefs2[0]; PointcutComponentDefinition pcd = (PointcutComponentDefinition) nestedComponentDefs2[0];
assertEquals("Incorrect number of BeanDefinitions", 1, pcd.getBeanDefinitions().length); assertThat(pcd.getBeanDefinitions().length).as("Incorrect number of BeanDefinitions").isEqualTo(1);
} }
} }

View File

@ -21,7 +21,7 @@ import org.junit.Test;
import org.springframework.beans.factory.support.DefaultListableBeanFactory; import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.beans.factory.xml.XmlBeanDefinitionReader; import org.springframework.beans.factory.xml.XmlBeanDefinitionReader;
import static org.junit.Assert.assertTrue; import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.tests.TestResourceUtils.qualifiedResource; import static org.springframework.tests.TestResourceUtils.qualifiedResource;
/** /**
@ -38,7 +38,7 @@ public class TopLevelAopTagTests {
new XmlBeanDefinitionReader(beanFactory).loadBeanDefinitions( new XmlBeanDefinitionReader(beanFactory).loadBeanDefinitions(
qualifiedResource(TopLevelAopTagTests.class, "context.xml")); qualifiedResource(TopLevelAopTagTests.class, "context.xml"));
assertTrue(beanFactory.containsBeanDefinition("testPointcut")); assertThat(beanFactory.containsBeanDefinition("testPointcut")).isTrue();
} }
} }

View File

@ -26,10 +26,8 @@ import org.springframework.aop.SpringProxy;
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.assertThatIllegalArgumentException; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
/** /**
* @author Rod Johnson * @author Rod Johnson
@ -41,10 +39,10 @@ public class AopProxyUtilsTests {
public void testCompleteProxiedInterfacesWorksWithNull() { public void testCompleteProxiedInterfacesWorksWithNull() {
AdvisedSupport as = new AdvisedSupport(); AdvisedSupport as = new AdvisedSupport();
Class<?>[] completedInterfaces = AopProxyUtils.completeProxiedInterfaces(as); Class<?>[] completedInterfaces = AopProxyUtils.completeProxiedInterfaces(as);
assertEquals(2, completedInterfaces.length); assertThat(completedInterfaces.length).isEqualTo(2);
List<?> ifaces = Arrays.asList(completedInterfaces); List<?> ifaces = Arrays.asList(completedInterfaces);
assertTrue(ifaces.contains(Advised.class)); assertThat(ifaces.contains(Advised.class)).isTrue();
assertTrue(ifaces.contains(SpringProxy.class)); assertThat(ifaces.contains(SpringProxy.class)).isTrue();
} }
@Test @Test
@ -52,7 +50,7 @@ public class AopProxyUtilsTests {
AdvisedSupport as = new AdvisedSupport(); AdvisedSupport as = new AdvisedSupport();
as.setOpaque(true); as.setOpaque(true);
Class<?>[] completedInterfaces = AopProxyUtils.completeProxiedInterfaces(as); Class<?>[] completedInterfaces = AopProxyUtils.completeProxiedInterfaces(as);
assertEquals(1, completedInterfaces.length); assertThat(completedInterfaces.length).isEqualTo(1);
} }
@Test @Test
@ -61,13 +59,13 @@ public class AopProxyUtilsTests {
as.addInterface(ITestBean.class); as.addInterface(ITestBean.class);
as.addInterface(Comparable.class); as.addInterface(Comparable.class);
Class<?>[] completedInterfaces = AopProxyUtils.completeProxiedInterfaces(as); Class<?>[] completedInterfaces = AopProxyUtils.completeProxiedInterfaces(as);
assertEquals(4, completedInterfaces.length); assertThat(completedInterfaces.length).isEqualTo(4);
// Can't assume ordering for others, so use a list // Can't assume ordering for others, so use a list
List<?> l = Arrays.asList(completedInterfaces); List<?> l = Arrays.asList(completedInterfaces);
assertTrue(l.contains(Advised.class)); assertThat(l.contains(Advised.class)).isTrue();
assertTrue(l.contains(ITestBean.class)); assertThat(l.contains(ITestBean.class)).isTrue();
assertTrue(l.contains(Comparable.class)); assertThat(l.contains(Comparable.class)).isTrue();
} }
@Test @Test
@ -77,13 +75,13 @@ public class AopProxyUtilsTests {
as.addInterface(Comparable.class); as.addInterface(Comparable.class);
as.addInterface(Advised.class); as.addInterface(Advised.class);
Class<?>[] completedInterfaces = AopProxyUtils.completeProxiedInterfaces(as); Class<?>[] completedInterfaces = AopProxyUtils.completeProxiedInterfaces(as);
assertEquals(4, completedInterfaces.length); assertThat(completedInterfaces.length).isEqualTo(4);
// Can't assume ordering for others, so use a list // Can't assume ordering for others, so use a list
List<?> l = Arrays.asList(completedInterfaces); List<?> l = Arrays.asList(completedInterfaces);
assertTrue(l.contains(Advised.class)); assertThat(l.contains(Advised.class)).isTrue();
assertTrue(l.contains(ITestBean.class)); assertThat(l.contains(ITestBean.class)).isTrue();
assertTrue(l.contains(Comparable.class)); assertThat(l.contains(Comparable.class)).isTrue();
} }
@Test @Test
@ -93,13 +91,13 @@ public class AopProxyUtilsTests {
as.addInterface(ITestBean.class); as.addInterface(ITestBean.class);
as.addInterface(Comparable.class); as.addInterface(Comparable.class);
Class<?>[] completedInterfaces = AopProxyUtils.completeProxiedInterfaces(as); Class<?>[] completedInterfaces = AopProxyUtils.completeProxiedInterfaces(as);
assertEquals(3, completedInterfaces.length); assertThat(completedInterfaces.length).isEqualTo(3);
// Can't assume ordering for others, so use a list // Can't assume ordering for others, so use a list
List<?> l = Arrays.asList(completedInterfaces); List<?> l = Arrays.asList(completedInterfaces);
assertFalse(l.contains(Advised.class)); assertThat(l.contains(Advised.class)).isFalse();
assertTrue(l.contains(ITestBean.class)); assertThat(l.contains(ITestBean.class)).isTrue();
assertTrue(l.contains(Comparable.class)); assertThat(l.contains(Comparable.class)).isTrue();
} }
@Test @Test
@ -109,8 +107,8 @@ public class AopProxyUtilsTests {
pf.addInterface(ITestBean.class); pf.addInterface(ITestBean.class);
Object proxy = pf.getProxy(); Object proxy = pf.getProxy();
Class<?>[] userInterfaces = AopProxyUtils.proxiedUserInterfaces(proxy); Class<?>[] userInterfaces = AopProxyUtils.proxiedUserInterfaces(proxy);
assertEquals(1, userInterfaces.length); assertThat(userInterfaces.length).isEqualTo(1);
assertEquals(ITestBean.class, userInterfaces[0]); assertThat(userInterfaces[0]).isEqualTo(ITestBean.class);
} }
@Test @Test
@ -121,9 +119,9 @@ public class AopProxyUtilsTests {
pf.addInterface(Comparable.class); pf.addInterface(Comparable.class);
Object proxy = pf.getProxy(); Object proxy = pf.getProxy();
Class<?>[] userInterfaces = AopProxyUtils.proxiedUserInterfaces(proxy); Class<?>[] userInterfaces = AopProxyUtils.proxiedUserInterfaces(proxy);
assertEquals(2, userInterfaces.length); assertThat(userInterfaces.length).isEqualTo(2);
assertEquals(ITestBean.class, userInterfaces[0]); assertThat(userInterfaces[0]).isEqualTo(ITestBean.class);
assertEquals(Comparable.class, userInterfaces[1]); assertThat(userInterfaces[1]).isEqualTo(Comparable.class);
} }
@Test @Test

View File

@ -26,7 +26,7 @@ import org.junit.Test;
import org.springframework.tests.sample.beans.TestBean; import org.springframework.tests.sample.beans.TestBean;
import static org.junit.Assert.assertTrue; import static org.assertj.core.api.Assertions.assertThat;
/** /**
* @author Rod Johnson * @author Rod Johnson
@ -51,7 +51,7 @@ public class MethodInvocationTests {
m, null, null, is // list m, null, null, is // list
); );
Object rv = invocation.proceed(); Object rv = invocation.proceed();
assertTrue("correct response", rv == returnValue); assertThat(rv == returnValue).as("correct response").isTrue();
} }
/** /**

View File

@ -24,7 +24,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.Resource; import org.springframework.core.io.Resource;
import static org.junit.Assert.assertEquals; import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.tests.TestResourceUtils.qualifiedResource; import static org.springframework.tests.TestResourceUtils.qualifiedResource;
/** /**
@ -47,8 +47,8 @@ public class PrototypeTargetTests {
tb.doSomething(); tb.doSomething();
} }
TestInterceptor interceptor = (TestInterceptor) bf.getBean("testInterceptor"); TestInterceptor interceptor = (TestInterceptor) bf.getBean("testInterceptor");
assertEquals(10, TestBeanImpl.constructionCount); assertThat(TestBeanImpl.constructionCount).isEqualTo(10);
assertEquals(10, interceptor.invocationCount); assertThat(interceptor.invocationCount).isEqualTo(10);
} }
@Test @Test
@ -61,8 +61,8 @@ public class PrototypeTargetTests {
tb.doSomething(); tb.doSomething();
} }
TestInterceptor interceptor = (TestInterceptor) bf.getBean("testInterceptor"); TestInterceptor interceptor = (TestInterceptor) bf.getBean("testInterceptor");
assertEquals(1, TestBeanImpl.constructionCount); assertThat(TestBeanImpl.constructionCount).isEqualTo(1);
assertEquals(10, interceptor.invocationCount); assertThat(interceptor.invocationCount).isEqualTo(10);
} }

View File

@ -44,11 +44,6 @@ import org.springframework.tests.sample.beans.TestBean;
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.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
/** /**
* Also tests AdvisedSupport and ProxyCreatorSupport superclasses. * Also tests AdvisedSupport and ProxyCreatorSupport superclasses.
@ -70,10 +65,10 @@ public class ProxyFactoryTests {
// Can use advised and ProxyFactory interchangeably // Can use advised and ProxyFactory interchangeably
advised.addAdvice(nop); advised.addAdvice(nop);
pf.addAdvisor(advisor); pf.addAdvisor(advisor);
assertEquals(-1, pf.indexOf(new NopInterceptor())); assertThat(pf.indexOf(new NopInterceptor())).isEqualTo(-1);
assertEquals(0, pf.indexOf(nop)); assertThat(pf.indexOf(nop)).isEqualTo(0);
assertEquals(1, pf.indexOf(advisor)); assertThat(pf.indexOf(advisor)).isEqualTo(1);
assertEquals(-1, advised.indexOf(new DefaultPointcutAdvisor(null))); assertThat(advised.indexOf(new DefaultPointcutAdvisor(null))).isEqualTo(-1);
} }
@Test @Test
@ -87,13 +82,13 @@ public class ProxyFactoryTests {
pf.addAdvisor(advisor); pf.addAdvisor(advisor);
ITestBean proxied = (ITestBean) pf.getProxy(); ITestBean proxied = (ITestBean) pf.getProxy();
proxied.setAge(5); proxied.setAge(5);
assertEquals(1, cba.getCalls()); assertThat(cba.getCalls()).isEqualTo(1);
assertEquals(1, nop.getCount()); assertThat(nop.getCount()).isEqualTo(1);
assertTrue(pf.removeAdvisor(advisor)); assertThat(pf.removeAdvisor(advisor)).isTrue();
assertEquals(5, proxied.getAge()); assertThat(proxied.getAge()).isEqualTo(5);
assertEquals(1, cba.getCalls()); assertThat(cba.getCalls()).isEqualTo(1);
assertEquals(2, nop.getCount()); assertThat(nop.getCount()).isEqualTo(2);
assertFalse(pf.removeAdvisor(new DefaultPointcutAdvisor(null))); assertThat(pf.removeAdvisor(new DefaultPointcutAdvisor(null))).isFalse();
} }
@Test @Test
@ -109,21 +104,21 @@ public class ProxyFactoryTests {
pf.addAdvice(nop2); pf.addAdvice(nop2);
ITestBean proxied = (ITestBean) pf.getProxy(); ITestBean proxied = (ITestBean) pf.getProxy();
proxied.setAge(5); proxied.setAge(5);
assertEquals(1, cba.getCalls()); assertThat(cba.getCalls()).isEqualTo(1);
assertEquals(1, nop.getCount()); assertThat(nop.getCount()).isEqualTo(1);
assertEquals(1, nop2.getCount()); assertThat(nop2.getCount()).isEqualTo(1);
// Removes counting before advisor // Removes counting before advisor
pf.removeAdvisor(1); pf.removeAdvisor(1);
assertEquals(5, proxied.getAge()); assertThat(proxied.getAge()).isEqualTo(5);
assertEquals(1, cba.getCalls()); assertThat(cba.getCalls()).isEqualTo(1);
assertEquals(2, nop.getCount()); assertThat(nop.getCount()).isEqualTo(2);
assertEquals(2, nop2.getCount()); assertThat(nop2.getCount()).isEqualTo(2);
// Removes Nop1 // Removes Nop1
pf.removeAdvisor(0); pf.removeAdvisor(0);
assertEquals(5, proxied.getAge()); assertThat(proxied.getAge()).isEqualTo(5);
assertEquals(1, cba.getCalls()); assertThat(cba.getCalls()).isEqualTo(1);
assertEquals(2, nop.getCount()); assertThat(nop.getCount()).isEqualTo(2);
assertEquals(3, nop2.getCount()); assertThat(nop2.getCount()).isEqualTo(3);
// Check out of bounds // Check out of bounds
try { try {
@ -140,8 +135,8 @@ public class ProxyFactoryTests {
// Ok // Ok
} }
assertEquals(5, proxied.getAge()); assertThat(proxied.getAge()).isEqualTo(5);
assertEquals(4, nop2.getCount()); assertThat(nop2.getCount()).isEqualTo(4);
} }
@Test @Test
@ -160,17 +155,17 @@ public class ProxyFactoryTests {
// Replace etc methods on advised should be same as on ProxyFactory // Replace etc methods on advised should be same as on ProxyFactory
Advised advised = (Advised) proxied; Advised advised = (Advised) proxied;
proxied.setAge(5); proxied.setAge(5);
assertEquals(1, cba1.getCalls()); assertThat(cba1.getCalls()).isEqualTo(1);
assertEquals(0, cba2.getCalls()); assertThat(cba2.getCalls()).isEqualTo(0);
assertEquals(1, nop.getCount()); assertThat(nop.getCount()).isEqualTo(1);
assertFalse(advised.replaceAdvisor(new DefaultPointcutAdvisor(new NopInterceptor()), advisor2)); assertThat(advised.replaceAdvisor(new DefaultPointcutAdvisor(new NopInterceptor()), advisor2)).isFalse();
assertTrue(advised.replaceAdvisor(advisor1, advisor2)); assertThat(advised.replaceAdvisor(advisor1, advisor2)).isTrue();
assertEquals(advisor2, pf.getAdvisors()[0]); assertThat(pf.getAdvisors()[0]).isEqualTo(advisor2);
assertEquals(5, proxied.getAge()); assertThat(proxied.getAge()).isEqualTo(5);
assertEquals(1, cba1.getCalls()); assertThat(cba1.getCalls()).isEqualTo(1);
assertEquals(2, nop.getCount()); assertThat(nop.getCount()).isEqualTo(2);
assertEquals(1, cba2.getCalls()); assertThat(cba2.getCalls()).isEqualTo(1);
assertFalse(pf.replaceAdvisor(new DefaultPointcutAdvisor(null), advisor1)); assertThat(pf.replaceAdvisor(new DefaultPointcutAdvisor(null), advisor1)).isFalse();
} }
@Test @Test
@ -201,11 +196,11 @@ public class ProxyFactoryTests {
TestBeanSubclass raw = new TestBeanSubclass(); TestBeanSubclass raw = new TestBeanSubclass();
ProxyFactory factory = new ProxyFactory(raw); ProxyFactory factory = new ProxyFactory(raw);
//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); assertThat(factory.getProxiedInterfaces().length).as("Found correct number of interfaces").isEqualTo(5);
ITestBean tb = (ITestBean) factory.getProxy(); ITestBean tb = (ITestBean) factory.getProxy();
assertThat(tb).as("Picked up secondary interface").isInstanceOf(IOther.class); assertThat(tb).as("Picked up secondary interface").isInstanceOf(IOther.class);
raw.setAge(25); raw.setAge(25);
assertTrue(tb.getAge() == raw.getAge()); assertThat(tb.getAge() == raw.getAge()).isTrue();
long t = 555555L; long t = 555555L;
TimestampIntroductionInterceptor ti = new TimestampIntroductionInterceptor(t); TimestampIntroductionInterceptor ti = new TimestampIntroductionInterceptor(t);
@ -215,10 +210,10 @@ public class ProxyFactoryTests {
factory.addAdvisor(0, new DefaultIntroductionAdvisor(ti, TimeStamped.class)); factory.addAdvisor(0, new DefaultIntroductionAdvisor(ti, TimeStamped.class));
Class<?>[] newProxiedInterfaces = factory.getProxiedInterfaces(); Class<?>[] newProxiedInterfaces = factory.getProxiedInterfaces();
assertEquals("Advisor proxies one more interface after introduction", oldProxiedInterfaces.length + 1, newProxiedInterfaces.length); assertThat(newProxiedInterfaces.length).as("Advisor proxies one more interface after introduction").isEqualTo(oldProxiedInterfaces.length + 1);
TimeStamped ts = (TimeStamped) factory.getProxy(); TimeStamped ts = (TimeStamped) factory.getProxy();
assertTrue(ts.getTimeStamp() == t); assertThat(ts.getTimeStamp() == t).isTrue();
// Shouldn't fail; // Shouldn't fail;
((IOther) ts).absquatulate(); ((IOther) ts).absquatulate();
} }
@ -237,14 +232,14 @@ public class ProxyFactoryTests {
ProxyFactory factory = new ProxyFactory(new TestBean()); ProxyFactory factory = new ProxyFactory(new TestBean());
factory.addAdvice(0, di); factory.addAdvice(0, di);
assertThat(factory.getProxy()).isInstanceOf(ITestBean.class); assertThat(factory.getProxy()).isInstanceOf(ITestBean.class);
assertTrue(factory.adviceIncluded(di)); assertThat(factory.adviceIncluded(di)).isTrue();
assertTrue(!factory.adviceIncluded(diUnused)); assertThat(!factory.adviceIncluded(diUnused)).isTrue();
assertTrue(factory.countAdvicesOfType(NopInterceptor.class) == 1); assertThat(factory.countAdvicesOfType(NopInterceptor.class) == 1).isTrue();
assertTrue(factory.countAdvicesOfType(MyInterceptor.class) == 0); assertThat(factory.countAdvicesOfType(MyInterceptor.class) == 0).isTrue();
factory.addAdvice(0, diUnused); factory.addAdvice(0, diUnused);
assertTrue(factory.adviceIncluded(diUnused)); assertThat(factory.adviceIncluded(diUnused)).isTrue();
assertTrue(factory.countAdvicesOfType(NopInterceptor.class) == 2); assertThat(factory.countAdvicesOfType(NopInterceptor.class) == 2).isTrue();
} }
/** /**
@ -254,8 +249,7 @@ public class ProxyFactoryTests {
public void testCanAddAndRemoveAspectInterfacesOnSingleton() { public void testCanAddAndRemoveAspectInterfacesOnSingleton() {
ProxyFactory config = new ProxyFactory(new TestBean()); ProxyFactory config = new ProxyFactory(new TestBean());
assertFalse("Shouldn't implement TimeStamped before manipulation", assertThat(config.getProxy() instanceof TimeStamped).as("Shouldn't implement TimeStamped before manipulation").isFalse();
config.getProxy() instanceof TimeStamped);
long time = 666L; long time = 666L;
TimestampIntroductionInterceptor ti = new TimestampIntroductionInterceptor(); TimestampIntroductionInterceptor ti = new TimestampIntroductionInterceptor();
@ -265,37 +259,36 @@ public class ProxyFactoryTests {
int oldCount = config.getAdvisors().length; int oldCount = config.getAdvisors().length;
config.addAdvisor(0, new DefaultIntroductionAdvisor(ti, TimeStamped.class)); config.addAdvisor(0, new DefaultIntroductionAdvisor(ti, TimeStamped.class));
assertTrue(config.getAdvisors().length == oldCount + 1); assertThat(config.getAdvisors().length == oldCount + 1).isTrue();
TimeStamped ts = (TimeStamped) config.getProxy(); TimeStamped ts = (TimeStamped) config.getProxy();
assertTrue(ts.getTimeStamp() == time); assertThat(ts.getTimeStamp() == time).isTrue();
// Can remove // Can remove
config.removeAdvice(ti); config.removeAdvice(ti);
assertTrue(config.getAdvisors().length == oldCount); assertThat(config.getAdvisors().length == oldCount).isTrue();
assertThatExceptionOfType(RuntimeException.class) assertThatExceptionOfType(RuntimeException.class)
.as("Existing object won't implement this interface any more") .as("Existing object won't implement this interface any more")
.isThrownBy(ts::getTimeStamp); // Existing reference will fail .isThrownBy(ts::getTimeStamp); // Existing reference will fail
assertFalse("Should no longer implement TimeStamped", assertThat(config.getProxy() instanceof TimeStamped).as("Should no longer implement TimeStamped").isFalse();
config.getProxy() instanceof TimeStamped);
// 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());
assertTrue(config.getAdvisors().length == oldCount); assertThat(config.getAdvisors().length == oldCount).isTrue();
ITestBean it = (ITestBean) ts; ITestBean it = (ITestBean) ts;
DebugInterceptor debugInterceptor = new DebugInterceptor(); DebugInterceptor debugInterceptor = new DebugInterceptor();
config.addAdvice(0, debugInterceptor); config.addAdvice(0, debugInterceptor);
it.getSpouse(); it.getSpouse();
assertEquals(1, debugInterceptor.getCount()); assertThat(debugInterceptor.getCount()).isEqualTo(1);
config.removeAdvice(debugInterceptor); config.removeAdvice(debugInterceptor);
it.getSpouse(); it.getSpouse();
// not invoked again // not invoked again
assertTrue(debugInterceptor.getCount() == 1); assertThat(debugInterceptor.getCount() == 1).isTrue();
} }
@Test @Test
@ -303,15 +296,15 @@ public class ProxyFactoryTests {
ProxyFactory pf = new ProxyFactory(); ProxyFactory pf = new ProxyFactory();
pf.setTargetClass(ITestBean.class); pf.setTargetClass(ITestBean.class);
Object proxy = pf.getProxy(); Object proxy = pf.getProxy();
assertTrue("Proxy is a JDK proxy", AopUtils.isJdkDynamicProxy(proxy)); assertThat(AopUtils.isJdkDynamicProxy(proxy)).as("Proxy is a JDK proxy").isTrue();
assertTrue(proxy instanceof ITestBean); assertThat(proxy instanceof ITestBean).isTrue();
assertEquals(ITestBean.class, AopProxyUtils.ultimateTargetClass(proxy)); assertThat(AopProxyUtils.ultimateTargetClass(proxy)).isEqualTo(ITestBean.class);
ProxyFactory pf2 = new ProxyFactory(proxy); ProxyFactory pf2 = new ProxyFactory(proxy);
Object proxy2 = pf2.getProxy(); Object proxy2 = pf2.getProxy();
assertTrue("Proxy is a JDK proxy", AopUtils.isJdkDynamicProxy(proxy2)); assertThat(AopUtils.isJdkDynamicProxy(proxy2)).as("Proxy is a JDK proxy").isTrue();
assertTrue(proxy2 instanceof ITestBean); assertThat(proxy2 instanceof ITestBean).isTrue();
assertEquals(ITestBean.class, AopProxyUtils.ultimateTargetClass(proxy2)); assertThat(AopProxyUtils.ultimateTargetClass(proxy2)).isEqualTo(ITestBean.class);
} }
@Test @Test
@ -319,16 +312,16 @@ public class ProxyFactoryTests {
ProxyFactory pf = new ProxyFactory(); ProxyFactory pf = new ProxyFactory();
pf.setTargetClass(TestBean.class); pf.setTargetClass(TestBean.class);
Object proxy = pf.getProxy(); Object proxy = pf.getProxy();
assertTrue("Proxy is a CGLIB proxy", AopUtils.isCglibProxy(proxy)); assertThat(AopUtils.isCglibProxy(proxy)).as("Proxy is a CGLIB proxy").isTrue();
assertTrue(proxy instanceof TestBean); assertThat(proxy instanceof TestBean).isTrue();
assertEquals(TestBean.class, AopProxyUtils.ultimateTargetClass(proxy)); assertThat(AopProxyUtils.ultimateTargetClass(proxy)).isEqualTo(TestBean.class);
ProxyFactory pf2 = new ProxyFactory(proxy); ProxyFactory pf2 = new ProxyFactory(proxy);
pf2.setProxyTargetClass(true); pf2.setProxyTargetClass(true);
Object proxy2 = pf2.getProxy(); Object proxy2 = pf2.getProxy();
assertTrue("Proxy is a CGLIB proxy", AopUtils.isCglibProxy(proxy2)); assertThat(AopUtils.isCglibProxy(proxy2)).as("Proxy is a CGLIB proxy").isTrue();
assertTrue(proxy2 instanceof TestBean); assertThat(proxy2 instanceof TestBean).isTrue();
assertEquals(TestBean.class, AopProxyUtils.ultimateTargetClass(proxy2)); assertThat(AopProxyUtils.ultimateTargetClass(proxy2)).isEqualTo(TestBean.class);
} }
@Test @Test
@ -337,8 +330,8 @@ public class ProxyFactoryTests {
JFrame frame = new JFrame(); JFrame frame = new JFrame();
ProxyFactory proxyFactory = new ProxyFactory(frame); ProxyFactory proxyFactory = new ProxyFactory(frame);
Object proxy = proxyFactory.getProxy(); Object proxy = proxyFactory.getProxy();
assertTrue(proxy instanceof RootPaneContainer); assertThat(proxy instanceof RootPaneContainer).isTrue();
assertTrue(proxy instanceof Accessible); assertThat(proxy instanceof Accessible).isTrue();
} }
@Test @Test
@ -349,8 +342,8 @@ public class ProxyFactoryTests {
list.add(proxy1); list.add(proxy1);
list.add(proxy2); list.add(proxy2);
AnnotationAwareOrderComparator.sort(list); AnnotationAwareOrderComparator.sort(list);
assertSame(proxy2, list.get(0)); assertThat(list.get(0)).isSameAs(proxy2);
assertSame(proxy1, list.get(1)); assertThat(list.get(1)).isSameAs(proxy1);
} }
@Test @Test
@ -365,18 +358,18 @@ public class ProxyFactoryTests {
list.add(proxy1); list.add(proxy1);
list.add(proxy2); list.add(proxy2);
AnnotationAwareOrderComparator.sort(list); AnnotationAwareOrderComparator.sort(list);
assertSame(proxy2, list.get(0)); assertThat(list.get(0)).isSameAs(proxy2);
assertSame(proxy1, list.get(1)); assertThat(list.get(1)).isSameAs(proxy1);
} }
@Test @Test
public void testInterceptorWithoutJoinpoint() { public void testInterceptorWithoutJoinpoint() {
final TestBean target = new TestBean("tb"); final TestBean target = new TestBean("tb");
ITestBean proxy = ProxyFactory.getProxy(ITestBean.class, (MethodInterceptor) invocation -> { ITestBean proxy = ProxyFactory.getProxy(ITestBean.class, (MethodInterceptor) invocation -> {
assertNull(invocation.getThis()); assertThat(invocation.getThis()).isNull();
return invocation.getMethod().invoke(target, invocation.getArguments()); return invocation.getMethod().invoke(target, invocation.getArguments());
}); });
assertEquals("tb", proxy.getName()); assertThat(proxy.getName()).isEqualTo("tb");
} }

View File

@ -28,9 +28,9 @@ import org.junit.Test;
import org.springframework.aop.ThrowsAdvice; import org.springframework.aop.ThrowsAdvice;
import org.springframework.tests.aop.advice.MethodCounter; import org.springframework.tests.aop.advice.MethodCounter;
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.junit.Assert.assertEquals;
import static org.mockito.BDDMockito.given; import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
@ -54,22 +54,22 @@ public class ThrowsAdviceInterceptorTests {
Object ret = new Object(); Object ret = new Object();
MethodInvocation mi = mock(MethodInvocation.class); MethodInvocation mi = mock(MethodInvocation.class);
given(mi.proceed()).willReturn(ret); given(mi.proceed()).willReturn(ret);
assertEquals(ret, ti.invoke(mi)); assertThat(ti.invoke(mi)).isEqualTo(ret);
assertEquals(0, th.getCalls()); assertThat(th.getCalls()).isEqualTo(0);
} }
@Test @Test
public void testNoHandlerMethodForThrowable() throws Throwable { public void testNoHandlerMethodForThrowable() throws Throwable {
MyThrowsHandler th = new MyThrowsHandler(); MyThrowsHandler th = new MyThrowsHandler();
ThrowsAdviceInterceptor ti = new ThrowsAdviceInterceptor(th); ThrowsAdviceInterceptor ti = new ThrowsAdviceInterceptor(th);
assertEquals(2, ti.getHandlerMethodCount()); assertThat(ti.getHandlerMethodCount()).isEqualTo(2);
Exception ex = new Exception(); Exception ex = new Exception();
MethodInvocation mi = mock(MethodInvocation.class); MethodInvocation mi = mock(MethodInvocation.class);
given(mi.proceed()).willThrow(ex); given(mi.proceed()).willThrow(ex);
assertThatExceptionOfType(Exception.class).isThrownBy(() -> assertThatExceptionOfType(Exception.class).isThrownBy(() ->
ti.invoke(mi)) ti.invoke(mi))
.isSameAs(ex); .isSameAs(ex);
assertEquals(0, th.getCalls()); assertThat(th.getCalls()).isEqualTo(0);
} }
@Test @Test
@ -84,8 +84,8 @@ public class ThrowsAdviceInterceptorTests {
assertThatExceptionOfType(FileNotFoundException.class).isThrownBy(() -> assertThatExceptionOfType(FileNotFoundException.class).isThrownBy(() ->
ti.invoke(mi)) ti.invoke(mi))
.isSameAs(ex); .isSameAs(ex);
assertEquals(1, th.getCalls()); assertThat(th.getCalls()).isEqualTo(1);
assertEquals(1, th.getCalls("ioException")); assertThat(th.getCalls("ioException")).isEqualTo(1);
} }
@Test @Test
@ -99,8 +99,8 @@ public class ThrowsAdviceInterceptorTests {
assertThatExceptionOfType(ConnectException.class).isThrownBy(() -> assertThatExceptionOfType(ConnectException.class).isThrownBy(() ->
ti.invoke(mi)) ti.invoke(mi))
.isSameAs(ex); .isSameAs(ex);
assertEquals(1, th.getCalls()); assertThat(th.getCalls()).isEqualTo(1);
assertEquals(1, th.getCalls("remoteException")); assertThat(th.getCalls("remoteException")).isEqualTo(1);
} }
@Test @Test
@ -124,8 +124,8 @@ public class ThrowsAdviceInterceptorTests {
assertThatExceptionOfType(Throwable.class).isThrownBy(() -> assertThatExceptionOfType(Throwable.class).isThrownBy(() ->
ti.invoke(mi)) ti.invoke(mi))
.isSameAs(t); .isSameAs(t);
assertEquals(1, th.getCalls()); assertThat(th.getCalls()).isEqualTo(1);
assertEquals(1, th.getCalls("remoteException")); assertThat(th.getCalls("remoteException")).isEqualTo(1);
} }

View File

@ -27,7 +27,7 @@ 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.SerializationTestUtils; import org.springframework.util.SerializationTestUtils;
import static org.junit.Assert.assertEquals; import static org.assertj.core.api.Assertions.assertThat;
/** /**
* @author Juergen Hoeller * @author Juergen Hoeller
@ -58,7 +58,7 @@ public class ConcurrencyThrottleInterceptorTests {
Advised advised = (Advised) serializedProxy; Advised advised = (Advised) serializedProxy;
ConcurrencyThrottleInterceptor serializedCti = ConcurrencyThrottleInterceptor serializedCti =
(ConcurrencyThrottleInterceptor) advised.getAdvisors()[0].getAdvice(); (ConcurrencyThrottleInterceptor) advised.getAdvisors()[0].getAdvice();
assertEquals(cti.getConcurrencyLimit(), serializedCti.getConcurrencyLimit()); assertThat(serializedCti.getConcurrencyLimit()).isEqualTo(cti.getConcurrencyLimit());
serializedProxy.getAge(); serializedProxy.getAge();
} }

View File

@ -20,8 +20,8 @@ import org.aopalliance.intercept.MethodInvocation;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.junit.Test; import org.junit.Test;
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.junit.Assert.assertEquals;
import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq; import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.BDDMockito.given; import static org.mockito.BDDMockito.given;
@ -73,7 +73,7 @@ public class DebugInterceptorTests {
} }
private void checkCallCountTotal(DebugInterceptor interceptor) { private void checkCallCountTotal(DebugInterceptor interceptor) {
assertEquals("Intercepted call count not being incremented correctly", 1, interceptor.getCount()); assertThat(interceptor.getCount()).as("Intercepted call count not being incremented correctly").isEqualTo(1);
} }

View File

@ -23,9 +23,7 @@ import org.springframework.beans.factory.NamedBean;
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.junit.Assert.assertEquals; import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
/** /**
* @author Rod Johnson * @author Rod Johnson
@ -42,7 +40,7 @@ public class ExposeBeanNameAdvisorsTests {
@Override @Override
public int getAge() { public int getAge() {
assertEquals(beanName, ExposeBeanNameAdvisors.getBeanName()); assertThat(ExposeBeanNameAdvisors.getBeanName()).isEqualTo(beanName);
return super.getAge(); return super.getAge();
} }
} }
@ -56,7 +54,8 @@ public class ExposeBeanNameAdvisorsTests {
pf.addAdvisor(ExposeBeanNameAdvisors.createAdvisorWithoutIntroduction(beanName)); pf.addAdvisor(ExposeBeanNameAdvisors.createAdvisorWithoutIntroduction(beanName));
ITestBean proxy = (ITestBean) pf.getProxy(); ITestBean proxy = (ITestBean) pf.getProxy();
assertFalse("No introduction", proxy instanceof NamedBean); boolean condition = proxy instanceof NamedBean;
assertThat(condition).as("No introduction").isFalse();
// Requires binding // Requires binding
proxy.getAge(); proxy.getAge();
} }
@ -70,12 +69,13 @@ public class ExposeBeanNameAdvisorsTests {
pf.addAdvisor(ExposeBeanNameAdvisors.createAdvisorIntroducingNamedBean(beanName)); pf.addAdvisor(ExposeBeanNameAdvisors.createAdvisorIntroducingNamedBean(beanName));
ITestBean proxy = (ITestBean) pf.getProxy(); ITestBean proxy = (ITestBean) pf.getProxy();
assertTrue("Introduction was made", proxy instanceof NamedBean); boolean condition = proxy instanceof NamedBean;
assertThat(condition).as("Introduction was made").isTrue();
// Requires binding // Requires binding
proxy.getAge(); proxy.getAge();
NamedBean nb = (NamedBean) proxy; NamedBean nb = (NamedBean) proxy;
assertEquals("Name returned correctly", beanName, nb.getBeanName()); assertThat(nb.getBeanName()).as("Name returned correctly").isEqualTo(beanName);
} }
} }

View File

@ -24,8 +24,7 @@ import org.springframework.beans.factory.xml.XmlBeanDefinitionReader;
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.junit.Assert.assertEquals; import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertTrue;
import static org.springframework.tests.TestResourceUtils.qualifiedResource; import static org.springframework.tests.TestResourceUtils.qualifiedResource;
/** /**
@ -45,7 +44,7 @@ public class ExposeInvocationInterceptorTests {
String name = "tony"; String name = "tony";
tb.setName(name); tb.setName(name);
// Fires context checks // Fires context checks
assertEquals(name, tb.getName()); assertThat(tb.getName()).isEqualTo(name);
} }
} }
@ -75,8 +74,7 @@ class InvocationCheckExposedInvocationTestBean extends ExposedInvocationTestBean
@Override @Override
protected void assertions(MethodInvocation invocation) { protected void assertions(MethodInvocation invocation) {
assertTrue(invocation.getThis() == this); assertThat(invocation.getThis() == this).isTrue();
assertTrue("Invocation should be on ITestBean: " + invocation.getMethod(), assertThat(ITestBean.class.isAssignableFrom(invocation.getMethod().getDeclaringClass())).as("Invocation should be on ITestBean: " + invocation.getMethod()).isTrue();
ITestBean.class.isAssignableFrom(invocation.getMethod().getDeclaringClass()));
} }
} }

View File

@ -23,9 +23,8 @@ import org.junit.After;
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.assertThatIllegalArgumentException; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.mockito.BDDMockito.given; import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
@ -59,9 +58,8 @@ public class JamonPerformanceMonitorInterceptorTests {
interceptor.invokeUnderTrace(mi, log); interceptor.invokeUnderTrace(mi, log);
assertTrue("jamon must track the method being invoked", MonitorFactory.getNumRows() > 0); assertThat(MonitorFactory.getNumRows() > 0).as("jamon must track the method being invoked").isTrue();
assertTrue("The jamon report must contain the toString method that was invoked", assertThat(MonitorFactory.getReport().contains("toString")).as("The jamon report must contain the toString method that was invoked").isTrue();
MonitorFactory.getReport().contains("toString"));
} }
@Test @Test
@ -72,14 +70,10 @@ public class JamonPerformanceMonitorInterceptorTests {
assertThatIllegalArgumentException().isThrownBy(() -> assertThatIllegalArgumentException().isThrownBy(() ->
interceptor.invokeUnderTrace(mi, log)); interceptor.invokeUnderTrace(mi, log));
assertEquals("Monitors must exist for the method invocation and 2 exceptions", assertThat(MonitorFactory.getNumRows()).as("Monitors must exist for the method invocation and 2 exceptions").isEqualTo(3);
3, MonitorFactory.getNumRows()); assertThat(MonitorFactory.getReport().contains("toString")).as("The jamon report must contain the toString method that was invoked").isTrue();
assertTrue("The jamon report must contain the toString method that was invoked", assertThat(MonitorFactory.getReport().contains(MonitorFactory.EXCEPTIONS_LABEL)).as("The jamon report must contain the generic exception: " + MonitorFactory.EXCEPTIONS_LABEL).isTrue();
MonitorFactory.getReport().contains("toString")); assertThat(MonitorFactory.getReport().contains("IllegalArgumentException")).as("The jamon report must contain the specific exception: IllegalArgumentException'").isTrue();
assertTrue("The jamon report must contain the generic exception: " + MonitorFactory.EXCEPTIONS_LABEL,
MonitorFactory.getReport().contains(MonitorFactory.EXCEPTIONS_LABEL));
assertTrue("The jamon report must contain the specific exception: IllegalArgumentException'",
MonitorFactory.getReport().contains("IllegalArgumentException"));
} }
} }

View File

@ -20,8 +20,8 @@ import org.aopalliance.intercept.MethodInvocation;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.junit.Test; import org.junit.Test;
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.junit.Assert.assertNotNull;
import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.BDDMockito.given; import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
@ -38,14 +38,14 @@ public class PerformanceMonitorInterceptorTests {
public void testSuffixAndPrefixAssignment() { public void testSuffixAndPrefixAssignment() {
PerformanceMonitorInterceptor interceptor = new PerformanceMonitorInterceptor(); PerformanceMonitorInterceptor interceptor = new PerformanceMonitorInterceptor();
assertNotNull(interceptor.getPrefix()); assertThat(interceptor.getPrefix()).isNotNull();
assertNotNull(interceptor.getSuffix()); assertThat(interceptor.getSuffix()).isNotNull();
interceptor.setPrefix(null); interceptor.setPrefix(null);
interceptor.setSuffix(null); interceptor.setSuffix(null);
assertNotNull(interceptor.getPrefix()); assertThat(interceptor.getPrefix()).isNotNull();
assertNotNull(interceptor.getSuffix()); assertThat(interceptor.getSuffix()).isNotNull();
} }
@Test @Test

View File

@ -23,9 +23,7 @@ import org.junit.Test;
import org.springframework.beans.factory.support.DefaultListableBeanFactory; import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.beans.factory.xml.XmlBeanDefinitionReader; import org.springframework.beans.factory.xml.XmlBeanDefinitionReader;
import static org.junit.Assert.assertFalse; import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import static org.springframework.tests.TestResourceUtils.qualifiedResource; import static org.springframework.tests.TestResourceUtils.qualifiedResource;
/** /**
@ -41,12 +39,12 @@ public class ScopedProxyAutowireTests {
new XmlBeanDefinitionReader(bf).loadBeanDefinitions( new XmlBeanDefinitionReader(bf).loadBeanDefinitions(
qualifiedResource(ScopedProxyAutowireTests.class, "scopedAutowireFalse.xml")); qualifiedResource(ScopedProxyAutowireTests.class, "scopedAutowireFalse.xml"));
assertTrue(Arrays.asList(bf.getBeanNamesForType(TestBean.class, false, false)).contains("scoped")); assertThat(Arrays.asList(bf.getBeanNamesForType(TestBean.class, false, false)).contains("scoped")).isTrue();
assertTrue(Arrays.asList(bf.getBeanNamesForType(TestBean.class, true, false)).contains("scoped")); assertThat(Arrays.asList(bf.getBeanNamesForType(TestBean.class, true, false)).contains("scoped")).isTrue();
assertFalse(bf.containsSingleton("scoped")); assertThat(bf.containsSingleton("scoped")).isFalse();
TestBean autowired = (TestBean) bf.getBean("autowired"); TestBean autowired = (TestBean) bf.getBean("autowired");
TestBean unscoped = (TestBean) bf.getBean("unscoped"); TestBean unscoped = (TestBean) bf.getBean("unscoped");
assertSame(unscoped, autowired.getChild()); assertThat(autowired.getChild()).isSameAs(unscoped);
} }
@Test @Test
@ -55,12 +53,12 @@ public class ScopedProxyAutowireTests {
new XmlBeanDefinitionReader(bf).loadBeanDefinitions( new XmlBeanDefinitionReader(bf).loadBeanDefinitions(
qualifiedResource(ScopedProxyAutowireTests.class, "scopedAutowireTrue.xml")); qualifiedResource(ScopedProxyAutowireTests.class, "scopedAutowireTrue.xml"));
assertTrue(Arrays.asList(bf.getBeanNamesForType(TestBean.class, true, false)).contains("scoped")); assertThat(Arrays.asList(bf.getBeanNamesForType(TestBean.class, true, false)).contains("scoped")).isTrue();
assertTrue(Arrays.asList(bf.getBeanNamesForType(TestBean.class, false, false)).contains("scoped")); assertThat(Arrays.asList(bf.getBeanNamesForType(TestBean.class, false, false)).contains("scoped")).isTrue();
assertFalse(bf.containsSingleton("scoped")); assertThat(bf.containsSingleton("scoped")).isFalse();
TestBean autowired = (TestBean) bf.getBean("autowired"); TestBean autowired = (TestBean) bf.getBean("autowired");
TestBean scoped = (TestBean) bf.getBean("scoped"); TestBean scoped = (TestBean) bf.getBean("scoped");
assertSame(scoped, autowired.getChild()); assertThat(autowired.getChild()).isSameAs(scoped);
} }

View File

@ -24,9 +24,7 @@ import org.junit.Test;
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.junit.Assert.assertEquals; import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
/** /**
* @author Rod Johnson * @author Rod Johnson
@ -56,9 +54,9 @@ public abstract class AbstractRegexpMethodPointcutTests {
} }
protected void noPatternSuppliedTests(AbstractRegexpMethodPointcut rpc) throws Exception { protected void noPatternSuppliedTests(AbstractRegexpMethodPointcut rpc) throws Exception {
assertFalse(rpc.matches(Object.class.getMethod("hashCode"), String.class)); assertThat(rpc.matches(Object.class.getMethod("hashCode"), String.class)).isFalse();
assertFalse(rpc.matches(Object.class.getMethod("wait"), Object.class)); assertThat(rpc.matches(Object.class.getMethod("wait"), Object.class)).isFalse();
assertEquals(0, rpc.getPatterns().length); assertThat(rpc.getPatterns().length).isEqualTo(0);
} }
@Test @Test
@ -71,46 +69,46 @@ public abstract class AbstractRegexpMethodPointcutTests {
protected void exactMatchTests(AbstractRegexpMethodPointcut rpc) throws Exception { protected void exactMatchTests(AbstractRegexpMethodPointcut rpc) throws Exception {
// assumes rpc.setPattern("java.lang.Object.hashCode"); // assumes rpc.setPattern("java.lang.Object.hashCode");
assertTrue(rpc.matches(Object.class.getMethod("hashCode"), String.class)); assertThat(rpc.matches(Object.class.getMethod("hashCode"), String.class)).isTrue();
assertTrue(rpc.matches(Object.class.getMethod("hashCode"), Object.class)); assertThat(rpc.matches(Object.class.getMethod("hashCode"), Object.class)).isTrue();
assertFalse(rpc.matches(Object.class.getMethod("wait"), Object.class)); assertThat(rpc.matches(Object.class.getMethod("wait"), Object.class)).isFalse();
} }
@Test @Test
public void testSpecificMatch() throws Exception { public void testSpecificMatch() throws Exception {
rpc.setPattern("java.lang.String.hashCode"); rpc.setPattern("java.lang.String.hashCode");
assertTrue(rpc.matches(Object.class.getMethod("hashCode"), String.class)); assertThat(rpc.matches(Object.class.getMethod("hashCode"), String.class)).isTrue();
assertFalse(rpc.matches(Object.class.getMethod("hashCode"), Object.class)); assertThat(rpc.matches(Object.class.getMethod("hashCode"), Object.class)).isFalse();
} }
@Test @Test
public void testWildcard() throws Exception { public void testWildcard() throws Exception {
rpc.setPattern(".*Object.hashCode"); rpc.setPattern(".*Object.hashCode");
assertTrue(rpc.matches(Object.class.getMethod("hashCode"), Object.class)); assertThat(rpc.matches(Object.class.getMethod("hashCode"), Object.class)).isTrue();
assertFalse(rpc.matches(Object.class.getMethod("wait"), Object.class)); assertThat(rpc.matches(Object.class.getMethod("wait"), Object.class)).isFalse();
} }
@Test @Test
public void testWildcardForOneClass() throws Exception { public void testWildcardForOneClass() throws Exception {
rpc.setPattern("java.lang.Object.*"); rpc.setPattern("java.lang.Object.*");
assertTrue(rpc.matches(Object.class.getMethod("hashCode"), String.class)); assertThat(rpc.matches(Object.class.getMethod("hashCode"), String.class)).isTrue();
assertTrue(rpc.matches(Object.class.getMethod("wait"), String.class)); assertThat(rpc.matches(Object.class.getMethod("wait"), String.class)).isTrue();
} }
@Test @Test
public void testMatchesObjectClass() throws Exception { public void testMatchesObjectClass() throws Exception {
rpc.setPattern("java.lang.Object.*"); rpc.setPattern("java.lang.Object.*");
assertTrue(rpc.matches(Exception.class.getMethod("hashCode"), IOException.class)); assertThat(rpc.matches(Exception.class.getMethod("hashCode"), IOException.class)).isTrue();
// Doesn't match a method from Throwable // Doesn't match a method from Throwable
assertFalse(rpc.matches(Exception.class.getMethod("getMessage"), Exception.class)); assertThat(rpc.matches(Exception.class.getMethod("getMessage"), Exception.class)).isFalse();
} }
@Test @Test
public void testWithExclusion() throws Exception { public void testWithExclusion() throws Exception {
this.rpc.setPattern(".*get.*"); this.rpc.setPattern(".*get.*");
this.rpc.setExcludedPattern(".*Age.*"); this.rpc.setExcludedPattern(".*Age.*");
assertTrue(this.rpc.matches(TestBean.class.getMethod("getName"), TestBean.class)); assertThat(this.rpc.matches(TestBean.class.getMethod("getName"), TestBean.class)).isTrue();
assertFalse(this.rpc.matches(TestBean.class.getMethod("getAge"), TestBean.class)); assertThat(this.rpc.matches(TestBean.class.getMethod("getAge"), TestBean.class)).isFalse();
} }
} }

View File

@ -30,9 +30,7 @@ import org.springframework.tests.aop.interceptor.NopInterceptor;
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.junit.Assert.assertFalse; import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
/** /**
* @author Rod Johnson * @author Rod Johnson
@ -50,13 +48,13 @@ public class AopUtilsTests {
} }
Pointcut no = new TestPointcut(); Pointcut no = new TestPointcut();
assertFalse(AopUtils.canApply(no, Object.class)); assertThat(AopUtils.canApply(no, Object.class)).isFalse();
} }
@Test @Test
public void testPointcutAlwaysApplies() { public void testPointcutAlwaysApplies() {
assertTrue(AopUtils.canApply(new DefaultPointcutAdvisor(new NopInterceptor()), Object.class)); assertThat(AopUtils.canApply(new DefaultPointcutAdvisor(new NopInterceptor()), Object.class)).isTrue();
assertTrue(AopUtils.canApply(new DefaultPointcutAdvisor(new NopInterceptor()), TestBean.class)); assertThat(AopUtils.canApply(new DefaultPointcutAdvisor(new NopInterceptor()), TestBean.class)).isTrue();
} }
@Test @Test
@ -71,7 +69,7 @@ public class AopUtilsTests {
Pointcut pc = new TestPointcut(); Pointcut pc = new TestPointcut();
// will return true if we're not proxying interfaces // will return true if we're not proxying interfaces
assertTrue(AopUtils.canApply(pc, Object.class)); assertThat(AopUtils.canApply(pc, Object.class)).isTrue();
} }
/** /**
@ -81,14 +79,13 @@ public class AopUtilsTests {
*/ */
@Test @Test
public void testCanonicalFrameworkClassesStillCanonicalOnDeserialization() throws Exception { public void testCanonicalFrameworkClassesStillCanonicalOnDeserialization() throws Exception {
assertSame(MethodMatcher.TRUE, SerializationTestUtils.serializeAndDeserialize(MethodMatcher.TRUE)); assertThat(SerializationTestUtils.serializeAndDeserialize(MethodMatcher.TRUE)).isSameAs(MethodMatcher.TRUE);
assertSame(ClassFilter.TRUE, SerializationTestUtils.serializeAndDeserialize(ClassFilter.TRUE)); assertThat(SerializationTestUtils.serializeAndDeserialize(ClassFilter.TRUE)).isSameAs(ClassFilter.TRUE);
assertSame(Pointcut.TRUE, SerializationTestUtils.serializeAndDeserialize(Pointcut.TRUE)); assertThat(SerializationTestUtils.serializeAndDeserialize(Pointcut.TRUE)).isSameAs(Pointcut.TRUE);
assertSame(EmptyTargetSource.INSTANCE, SerializationTestUtils.serializeAndDeserialize(EmptyTargetSource.INSTANCE)); assertThat(SerializationTestUtils.serializeAndDeserialize(EmptyTargetSource.INSTANCE)).isSameAs(EmptyTargetSource.INSTANCE);
assertSame(Pointcuts.SETTERS, SerializationTestUtils.serializeAndDeserialize(Pointcuts.SETTERS)); assertThat(SerializationTestUtils.serializeAndDeserialize(Pointcuts.SETTERS)).isSameAs(Pointcuts.SETTERS);
assertSame(Pointcuts.GETTERS, SerializationTestUtils.serializeAndDeserialize(Pointcuts.GETTERS)); assertThat(SerializationTestUtils.serializeAndDeserialize(Pointcuts.GETTERS)).isSameAs(Pointcuts.GETTERS);
assertSame(ExposeInvocationInterceptor.INSTANCE, assertThat(SerializationTestUtils.serializeAndDeserialize(ExposeInvocationInterceptor.INSTANCE)).isSameAs(ExposeInvocationInterceptor.INSTANCE);
SerializationTestUtils.serializeAndDeserialize(ExposeInvocationInterceptor.INSTANCE));
} }
} }

View File

@ -23,8 +23,7 @@ import org.springframework.core.NestedRuntimeException;
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.junit.Assert.assertFalse; import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertTrue;
/** /**
* @author Rod Johnson * @author Rod Johnson
@ -40,23 +39,23 @@ public class ClassFiltersTests {
@Test @Test
public void testUnion() { public void testUnion() {
assertTrue(exceptionFilter.matches(RuntimeException.class)); assertThat(exceptionFilter.matches(RuntimeException.class)).isTrue();
assertFalse(exceptionFilter.matches(TestBean.class)); assertThat(exceptionFilter.matches(TestBean.class)).isFalse();
assertFalse(itbFilter.matches(Exception.class)); assertThat(itbFilter.matches(Exception.class)).isFalse();
assertTrue(itbFilter.matches(TestBean.class)); assertThat(itbFilter.matches(TestBean.class)).isTrue();
ClassFilter union = ClassFilters.union(exceptionFilter, itbFilter); ClassFilter union = ClassFilters.union(exceptionFilter, itbFilter);
assertTrue(union.matches(RuntimeException.class)); assertThat(union.matches(RuntimeException.class)).isTrue();
assertTrue(union.matches(TestBean.class)); assertThat(union.matches(TestBean.class)).isTrue();
} }
@Test @Test
public void testIntersection() { public void testIntersection() {
assertTrue(exceptionFilter.matches(RuntimeException.class)); assertThat(exceptionFilter.matches(RuntimeException.class)).isTrue();
assertTrue(hasRootCauseFilter.matches(NestedRuntimeException.class)); assertThat(hasRootCauseFilter.matches(NestedRuntimeException.class)).isTrue();
ClassFilter intersection = ClassFilters.intersection(exceptionFilter, hasRootCauseFilter); ClassFilter intersection = ClassFilters.intersection(exceptionFilter, hasRootCauseFilter);
assertFalse(intersection.matches(RuntimeException.class)); assertThat(intersection.matches(RuntimeException.class)).isFalse();
assertFalse(intersection.matches(TestBean.class)); assertThat(intersection.matches(TestBean.class)).isFalse();
assertTrue(intersection.matches(NestedRuntimeException.class)); assertThat(intersection.matches(NestedRuntimeException.class)).isTrue();
} }
} }

View File

@ -21,7 +21,7 @@ import org.springframework.aop.framework.ProxyFactory;
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.junit.Assert.assertEquals; import static org.assertj.core.api.Assertions.assertThat;
/** /**
* @author Colin Sampaleanu * @author Colin Sampaleanu
@ -39,6 +39,6 @@ public class ClassUtilsTests {
pf.setProxyTargetClass(true); pf.setProxyTargetClass(true);
TestBean proxy = (TestBean) pf.getProxy(); TestBean proxy = (TestBean) pf.getProxy();
String className = ClassUtils.getShortName(proxy.getClass()); String className = ClassUtils.getShortName(proxy.getClass());
assertEquals("Class name did not match", "TestBean", className); assertThat(className).as("Class name did not match").isEqualTo("TestBean");
} }
} }

View File

@ -27,9 +27,7 @@ import org.springframework.core.NestedRuntimeException;
import org.springframework.lang.Nullable; import org.springframework.lang.Nullable;
import org.springframework.tests.sample.beans.TestBean; import org.springframework.tests.sample.beans.TestBean;
import static org.junit.Assert.assertEquals; import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
/** /**
* @author Rod Johnson * @author Rod Johnson
@ -69,68 +67,68 @@ public class ComposablePointcutTests {
@Test @Test
public void testMatchAll() throws NoSuchMethodException { public void testMatchAll() throws NoSuchMethodException {
Pointcut pc = new ComposablePointcut(); Pointcut pc = new ComposablePointcut();
assertTrue(pc.getClassFilter().matches(Object.class)); assertThat(pc.getClassFilter().matches(Object.class)).isTrue();
assertTrue(pc.getMethodMatcher().matches(Object.class.getMethod("hashCode"), Exception.class)); assertThat(pc.getMethodMatcher().matches(Object.class.getMethod("hashCode"), Exception.class)).isTrue();
} }
@Test @Test
public void testFilterByClass() throws NoSuchMethodException { public void testFilterByClass() throws NoSuchMethodException {
ComposablePointcut pc = new ComposablePointcut(); ComposablePointcut pc = new ComposablePointcut();
assertTrue(pc.getClassFilter().matches(Object.class)); assertThat(pc.getClassFilter().matches(Object.class)).isTrue();
ClassFilter cf = new RootClassFilter(Exception.class); ClassFilter cf = new RootClassFilter(Exception.class);
pc.intersection(cf); pc.intersection(cf);
assertFalse(pc.getClassFilter().matches(Object.class)); assertThat(pc.getClassFilter().matches(Object.class)).isFalse();
assertTrue(pc.getClassFilter().matches(Exception.class)); assertThat(pc.getClassFilter().matches(Exception.class)).isTrue();
pc.intersection(new RootClassFilter(NestedRuntimeException.class)); pc.intersection(new RootClassFilter(NestedRuntimeException.class));
assertFalse(pc.getClassFilter().matches(Exception.class)); assertThat(pc.getClassFilter().matches(Exception.class)).isFalse();
assertTrue(pc.getClassFilter().matches(NestedRuntimeException.class)); assertThat(pc.getClassFilter().matches(NestedRuntimeException.class)).isTrue();
assertFalse(pc.getClassFilter().matches(String.class)); assertThat(pc.getClassFilter().matches(String.class)).isFalse();
pc.union(new RootClassFilter(String.class)); pc.union(new RootClassFilter(String.class));
assertFalse(pc.getClassFilter().matches(Exception.class)); assertThat(pc.getClassFilter().matches(Exception.class)).isFalse();
assertTrue(pc.getClassFilter().matches(String.class)); assertThat(pc.getClassFilter().matches(String.class)).isTrue();
assertTrue(pc.getClassFilter().matches(NestedRuntimeException.class)); assertThat(pc.getClassFilter().matches(NestedRuntimeException.class)).isTrue();
} }
@Test @Test
public void testUnionMethodMatcher() { public void testUnionMethodMatcher() {
// Matches the getAge() method in any class // Matches the getAge() method in any class
ComposablePointcut pc = new ComposablePointcut(ClassFilter.TRUE, GET_AGE_METHOD_MATCHER); ComposablePointcut pc = new ComposablePointcut(ClassFilter.TRUE, GET_AGE_METHOD_MATCHER);
assertFalse(Pointcuts.matches(pc, PointcutsTests.TEST_BEAN_ABSQUATULATE, TestBean.class)); assertThat(Pointcuts.matches(pc, PointcutsTests.TEST_BEAN_ABSQUATULATE, TestBean.class)).isFalse();
assertTrue(Pointcuts.matches(pc, PointcutsTests.TEST_BEAN_GET_AGE, TestBean.class)); assertThat(Pointcuts.matches(pc, PointcutsTests.TEST_BEAN_GET_AGE, TestBean.class)).isTrue();
assertFalse(Pointcuts.matches(pc, PointcutsTests.TEST_BEAN_GET_NAME, TestBean.class)); assertThat(Pointcuts.matches(pc, PointcutsTests.TEST_BEAN_GET_NAME, TestBean.class)).isFalse();
pc.union(GETTER_METHOD_MATCHER); pc.union(GETTER_METHOD_MATCHER);
// Should now match all getter methods // Should now match all getter methods
assertFalse(Pointcuts.matches(pc, PointcutsTests.TEST_BEAN_ABSQUATULATE, TestBean.class)); assertThat(Pointcuts.matches(pc, PointcutsTests.TEST_BEAN_ABSQUATULATE, TestBean.class)).isFalse();
assertTrue(Pointcuts.matches(pc, PointcutsTests.TEST_BEAN_GET_AGE, TestBean.class)); assertThat(Pointcuts.matches(pc, PointcutsTests.TEST_BEAN_GET_AGE, TestBean.class)).isTrue();
assertTrue(Pointcuts.matches(pc, PointcutsTests.TEST_BEAN_GET_NAME, TestBean.class)); assertThat(Pointcuts.matches(pc, PointcutsTests.TEST_BEAN_GET_NAME, TestBean.class)).isTrue();
pc.union(ABSQUATULATE_METHOD_MATCHER); pc.union(ABSQUATULATE_METHOD_MATCHER);
// Should now match absquatulate() as well // Should now match absquatulate() as well
assertTrue(Pointcuts.matches(pc, PointcutsTests.TEST_BEAN_ABSQUATULATE, TestBean.class)); assertThat(Pointcuts.matches(pc, PointcutsTests.TEST_BEAN_ABSQUATULATE, TestBean.class)).isTrue();
assertTrue(Pointcuts.matches(pc, PointcutsTests.TEST_BEAN_GET_AGE, TestBean.class)); assertThat(Pointcuts.matches(pc, PointcutsTests.TEST_BEAN_GET_AGE, TestBean.class)).isTrue();
assertTrue(Pointcuts.matches(pc, PointcutsTests.TEST_BEAN_GET_NAME, TestBean.class)); assertThat(Pointcuts.matches(pc, PointcutsTests.TEST_BEAN_GET_NAME, TestBean.class)).isTrue();
// But it doesn't match everything // But it doesn't match everything
assertFalse(Pointcuts.matches(pc, PointcutsTests.TEST_BEAN_SET_AGE, TestBean.class)); assertThat(Pointcuts.matches(pc, PointcutsTests.TEST_BEAN_SET_AGE, TestBean.class)).isFalse();
} }
@Test @Test
public void testIntersectionMethodMatcher() { public void testIntersectionMethodMatcher() {
ComposablePointcut pc = new ComposablePointcut(); ComposablePointcut pc = new ComposablePointcut();
assertTrue(pc.getMethodMatcher().matches(PointcutsTests.TEST_BEAN_ABSQUATULATE, TestBean.class)); assertThat(pc.getMethodMatcher().matches(PointcutsTests.TEST_BEAN_ABSQUATULATE, TestBean.class)).isTrue();
assertTrue(pc.getMethodMatcher().matches(PointcutsTests.TEST_BEAN_GET_AGE, TestBean.class)); assertThat(pc.getMethodMatcher().matches(PointcutsTests.TEST_BEAN_GET_AGE, TestBean.class)).isTrue();
assertTrue(pc.getMethodMatcher().matches(PointcutsTests.TEST_BEAN_GET_NAME, TestBean.class)); assertThat(pc.getMethodMatcher().matches(PointcutsTests.TEST_BEAN_GET_NAME, TestBean.class)).isTrue();
pc.intersection(GETTER_METHOD_MATCHER); pc.intersection(GETTER_METHOD_MATCHER);
assertFalse(pc.getMethodMatcher().matches(PointcutsTests.TEST_BEAN_ABSQUATULATE, TestBean.class)); assertThat(pc.getMethodMatcher().matches(PointcutsTests.TEST_BEAN_ABSQUATULATE, TestBean.class)).isFalse();
assertTrue(pc.getMethodMatcher().matches(PointcutsTests.TEST_BEAN_GET_AGE, TestBean.class)); assertThat(pc.getMethodMatcher().matches(PointcutsTests.TEST_BEAN_GET_AGE, TestBean.class)).isTrue();
assertTrue(pc.getMethodMatcher().matches(PointcutsTests.TEST_BEAN_GET_NAME, TestBean.class)); assertThat(pc.getMethodMatcher().matches(PointcutsTests.TEST_BEAN_GET_NAME, TestBean.class)).isTrue();
pc.intersection(GET_AGE_METHOD_MATCHER); pc.intersection(GET_AGE_METHOD_MATCHER);
// Use the Pointcuts matches method // Use the Pointcuts matches method
assertFalse(Pointcuts.matches(pc, PointcutsTests.TEST_BEAN_ABSQUATULATE, TestBean.class)); assertThat(Pointcuts.matches(pc, PointcutsTests.TEST_BEAN_ABSQUATULATE, TestBean.class)).isFalse();
assertTrue(Pointcuts.matches(pc, PointcutsTests.TEST_BEAN_GET_AGE, TestBean.class)); assertThat(Pointcuts.matches(pc, PointcutsTests.TEST_BEAN_GET_AGE, TestBean.class)).isTrue();
assertFalse(Pointcuts.matches(pc, PointcutsTests.TEST_BEAN_GET_NAME, TestBean.class)); assertThat(Pointcuts.matches(pc, PointcutsTests.TEST_BEAN_GET_NAME, TestBean.class)).isFalse();
} }
@Test @Test
@ -138,24 +136,24 @@ public class ComposablePointcutTests {
ComposablePointcut pc1 = new ComposablePointcut(); ComposablePointcut pc1 = new ComposablePointcut();
ComposablePointcut pc2 = new ComposablePointcut(); ComposablePointcut pc2 = new ComposablePointcut();
assertEquals(pc1, pc2); assertThat(pc2).isEqualTo(pc1);
assertEquals(pc1.hashCode(), pc2.hashCode()); assertThat(pc2.hashCode()).isEqualTo(pc1.hashCode());
pc1.intersection(GETTER_METHOD_MATCHER); pc1.intersection(GETTER_METHOD_MATCHER);
assertFalse(pc1.equals(pc2)); assertThat(pc1.equals(pc2)).isFalse();
assertFalse(pc1.hashCode() == pc2.hashCode()); assertThat(pc1.hashCode() == pc2.hashCode()).isFalse();
pc2.intersection(GETTER_METHOD_MATCHER); pc2.intersection(GETTER_METHOD_MATCHER);
assertEquals(pc1, pc2); assertThat(pc2).isEqualTo(pc1);
assertEquals(pc1.hashCode(), pc2.hashCode()); assertThat(pc2.hashCode()).isEqualTo(pc1.hashCode());
pc1.union(GET_AGE_METHOD_MATCHER); pc1.union(GET_AGE_METHOD_MATCHER);
pc2.union(GET_AGE_METHOD_MATCHER); pc2.union(GET_AGE_METHOD_MATCHER);
assertEquals(pc1, pc2); assertThat(pc2).isEqualTo(pc1);
assertEquals(pc1.hashCode(), pc2.hashCode()); assertThat(pc2.hashCode()).isEqualTo(pc1.hashCode());
} }
} }

View File

@ -24,8 +24,7 @@ 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.junit.Assert.assertEquals; import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertFalse;
/** /**
* @author Rod Johnson * @author Rod Johnson
@ -44,17 +43,17 @@ public class ControlFlowPointcutTests {
pf.addAdvisor(new DefaultPointcutAdvisor(cflow, nop)); pf.addAdvisor(new DefaultPointcutAdvisor(cflow, nop));
// Not advised, not under One // Not advised, not under One
assertEquals(target.getAge(), proxied.getAge()); assertThat(proxied.getAge()).isEqualTo(target.getAge());
assertEquals(0, nop.getCount()); assertThat(nop.getCount()).isEqualTo(0);
// Will be advised // Will be advised
assertEquals(target.getAge(), new One().getAge(proxied)); assertThat(new One().getAge(proxied)).isEqualTo(target.getAge());
assertEquals(1, nop.getCount()); assertThat(nop.getCount()).isEqualTo(1);
// Won't be advised // Won't be advised
assertEquals(target.getAge(), new One().nomatch(proxied)); assertThat(new One().nomatch(proxied)).isEqualTo(target.getAge());
assertEquals(1, nop.getCount()); assertThat(nop.getCount()).isEqualTo(1);
assertEquals(3, cflow.getEvaluations()); assertThat(cflow.getEvaluations()).isEqualTo(3);
} }
/** /**
@ -77,28 +76,28 @@ public class ControlFlowPointcutTests {
// Not advised, not under One // Not advised, not under One
target.setAge(16); target.setAge(16);
assertEquals(0, nop.getCount()); assertThat(nop.getCount()).isEqualTo(0);
// Not advised; under One but not a setter // Not advised; under One but not a setter
assertEquals(16, new One().getAge(proxied)); assertThat(new One().getAge(proxied)).isEqualTo(16);
assertEquals(0, nop.getCount()); assertThat(nop.getCount()).isEqualTo(0);
// Won't be advised // Won't be advised
new One().set(proxied); new One().set(proxied);
assertEquals(1, nop.getCount()); assertThat(nop.getCount()).isEqualTo(1);
// We saved most evaluations // We saved most evaluations
assertEquals(1, cflow.getEvaluations()); assertThat(cflow.getEvaluations()).isEqualTo(1);
} }
@Test @Test
public void testEqualsAndHashCode() throws Exception { public void testEqualsAndHashCode() throws Exception {
assertEquals(new ControlFlowPointcut(One.class), new ControlFlowPointcut(One.class)); assertThat(new ControlFlowPointcut(One.class)).isEqualTo(new ControlFlowPointcut(One.class));
assertEquals(new ControlFlowPointcut(One.class, "getAge"), new ControlFlowPointcut(One.class, "getAge")); assertThat(new ControlFlowPointcut(One.class, "getAge")).isEqualTo(new ControlFlowPointcut(One.class, "getAge"));
assertFalse(new ControlFlowPointcut(One.class, "getAge").equals(new ControlFlowPointcut(One.class))); assertThat(new ControlFlowPointcut(One.class, "getAge").equals(new ControlFlowPointcut(One.class))).isFalse();
assertEquals(new ControlFlowPointcut(One.class).hashCode(), new ControlFlowPointcut(One.class).hashCode()); assertThat(new ControlFlowPointcut(One.class).hashCode()).isEqualTo(new ControlFlowPointcut(One.class).hashCode());
assertEquals(new ControlFlowPointcut(One.class, "getAge").hashCode(), new ControlFlowPointcut(One.class, "getAge").hashCode()); assertThat(new ControlFlowPointcut(One.class, "getAge").hashCode()).isEqualTo(new ControlFlowPointcut(One.class, "getAge").hashCode());
assertFalse(new ControlFlowPointcut(One.class, "getAge").hashCode() == new ControlFlowPointcut(One.class).hashCode()); assertThat(new ControlFlowPointcut(One.class, "getAge").hashCode() == new ControlFlowPointcut(One.class).hashCode()).isFalse();
} }
public class One { public class One {

View File

@ -36,9 +36,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.assertThatIllegalArgumentException; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import static org.mockito.BDDMockito.given; import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
@ -59,7 +56,7 @@ public class DelegatingIntroductionInterceptorTests {
@Test @Test
public void testIntroductionInterceptorWithDelegation() throws Exception { public void testIntroductionInterceptorWithDelegation() throws Exception {
TestBean raw = new TestBean(); TestBean raw = new TestBean();
assertTrue(! (raw instanceof TimeStamped)); assertThat(! (raw instanceof TimeStamped)).isTrue();
ProxyFactory factory = new ProxyFactory(raw); ProxyFactory factory = new ProxyFactory(raw);
TimeStamped ts = mock(TimeStamped.class); TimeStamped ts = mock(TimeStamped.class);
@ -69,13 +66,13 @@ public class DelegatingIntroductionInterceptorTests {
factory.addAdvisor(0, new DefaultIntroductionAdvisor(new DelegatingIntroductionInterceptor(ts))); factory.addAdvisor(0, new DefaultIntroductionAdvisor(new DelegatingIntroductionInterceptor(ts)));
TimeStamped tsp = (TimeStamped) factory.getProxy(); TimeStamped tsp = (TimeStamped) factory.getProxy();
assertTrue(tsp.getTimeStamp() == timestamp); assertThat(tsp.getTimeStamp() == timestamp).isTrue();
} }
@Test @Test
public void testIntroductionInterceptorWithInterfaceHierarchy() throws Exception { public void testIntroductionInterceptorWithInterfaceHierarchy() throws Exception {
TestBean raw = new TestBean(); TestBean raw = new TestBean();
assertTrue(! (raw instanceof SubTimeStamped)); assertThat(! (raw instanceof SubTimeStamped)).isTrue();
ProxyFactory factory = new ProxyFactory(raw); ProxyFactory factory = new ProxyFactory(raw);
TimeStamped ts = mock(SubTimeStamped.class); TimeStamped ts = mock(SubTimeStamped.class);
@ -85,13 +82,13 @@ public class DelegatingIntroductionInterceptorTests {
factory.addAdvisor(0, new DefaultIntroductionAdvisor(new DelegatingIntroductionInterceptor(ts), SubTimeStamped.class)); factory.addAdvisor(0, new DefaultIntroductionAdvisor(new DelegatingIntroductionInterceptor(ts), SubTimeStamped.class));
SubTimeStamped tsp = (SubTimeStamped) factory.getProxy(); SubTimeStamped tsp = (SubTimeStamped) factory.getProxy();
assertTrue(tsp.getTimeStamp() == timestamp); assertThat(tsp.getTimeStamp() == timestamp).isTrue();
} }
@Test @Test
public void testIntroductionInterceptorWithSuperInterface() throws Exception { public void testIntroductionInterceptorWithSuperInterface() throws Exception {
TestBean raw = new TestBean(); TestBean raw = new TestBean();
assertTrue(! (raw instanceof TimeStamped)); assertThat(! (raw instanceof TimeStamped)).isTrue();
ProxyFactory factory = new ProxyFactory(raw); ProxyFactory factory = new ProxyFactory(raw);
TimeStamped ts = mock(SubTimeStamped.class); TimeStamped ts = mock(SubTimeStamped.class);
@ -101,8 +98,8 @@ public class DelegatingIntroductionInterceptorTests {
factory.addAdvisor(0, new DefaultIntroductionAdvisor(new DelegatingIntroductionInterceptor(ts), TimeStamped.class)); factory.addAdvisor(0, new DefaultIntroductionAdvisor(new DelegatingIntroductionInterceptor(ts), TimeStamped.class));
TimeStamped tsp = (TimeStamped) factory.getProxy(); TimeStamped tsp = (TimeStamped) factory.getProxy();
assertTrue(!(tsp instanceof SubTimeStamped)); assertThat(!(tsp instanceof SubTimeStamped)).isTrue();
assertTrue(tsp.getTimeStamp() == timestamp); assertThat(tsp.getTimeStamp() == timestamp).isTrue();
} }
@Test @Test
@ -128,7 +125,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();
assertTrue(ts.getTimeStamp() == t); assertThat(ts.getTimeStamp() == t).isTrue();
((ITester) ts).foo(); ((ITester) ts).foo();
((ITestBean) ts).getAge(); ((ITestBean) ts).getAge();
@ -155,7 +152,7 @@ public class DelegatingIntroductionInterceptorTests {
ProxyFactory pf = new ProxyFactory(target); ProxyFactory pf = new ProxyFactory(target);
IntroductionAdvisor ia = new DefaultIntroductionAdvisor(ii); IntroductionAdvisor ia = new DefaultIntroductionAdvisor(ii);
assertTrue(ia.isPerInstance()); assertThat(ia.isPerInstance()).isTrue();
pf.addAdvisor(0, ia); pf.addAdvisor(0, ia);
//assertTrue(Arrays.binarySearch(pf.getProxiedInterfaces(), TimeStamped.class) != -1); //assertTrue(Arrays.binarySearch(pf.getProxiedInterfaces(), TimeStamped.class) != -1);
@ -163,10 +160,10 @@ public class DelegatingIntroductionInterceptorTests {
assertThat(ts).isInstanceOf(TimeStamped.class); assertThat(ts).isInstanceOf(TimeStamped.class);
// Shouldn't proxy framework interfaces // Shouldn't proxy framework interfaces
assertTrue(!(ts instanceof MethodInterceptor)); assertThat(!(ts instanceof MethodInterceptor)).isTrue();
assertTrue(!(ts instanceof IntroductionInterceptor)); assertThat(!(ts instanceof IntroductionInterceptor)).isTrue();
assertTrue(ts.getTimeStamp() == t); assertThat(ts.getTimeStamp() == t).isTrue();
((ITester) ts).foo(); ((ITester) ts).foo();
((ITestBean) ts).getAge(); ((ITestBean) ts).getAge();
@ -177,14 +174,14 @@ public class DelegatingIntroductionInterceptorTests {
pf = new ProxyFactory(target); pf = new ProxyFactory(target);
pf.addAdvisor(0, new DefaultIntroductionAdvisor(ii)); pf.addAdvisor(0, new DefaultIntroductionAdvisor(ii));
Object o = pf.getProxy(); Object o = pf.getProxy();
assertTrue(!(o instanceof TimeStamped)); assertThat(!(o instanceof TimeStamped)).isTrue();
} }
@SuppressWarnings("serial") @SuppressWarnings("serial")
@Test @Test
public void testIntroductionInterceptorDoesntReplaceToString() throws Exception { public void testIntroductionInterceptorDoesntReplaceToString() throws Exception {
TestBean raw = new TestBean(); TestBean raw = new TestBean();
assertTrue(! (raw instanceof TimeStamped)); assertThat(! (raw instanceof TimeStamped)).isTrue();
ProxyFactory factory = new ProxyFactory(raw); ProxyFactory factory = new ProxyFactory(raw);
TimeStamped ts = new SerializableTimeStamped(0); TimeStamped ts = new SerializableTimeStamped(0);
@ -197,9 +194,9 @@ public class DelegatingIntroductionInterceptorTests {
})); }));
TimeStamped tsp = (TimeStamped) factory.getProxy(); TimeStamped tsp = (TimeStamped) factory.getProxy();
assertEquals(0, tsp.getTimeStamp()); assertThat(tsp.getTimeStamp()).isEqualTo(0);
assertEquals(raw.toString(), tsp.toString()); assertThat(tsp.toString()).isEqualTo(raw.toString());
} }
@Test @Test
@ -217,10 +214,10 @@ public class DelegatingIntroductionInterceptorTests {
pf.addAdvice(new DelegatingIntroductionInterceptor(delegate)); pf.addAdvice(new DelegatingIntroductionInterceptor(delegate));
INestedTestBean proxy = (INestedTestBean) pf.getProxy(); INestedTestBean proxy = (INestedTestBean) pf.getProxy();
assertEquals(company, proxy.getCompany()); assertThat(proxy.getCompany()).isEqualTo(company);
ITestBean introduction = (ITestBean) proxy; ITestBean introduction = (ITestBean) proxy;
assertSame("Introduced method returning delegate returns proxy", introduction, introduction.getSpouse()); assertThat(introduction.getSpouse()).as("Introduced method returning delegate returns proxy").isSameAs(introduction);
assertTrue("Introduced method returning delegate returns proxy", AopUtils.isAopProxy(introduction.getSpouse())); assertThat(AopUtils.isAopProxy(introduction.getSpouse())).as("Introduced method returning delegate returns proxy").isTrue();
} }
@Test @Test
@ -239,12 +236,12 @@ public class DelegatingIntroductionInterceptorTests {
Person p = (Person) factory.getProxy(); Person p = (Person) factory.getProxy();
assertEquals(name, p.getName()); assertThat(p.getName()).isEqualTo(name);
assertEquals(time, ((TimeStamped) p).getTimeStamp()); assertThat(((TimeStamped) p).getTimeStamp()).isEqualTo(time);
Person p1 = (Person) SerializationTestUtils.serializeAndDeserialize(p); Person p1 = (Person) SerializationTestUtils.serializeAndDeserialize(p);
assertEquals(name, p1.getName()); assertThat(p1.getName()).isEqualTo(name);
assertEquals(time, ((TimeStamped) p1).getTimeStamp()); assertThat(((TimeStamped) p1).getTimeStamp()).isEqualTo(time);
} }
// Test when target implements the interface: should get interceptor by preference. // Test when target implements the interface: should get interceptor by preference.
@ -269,7 +266,7 @@ public class DelegatingIntroductionInterceptorTests {
TimeStamped ts = (TimeStamped) pf.getProxy(); TimeStamped ts = (TimeStamped) pf.getProxy();
// From introduction interceptor, not target // From introduction interceptor, not target
assertTrue(ts.getTimeStamp() == t); assertThat(ts.getTimeStamp() == t).isTrue();
} }

View File

@ -27,9 +27,7 @@ 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.SerializationTestUtils; import org.springframework.util.SerializationTestUtils;
import static org.junit.Assert.assertFalse; import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
/** /**
* @author Juergen Hoeller * @author Juergen Hoeller
@ -57,24 +55,24 @@ public class MethodMatchersTests {
@Test @Test
public void testDefaultMatchesAll() throws Exception { public void testDefaultMatchesAll() throws Exception {
MethodMatcher defaultMm = MethodMatcher.TRUE; MethodMatcher defaultMm = MethodMatcher.TRUE;
assertTrue(defaultMm.matches(EXCEPTION_GETMESSAGE, Exception.class)); assertThat(defaultMm.matches(EXCEPTION_GETMESSAGE, Exception.class)).isTrue();
assertTrue(defaultMm.matches(ITESTBEAN_SETAGE, TestBean.class)); assertThat(defaultMm.matches(ITESTBEAN_SETAGE, TestBean.class)).isTrue();
} }
@Test @Test
public void testMethodMatcherTrueSerializable() throws Exception { public void testMethodMatcherTrueSerializable() throws Exception {
assertSame(SerializationTestUtils.serializeAndDeserialize(MethodMatcher.TRUE), MethodMatcher.TRUE); assertThat(MethodMatcher.TRUE).isSameAs(SerializationTestUtils.serializeAndDeserialize(MethodMatcher.TRUE));
} }
@Test @Test
public void testSingle() throws Exception { public void testSingle() throws Exception {
MethodMatcher defaultMm = MethodMatcher.TRUE; MethodMatcher defaultMm = MethodMatcher.TRUE;
assertTrue(defaultMm.matches(EXCEPTION_GETMESSAGE, Exception.class)); assertThat(defaultMm.matches(EXCEPTION_GETMESSAGE, Exception.class)).isTrue();
assertTrue(defaultMm.matches(ITESTBEAN_SETAGE, TestBean.class)); assertThat(defaultMm.matches(ITESTBEAN_SETAGE, TestBean.class)).isTrue();
defaultMm = MethodMatchers.intersection(defaultMm, new StartsWithMatcher("get")); defaultMm = MethodMatchers.intersection(defaultMm, new StartsWithMatcher("get"));
assertTrue(defaultMm.matches(EXCEPTION_GETMESSAGE, Exception.class)); assertThat(defaultMm.matches(EXCEPTION_GETMESSAGE, Exception.class)).isTrue();
assertFalse(defaultMm.matches(ITESTBEAN_SETAGE, TestBean.class)); assertThat(defaultMm.matches(ITESTBEAN_SETAGE, TestBean.class)).isFalse();
} }
@ -83,14 +81,14 @@ public class MethodMatchersTests {
MethodMatcher mm1 = MethodMatcher.TRUE; MethodMatcher mm1 = MethodMatcher.TRUE;
MethodMatcher mm2 = new TestDynamicMethodMatcherWhichMatches(); MethodMatcher mm2 = new TestDynamicMethodMatcherWhichMatches();
MethodMatcher intersection = MethodMatchers.intersection(mm1, mm2); MethodMatcher intersection = MethodMatchers.intersection(mm1, mm2);
assertTrue("Intersection is a dynamic matcher", intersection.isRuntime()); assertThat(intersection.isRuntime()).as("Intersection is a dynamic matcher").isTrue();
assertTrue("2Matched setAge method", intersection.matches(ITESTBEAN_SETAGE, TestBean.class)); assertThat(intersection.matches(ITESTBEAN_SETAGE, TestBean.class)).as("2Matched setAge method").isTrue();
assertTrue("3Matched setAge method", intersection.matches(ITESTBEAN_SETAGE, TestBean.class, new Integer(5))); assertThat(intersection.matches(ITESTBEAN_SETAGE, TestBean.class, new Integer(5))).as("3Matched setAge method").isTrue();
// Knock out dynamic part // Knock out dynamic part
intersection = MethodMatchers.intersection(intersection, new TestDynamicMethodMatcherWhichDoesNotMatch()); intersection = MethodMatchers.intersection(intersection, new TestDynamicMethodMatcherWhichDoesNotMatch());
assertTrue("Intersection is a dynamic matcher", intersection.isRuntime()); assertThat(intersection.isRuntime()).as("Intersection is a dynamic matcher").isTrue();
assertTrue("2Matched setAge method", intersection.matches(ITESTBEAN_SETAGE, TestBean.class)); assertThat(intersection.matches(ITESTBEAN_SETAGE, TestBean.class)).as("2Matched setAge method").isTrue();
assertFalse("3 - not Matched setAge method", intersection.matches(ITESTBEAN_SETAGE, TestBean.class, new Integer(5))); assertThat(intersection.matches(ITESTBEAN_SETAGE, TestBean.class, new Integer(5))).as("3 - not Matched setAge method").isFalse();
} }
@Test @Test
@ -99,18 +97,18 @@ public class MethodMatchersTests {
MethodMatcher setterMatcher = new StartsWithMatcher("set"); MethodMatcher setterMatcher = new StartsWithMatcher("set");
MethodMatcher union = MethodMatchers.union(getterMatcher, setterMatcher); MethodMatcher union = MethodMatchers.union(getterMatcher, setterMatcher);
assertFalse("Union is a static matcher", union.isRuntime()); assertThat(union.isRuntime()).as("Union is a static matcher").isFalse();
assertTrue("Matched setAge method", union.matches(ITESTBEAN_SETAGE, TestBean.class)); assertThat(union.matches(ITESTBEAN_SETAGE, TestBean.class)).as("Matched setAge method").isTrue();
assertTrue("Matched getAge method", union.matches(ITESTBEAN_GETAGE, TestBean.class)); assertThat(union.matches(ITESTBEAN_GETAGE, TestBean.class)).as("Matched getAge method").isTrue();
assertFalse("Didn't matched absquatulate method", union.matches(IOTHER_ABSQUATULATE, TestBean.class)); assertThat(union.matches(IOTHER_ABSQUATULATE, TestBean.class)).as("Didn't matched absquatulate method").isFalse();
} }
@Test @Test
public void testUnionEquals() { public void testUnionEquals() {
MethodMatcher first = MethodMatchers.union(MethodMatcher.TRUE, MethodMatcher.TRUE); MethodMatcher first = MethodMatchers.union(MethodMatcher.TRUE, MethodMatcher.TRUE);
MethodMatcher second = new ComposablePointcut(MethodMatcher.TRUE).union(new ComposablePointcut(MethodMatcher.TRUE)).getMethodMatcher(); MethodMatcher second = new ComposablePointcut(MethodMatcher.TRUE).union(new ComposablePointcut(MethodMatcher.TRUE)).getMethodMatcher();
assertTrue(first.equals(second)); assertThat(first.equals(second)).isTrue();
assertTrue(second.equals(first)); assertThat(second.equals(first)).isTrue();
} }

View File

@ -27,9 +27,7 @@ import org.springframework.tests.sample.beans.Person;
import org.springframework.tests.sample.beans.SerializablePerson; import org.springframework.tests.sample.beans.SerializablePerson;
import org.springframework.util.SerializationTestUtils; import org.springframework.util.SerializationTestUtils;
import static org.junit.Assert.assertEquals; import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
/** /**
* @author Rod Johnson * @author Rod Johnson
@ -60,21 +58,21 @@ public class NameMatchMethodPointcutTests {
@Test @Test
public void testMatchingOnly() { public void testMatchingOnly() {
// Can't do exact matching through isMatch // Can't do exact matching through isMatch
assertTrue(pc.isMatch("echo", "ech*")); assertThat(pc.isMatch("echo", "ech*")).isTrue();
assertTrue(pc.isMatch("setName", "setN*")); assertThat(pc.isMatch("setName", "setN*")).isTrue();
assertTrue(pc.isMatch("setName", "set*")); assertThat(pc.isMatch("setName", "set*")).isTrue();
assertFalse(pc.isMatch("getName", "set*")); assertThat(pc.isMatch("getName", "set*")).isFalse();
assertFalse(pc.isMatch("setName", "set")); assertThat(pc.isMatch("setName", "set")).isFalse();
assertTrue(pc.isMatch("testing", "*ing")); assertThat(pc.isMatch("testing", "*ing")).isTrue();
} }
@Test @Test
public void testEmpty() throws Throwable { public void testEmpty() throws Throwable {
assertEquals(0, nop.getCount()); assertThat(nop.getCount()).isEqualTo(0);
proxied.getName(); proxied.getName();
proxied.setName(""); proxied.setName("");
proxied.echo(null); proxied.echo(null);
assertEquals(0, nop.getCount()); assertThat(nop.getCount()).isEqualTo(0);
} }
@ -82,29 +80,29 @@ public class NameMatchMethodPointcutTests {
public void testMatchOneMethod() throws Throwable { public void testMatchOneMethod() throws Throwable {
pc.addMethodName("echo"); pc.addMethodName("echo");
pc.addMethodName("set*"); pc.addMethodName("set*");
assertEquals(0, nop.getCount()); assertThat(nop.getCount()).isEqualTo(0);
proxied.getName(); proxied.getName();
proxied.getName(); proxied.getName();
assertEquals(0, nop.getCount()); assertThat(nop.getCount()).isEqualTo(0);
proxied.echo(null); proxied.echo(null);
assertEquals(1, nop.getCount()); assertThat(nop.getCount()).isEqualTo(1);
proxied.setName(""); proxied.setName("");
assertEquals(2, nop.getCount()); assertThat(nop.getCount()).isEqualTo(2);
proxied.setAge(25); proxied.setAge(25);
assertEquals(25, proxied.getAge()); assertThat(proxied.getAge()).isEqualTo(25);
assertEquals(3, nop.getCount()); assertThat(nop.getCount()).isEqualTo(3);
} }
@Test @Test
public void testSets() throws Throwable { public void testSets() throws Throwable {
pc.setMappedNames("set*", "echo"); pc.setMappedNames("set*", "echo");
assertEquals(0, nop.getCount()); assertThat(nop.getCount()).isEqualTo(0);
proxied.getName(); proxied.getName();
proxied.setName(""); proxied.setName("");
assertEquals(1, nop.getCount()); assertThat(nop.getCount()).isEqualTo(1);
proxied.echo(null); proxied.echo(null);
assertEquals(2, nop.getCount()); assertThat(nop.getCount()).isEqualTo(2);
} }
@Test @Test
@ -114,9 +112,9 @@ public class NameMatchMethodPointcutTests {
Person p2 = (Person) SerializationTestUtils.serializeAndDeserialize(proxied); Person p2 = (Person) SerializationTestUtils.serializeAndDeserialize(proxied);
NopInterceptor nop2 = (NopInterceptor) ((Advised) p2).getAdvisors()[0].getAdvice(); NopInterceptor nop2 = (NopInterceptor) ((Advised) p2).getAdvisors()[0].getAdvice();
p2.getName(); p2.getName();
assertEquals(2, nop2.getCount()); assertThat(nop2.getCount()).isEqualTo(2);
p2.echo(null); p2.echo(null);
assertEquals(3, nop2.getCount()); assertThat(nop2.getCount()).isEqualTo(3);
} }
@Test @Test
@ -126,16 +124,16 @@ public class NameMatchMethodPointcutTests {
String foo = "foo"; String foo = "foo";
assertEquals(pc1, pc2); assertThat(pc2).isEqualTo(pc1);
assertEquals(pc1.hashCode(), pc2.hashCode()); assertThat(pc2.hashCode()).isEqualTo(pc1.hashCode());
pc1.setMappedName(foo); pc1.setMappedName(foo);
assertFalse(pc1.equals(pc2)); assertThat(pc1.equals(pc2)).isFalse();
assertTrue(pc1.hashCode() != pc2.hashCode()); assertThat(pc1.hashCode() != pc2.hashCode()).isTrue();
pc2.setMappedName(foo); pc2.setMappedName(foo);
assertEquals(pc1, pc2); assertThat(pc2).isEqualTo(pc1);
assertEquals(pc1.hashCode(), pc2.hashCode()); assertThat(pc2.hashCode()).isEqualTo(pc1.hashCode());
} }
} }

View File

@ -25,8 +25,7 @@ import org.springframework.aop.Pointcut;
import org.springframework.lang.Nullable; import org.springframework.lang.Nullable;
import org.springframework.tests.sample.beans.TestBean; import org.springframework.tests.sample.beans.TestBean;
import static org.junit.Assert.assertFalse; import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertTrue;
/** /**
* @author Rod Johnson * @author Rod Johnson
@ -127,22 +126,22 @@ public class PointcutsTests {
@Test @Test
public void testTrue() { public void testTrue() {
assertTrue(Pointcuts.matches(Pointcut.TRUE, TEST_BEAN_SET_AGE, TestBean.class, new Integer(6))); assertThat(Pointcuts.matches(Pointcut.TRUE, TEST_BEAN_SET_AGE, TestBean.class, new Integer(6))).isTrue();
assertTrue(Pointcuts.matches(Pointcut.TRUE, TEST_BEAN_GET_AGE, TestBean.class)); assertThat(Pointcuts.matches(Pointcut.TRUE, TEST_BEAN_GET_AGE, TestBean.class)).isTrue();
assertTrue(Pointcuts.matches(Pointcut.TRUE, TEST_BEAN_ABSQUATULATE, TestBean.class)); assertThat(Pointcuts.matches(Pointcut.TRUE, TEST_BEAN_ABSQUATULATE, TestBean.class)).isTrue();
assertTrue(Pointcuts.matches(Pointcut.TRUE, TEST_BEAN_SET_AGE, TestBean.class, new Integer(6))); assertThat(Pointcuts.matches(Pointcut.TRUE, TEST_BEAN_SET_AGE, TestBean.class, new Integer(6))).isTrue();
assertTrue(Pointcuts.matches(Pointcut.TRUE, TEST_BEAN_GET_AGE, TestBean.class)); assertThat(Pointcuts.matches(Pointcut.TRUE, TEST_BEAN_GET_AGE, TestBean.class)).isTrue();
assertTrue(Pointcuts.matches(Pointcut.TRUE, TEST_BEAN_ABSQUATULATE, TestBean.class)); assertThat(Pointcuts.matches(Pointcut.TRUE, TEST_BEAN_ABSQUATULATE, TestBean.class)).isTrue();
} }
@Test @Test
public void testMatches() { public void testMatches() {
assertTrue(Pointcuts.matches(allClassSetterPointcut, TEST_BEAN_SET_AGE, TestBean.class, new Integer(6))); assertThat(Pointcuts.matches(allClassSetterPointcut, TEST_BEAN_SET_AGE, TestBean.class, new Integer(6))).isTrue();
assertFalse(Pointcuts.matches(allClassSetterPointcut, TEST_BEAN_GET_AGE, TestBean.class)); assertThat(Pointcuts.matches(allClassSetterPointcut, TEST_BEAN_GET_AGE, TestBean.class)).isFalse();
assertFalse(Pointcuts.matches(allClassSetterPointcut, TEST_BEAN_ABSQUATULATE, TestBean.class)); assertThat(Pointcuts.matches(allClassSetterPointcut, TEST_BEAN_ABSQUATULATE, TestBean.class)).isFalse();
assertFalse(Pointcuts.matches(allClassGetterPointcut, TEST_BEAN_SET_AGE, TestBean.class, new Integer(6))); assertThat(Pointcuts.matches(allClassGetterPointcut, TEST_BEAN_SET_AGE, TestBean.class, new Integer(6))).isFalse();
assertTrue(Pointcuts.matches(allClassGetterPointcut, TEST_BEAN_GET_AGE, TestBean.class)); assertThat(Pointcuts.matches(allClassGetterPointcut, TEST_BEAN_GET_AGE, TestBean.class)).isTrue();
assertFalse(Pointcuts.matches(allClassGetterPointcut, TEST_BEAN_ABSQUATULATE, TestBean.class)); assertThat(Pointcuts.matches(allClassGetterPointcut, TEST_BEAN_ABSQUATULATE, TestBean.class)).isFalse();
} }
/** /**
@ -151,29 +150,29 @@ public class PointcutsTests {
@Test @Test
public void testUnionOfSettersAndGetters() { public void testUnionOfSettersAndGetters() {
Pointcut union = Pointcuts.union(allClassGetterPointcut, allClassSetterPointcut); Pointcut union = Pointcuts.union(allClassGetterPointcut, allClassSetterPointcut);
assertTrue(Pointcuts.matches(union, TEST_BEAN_SET_AGE, TestBean.class, new Integer(6))); assertThat(Pointcuts.matches(union, TEST_BEAN_SET_AGE, TestBean.class, new Integer(6))).isTrue();
assertTrue(Pointcuts.matches(union, TEST_BEAN_GET_AGE, TestBean.class)); assertThat(Pointcuts.matches(union, TEST_BEAN_GET_AGE, TestBean.class)).isTrue();
assertFalse(Pointcuts.matches(union, TEST_BEAN_ABSQUATULATE, TestBean.class)); assertThat(Pointcuts.matches(union, TEST_BEAN_ABSQUATULATE, TestBean.class)).isFalse();
} }
@Test @Test
public void testUnionOfSpecificGetters() { public void testUnionOfSpecificGetters() {
Pointcut union = Pointcuts.union(allClassGetAgePointcut, allClassGetNamePointcut); Pointcut union = Pointcuts.union(allClassGetAgePointcut, allClassGetNamePointcut);
assertFalse(Pointcuts.matches(union, TEST_BEAN_SET_AGE, TestBean.class, new Integer(6))); assertThat(Pointcuts.matches(union, TEST_BEAN_SET_AGE, TestBean.class, new Integer(6))).isFalse();
assertTrue(Pointcuts.matches(union, TEST_BEAN_GET_AGE, TestBean.class)); assertThat(Pointcuts.matches(union, TEST_BEAN_GET_AGE, TestBean.class)).isTrue();
assertFalse(Pointcuts.matches(allClassGetAgePointcut, TEST_BEAN_GET_NAME, TestBean.class)); assertThat(Pointcuts.matches(allClassGetAgePointcut, TEST_BEAN_GET_NAME, TestBean.class)).isFalse();
assertTrue(Pointcuts.matches(union, TEST_BEAN_GET_NAME, TestBean.class)); assertThat(Pointcuts.matches(union, TEST_BEAN_GET_NAME, TestBean.class)).isTrue();
assertFalse(Pointcuts.matches(union, TEST_BEAN_ABSQUATULATE, TestBean.class)); assertThat(Pointcuts.matches(union, TEST_BEAN_ABSQUATULATE, TestBean.class)).isFalse();
// Union with all setters // Union with all setters
union = Pointcuts.union(union, allClassSetterPointcut); union = Pointcuts.union(union, allClassSetterPointcut);
assertTrue(Pointcuts.matches(union, TEST_BEAN_SET_AGE, TestBean.class, new Integer(6))); assertThat(Pointcuts.matches(union, TEST_BEAN_SET_AGE, TestBean.class, new Integer(6))).isTrue();
assertTrue(Pointcuts.matches(union, TEST_BEAN_GET_AGE, TestBean.class)); assertThat(Pointcuts.matches(union, TEST_BEAN_GET_AGE, TestBean.class)).isTrue();
assertFalse(Pointcuts.matches(allClassGetAgePointcut, TEST_BEAN_GET_NAME, TestBean.class)); assertThat(Pointcuts.matches(allClassGetAgePointcut, TEST_BEAN_GET_NAME, TestBean.class)).isFalse();
assertTrue(Pointcuts.matches(union, TEST_BEAN_GET_NAME, TestBean.class)); assertThat(Pointcuts.matches(union, TEST_BEAN_GET_NAME, TestBean.class)).isTrue();
assertFalse(Pointcuts.matches(union, TEST_BEAN_ABSQUATULATE, TestBean.class)); assertThat(Pointcuts.matches(union, TEST_BEAN_ABSQUATULATE, TestBean.class)).isFalse();
assertTrue(Pointcuts.matches(union, TEST_BEAN_SET_AGE, TestBean.class, new Integer(6))); assertThat(Pointcuts.matches(union, TEST_BEAN_SET_AGE, TestBean.class, new Integer(6))).isTrue();
} }
/** /**
@ -182,16 +181,16 @@ public class PointcutsTests {
*/ */
@Test @Test
public void testUnionOfAllSettersAndSubclassSetters() { public void testUnionOfAllSettersAndSubclassSetters() {
assertFalse(Pointcuts.matches(myTestBeanSetterPointcut, TEST_BEAN_SET_AGE, TestBean.class, new Integer(6))); assertThat(Pointcuts.matches(myTestBeanSetterPointcut, TEST_BEAN_SET_AGE, TestBean.class, new Integer(6))).isFalse();
assertTrue(Pointcuts.matches(myTestBeanSetterPointcut, TEST_BEAN_SET_AGE, MyTestBean.class, new Integer(6))); assertThat(Pointcuts.matches(myTestBeanSetterPointcut, TEST_BEAN_SET_AGE, MyTestBean.class, new Integer(6))).isTrue();
assertFalse(Pointcuts.matches(myTestBeanSetterPointcut, TEST_BEAN_GET_AGE, TestBean.class)); assertThat(Pointcuts.matches(myTestBeanSetterPointcut, TEST_BEAN_GET_AGE, TestBean.class)).isFalse();
Pointcut union = Pointcuts.union(myTestBeanSetterPointcut, allClassGetterPointcut); Pointcut union = Pointcuts.union(myTestBeanSetterPointcut, allClassGetterPointcut);
assertTrue(Pointcuts.matches(union, TEST_BEAN_GET_AGE, TestBean.class)); assertThat(Pointcuts.matches(union, TEST_BEAN_GET_AGE, TestBean.class)).isTrue();
assertTrue(Pointcuts.matches(union, TEST_BEAN_GET_AGE, MyTestBean.class)); assertThat(Pointcuts.matches(union, TEST_BEAN_GET_AGE, MyTestBean.class)).isTrue();
// Still doesn't match superclass setter // Still doesn't match superclass setter
assertTrue(Pointcuts.matches(union, TEST_BEAN_SET_AGE, MyTestBean.class, new Integer(6))); assertThat(Pointcuts.matches(union, TEST_BEAN_SET_AGE, MyTestBean.class, new Integer(6))).isTrue();
assertFalse(Pointcuts.matches(union, TEST_BEAN_SET_AGE, TestBean.class, new Integer(6))); assertThat(Pointcuts.matches(union, TEST_BEAN_SET_AGE, TestBean.class, new Integer(6))).isFalse();
} }
/** /**
@ -200,44 +199,44 @@ public class PointcutsTests {
*/ */
@Test @Test
public void testIntersectionOfSpecificGettersAndSubclassGetters() { public void testIntersectionOfSpecificGettersAndSubclassGetters() {
assertTrue(Pointcuts.matches(allClassGetAgePointcut, TEST_BEAN_GET_AGE, TestBean.class)); assertThat(Pointcuts.matches(allClassGetAgePointcut, TEST_BEAN_GET_AGE, TestBean.class)).isTrue();
assertTrue(Pointcuts.matches(allClassGetAgePointcut, TEST_BEAN_GET_AGE, MyTestBean.class)); assertThat(Pointcuts.matches(allClassGetAgePointcut, TEST_BEAN_GET_AGE, MyTestBean.class)).isTrue();
assertFalse(Pointcuts.matches(myTestBeanGetterPointcut, TEST_BEAN_GET_NAME, TestBean.class)); assertThat(Pointcuts.matches(myTestBeanGetterPointcut, TEST_BEAN_GET_NAME, TestBean.class)).isFalse();
assertFalse(Pointcuts.matches(myTestBeanGetterPointcut, TEST_BEAN_GET_AGE, TestBean.class)); assertThat(Pointcuts.matches(myTestBeanGetterPointcut, TEST_BEAN_GET_AGE, TestBean.class)).isFalse();
assertTrue(Pointcuts.matches(myTestBeanGetterPointcut, TEST_BEAN_GET_NAME, MyTestBean.class)); assertThat(Pointcuts.matches(myTestBeanGetterPointcut, TEST_BEAN_GET_NAME, MyTestBean.class)).isTrue();
assertTrue(Pointcuts.matches(myTestBeanGetterPointcut, TEST_BEAN_GET_AGE, MyTestBean.class)); assertThat(Pointcuts.matches(myTestBeanGetterPointcut, TEST_BEAN_GET_AGE, MyTestBean.class)).isTrue();
Pointcut intersection = Pointcuts.intersection(allClassGetAgePointcut, myTestBeanGetterPointcut); Pointcut intersection = Pointcuts.intersection(allClassGetAgePointcut, myTestBeanGetterPointcut);
assertFalse(Pointcuts.matches(intersection, TEST_BEAN_GET_NAME, TestBean.class)); assertThat(Pointcuts.matches(intersection, TEST_BEAN_GET_NAME, TestBean.class)).isFalse();
assertFalse(Pointcuts.matches(intersection, TEST_BEAN_GET_AGE, TestBean.class)); assertThat(Pointcuts.matches(intersection, TEST_BEAN_GET_AGE, TestBean.class)).isFalse();
assertFalse(Pointcuts.matches(intersection, TEST_BEAN_GET_NAME, MyTestBean.class)); assertThat(Pointcuts.matches(intersection, TEST_BEAN_GET_NAME, MyTestBean.class)).isFalse();
assertTrue(Pointcuts.matches(intersection, TEST_BEAN_GET_AGE, MyTestBean.class)); assertThat(Pointcuts.matches(intersection, TEST_BEAN_GET_AGE, MyTestBean.class)).isTrue();
// Matches subclass of MyTestBean // Matches subclass of MyTestBean
assertFalse(Pointcuts.matches(intersection, TEST_BEAN_GET_NAME, MyTestBeanSubclass.class)); assertThat(Pointcuts.matches(intersection, TEST_BEAN_GET_NAME, MyTestBeanSubclass.class)).isFalse();
assertTrue(Pointcuts.matches(intersection, TEST_BEAN_GET_AGE, MyTestBeanSubclass.class)); assertThat(Pointcuts.matches(intersection, TEST_BEAN_GET_AGE, MyTestBeanSubclass.class)).isTrue();
// Now intersection with MyTestBeanSubclass getters should eliminate MyTestBean target // Now intersection with MyTestBeanSubclass getters should eliminate MyTestBean target
intersection = Pointcuts.intersection(intersection, myTestBeanSubclassGetterPointcut); intersection = Pointcuts.intersection(intersection, myTestBeanSubclassGetterPointcut);
assertFalse(Pointcuts.matches(intersection, TEST_BEAN_GET_NAME, TestBean.class)); assertThat(Pointcuts.matches(intersection, TEST_BEAN_GET_NAME, TestBean.class)).isFalse();
assertFalse(Pointcuts.matches(intersection, TEST_BEAN_GET_AGE, TestBean.class)); assertThat(Pointcuts.matches(intersection, TEST_BEAN_GET_AGE, TestBean.class)).isFalse();
assertFalse(Pointcuts.matches(intersection, TEST_BEAN_GET_NAME, MyTestBean.class)); assertThat(Pointcuts.matches(intersection, TEST_BEAN_GET_NAME, MyTestBean.class)).isFalse();
assertFalse(Pointcuts.matches(intersection, TEST_BEAN_GET_AGE, MyTestBean.class)); assertThat(Pointcuts.matches(intersection, TEST_BEAN_GET_AGE, MyTestBean.class)).isFalse();
// Still matches subclass of MyTestBean // Still matches subclass of MyTestBean
assertFalse(Pointcuts.matches(intersection, TEST_BEAN_GET_NAME, MyTestBeanSubclass.class)); assertThat(Pointcuts.matches(intersection, TEST_BEAN_GET_NAME, MyTestBeanSubclass.class)).isFalse();
assertTrue(Pointcuts.matches(intersection, TEST_BEAN_GET_AGE, MyTestBeanSubclass.class)); assertThat(Pointcuts.matches(intersection, TEST_BEAN_GET_AGE, MyTestBeanSubclass.class)).isTrue();
// Now union with all TestBean methods // Now union with all TestBean methods
Pointcut union = Pointcuts.union(intersection, allTestBeanMethodsPointcut); Pointcut union = Pointcuts.union(intersection, allTestBeanMethodsPointcut);
assertTrue(Pointcuts.matches(union, TEST_BEAN_GET_NAME, TestBean.class)); assertThat(Pointcuts.matches(union, TEST_BEAN_GET_NAME, TestBean.class)).isTrue();
assertTrue(Pointcuts.matches(union, TEST_BEAN_GET_AGE, TestBean.class)); assertThat(Pointcuts.matches(union, TEST_BEAN_GET_AGE, TestBean.class)).isTrue();
assertFalse(Pointcuts.matches(union, TEST_BEAN_GET_NAME, MyTestBean.class)); assertThat(Pointcuts.matches(union, TEST_BEAN_GET_NAME, MyTestBean.class)).isFalse();
assertFalse(Pointcuts.matches(union, TEST_BEAN_GET_AGE, MyTestBean.class)); assertThat(Pointcuts.matches(union, TEST_BEAN_GET_AGE, MyTestBean.class)).isFalse();
// Still matches subclass of MyTestBean // Still matches subclass of MyTestBean
assertFalse(Pointcuts.matches(union, TEST_BEAN_GET_NAME, MyTestBeanSubclass.class)); assertThat(Pointcuts.matches(union, TEST_BEAN_GET_NAME, MyTestBeanSubclass.class)).isFalse();
assertTrue(Pointcuts.matches(union, TEST_BEAN_GET_AGE, MyTestBeanSubclass.class)); assertThat(Pointcuts.matches(union, TEST_BEAN_GET_AGE, MyTestBeanSubclass.class)).isTrue();
assertTrue(Pointcuts.matches(union, TEST_BEAN_ABSQUATULATE, TestBean.class)); assertThat(Pointcuts.matches(union, TEST_BEAN_ABSQUATULATE, TestBean.class)).isTrue();
assertFalse(Pointcuts.matches(union, TEST_BEAN_ABSQUATULATE, MyTestBean.class)); assertThat(Pointcuts.matches(union, TEST_BEAN_ABSQUATULATE, MyTestBean.class)).isFalse();
} }
@ -247,9 +246,9 @@ public class PointcutsTests {
@Test @Test
public void testSimpleIntersection() { public void testSimpleIntersection() {
Pointcut intersection = Pointcuts.intersection(allClassGetterPointcut, allClassSetterPointcut); Pointcut intersection = Pointcuts.intersection(allClassGetterPointcut, allClassSetterPointcut);
assertFalse(Pointcuts.matches(intersection, TEST_BEAN_SET_AGE, TestBean.class, new Integer(6))); assertThat(Pointcuts.matches(intersection, TEST_BEAN_SET_AGE, TestBean.class, new Integer(6))).isFalse();
assertFalse(Pointcuts.matches(intersection, TEST_BEAN_GET_AGE, TestBean.class)); assertThat(Pointcuts.matches(intersection, TEST_BEAN_GET_AGE, TestBean.class)).isFalse();
assertFalse(Pointcuts.matches(intersection, TEST_BEAN_ABSQUATULATE, TestBean.class)); assertThat(Pointcuts.matches(intersection, TEST_BEAN_ABSQUATULATE, TestBean.class)).isFalse();
} }
} }

View File

@ -29,7 +29,7 @@ import org.springframework.tests.sample.beans.Person;
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.junit.Assert.assertEquals; import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.tests.TestResourceUtils.qualifiedResource; import static org.springframework.tests.TestResourceUtils.qualifiedResource;
/** /**
@ -49,16 +49,16 @@ public class RegexpMethodPointcutAdvisorIntegrationTests {
ITestBean advised = (ITestBean) bf.getBean("settersAdvised"); ITestBean advised = (ITestBean) bf.getBean("settersAdvised");
// Interceptor behind regexp advisor // Interceptor behind regexp advisor
NopInterceptor nop = (NopInterceptor) bf.getBean("nopInterceptor"); NopInterceptor nop = (NopInterceptor) bf.getBean("nopInterceptor");
assertEquals(0, nop.getCount()); assertThat(nop.getCount()).isEqualTo(0);
int newAge = 12; int newAge = 12;
// Not advised // Not advised
advised.exceptional(null); advised.exceptional(null);
assertEquals(0, nop.getCount()); assertThat(nop.getCount()).isEqualTo(0);
advised.setAge(newAge); advised.setAge(newAge);
assertEquals(newAge, advised.getAge()); assertThat(advised.getAge()).isEqualTo(newAge);
// Only setter fired // Only setter fired
assertEquals(1, nop.getCount()); assertThat(nop.getCount()).isEqualTo(1);
} }
@Test @Test
@ -69,20 +69,20 @@ public class RegexpMethodPointcutAdvisorIntegrationTests {
TestBean advised = (TestBean) bf.getBean("settersAndAbsquatulateAdvised"); TestBean advised = (TestBean) bf.getBean("settersAndAbsquatulateAdvised");
// Interceptor behind regexp advisor // Interceptor behind regexp advisor
NopInterceptor nop = (NopInterceptor) bf.getBean("nopInterceptor"); NopInterceptor nop = (NopInterceptor) bf.getBean("nopInterceptor");
assertEquals(0, nop.getCount()); assertThat(nop.getCount()).isEqualTo(0);
int newAge = 12; int newAge = 12;
// Not advised // Not advised
advised.exceptional(null); advised.exceptional(null);
assertEquals(0, nop.getCount()); assertThat(nop.getCount()).isEqualTo(0);
// This is proxied // This is proxied
advised.absquatulate(); advised.absquatulate();
assertEquals(1, nop.getCount()); assertThat(nop.getCount()).isEqualTo(1);
advised.setAge(newAge); advised.setAge(newAge);
assertEquals(newAge, advised.getAge()); assertThat(advised.getAge()).isEqualTo(newAge);
// Only setter fired // Only setter fired
assertEquals(2, nop.getCount()); assertThat(nop.getCount()).isEqualTo(2);
} }
@Test @Test
@ -93,31 +93,31 @@ public class RegexpMethodPointcutAdvisorIntegrationTests {
Person p = (Person) bf.getBean("serializableSettersAdvised"); Person p = (Person) bf.getBean("serializableSettersAdvised");
// Interceptor behind regexp advisor // Interceptor behind regexp advisor
NopInterceptor nop = (NopInterceptor) bf.getBean("nopInterceptor"); NopInterceptor nop = (NopInterceptor) bf.getBean("nopInterceptor");
assertEquals(0, nop.getCount()); assertThat(nop.getCount()).isEqualTo(0);
int newAge = 12; int newAge = 12;
// Not advised // Not advised
assertEquals(0, p.getAge()); assertThat(p.getAge()).isEqualTo(0);
assertEquals(0, nop.getCount()); assertThat(nop.getCount()).isEqualTo(0);
// This is proxied // This is proxied
p.setAge(newAge); p.setAge(newAge);
assertEquals(1, nop.getCount()); assertThat(nop.getCount()).isEqualTo(1);
p.setAge(newAge); p.setAge(newAge);
assertEquals(newAge, p.getAge()); assertThat(p.getAge()).isEqualTo(newAge);
// Only setter fired // Only setter fired
assertEquals(2, nop.getCount()); assertThat(nop.getCount()).isEqualTo(2);
// Serialize and continue... // Serialize and continue...
p = (Person) SerializationTestUtils.serializeAndDeserialize(p); p = (Person) SerializationTestUtils.serializeAndDeserialize(p);
assertEquals(newAge, p.getAge()); assertThat(p.getAge()).isEqualTo(newAge);
// Remembers count, but we need to get a new reference to nop... // Remembers count, but we need to get a new reference to nop...
nop = (SerializableNopInterceptor) ((Advised) p).getAdvisors()[0].getAdvice(); nop = (SerializableNopInterceptor) ((Advised) p).getAdvisors()[0].getAdvice();
assertEquals(2, nop.getCount()); assertThat(nop.getCount()).isEqualTo(2);
assertEquals("serializableSettersAdvised", p.getName()); assertThat(p.getName()).isEqualTo("serializableSettersAdvised");
p.setAge(newAge + 1); p.setAge(newAge + 1);
assertEquals(3, nop.getCount()); assertThat(nop.getCount()).isEqualTo(3);
assertEquals(newAge + 1, p.getAge()); assertThat(p.getAge()).isEqualTo((newAge + 1));
} }
} }

View File

@ -24,7 +24,7 @@ import org.springframework.beans.factory.xml.XmlBeanDefinitionReader;
import org.springframework.core.io.Resource; import org.springframework.core.io.Resource;
import org.springframework.tests.sample.beans.ITestBean; import org.springframework.tests.sample.beans.ITestBean;
import static org.junit.Assert.assertTrue; import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.tests.TestResourceUtils.qualifiedResource; import static org.springframework.tests.TestResourceUtils.qualifiedResource;
/** /**
@ -42,6 +42,6 @@ public class CommonsPool2TargetSourceProxyTests {
reader.loadBeanDefinitions(CONTEXT); reader.loadBeanDefinitions(CONTEXT);
beanFactory.preInstantiateSingletons(); beanFactory.preInstantiateSingletons();
ITestBean bean = (ITestBean)beanFactory.getBean("testBean"); ITestBean bean = (ITestBean)beanFactory.getBean("testBean");
assertTrue(AopUtils.isAopProxy(bean)); assertThat(AopUtils.isAopProxy(bean)).isTrue();
} }
} }

View File

@ -31,8 +31,8 @@ import org.springframework.tests.sample.beans.SerializablePerson;
import org.springframework.tests.sample.beans.SideEffectBean; import org.springframework.tests.sample.beans.SideEffectBean;
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.junit.Assert.assertEquals;
import static org.springframework.tests.TestResourceUtils.qualifiedResource; import static org.springframework.tests.TestResourceUtils.qualifiedResource;
/** /**
@ -70,13 +70,13 @@ public class HotSwappableTargetSourceTests {
@Test @Test
public void testBasicFunctionality() { public void testBasicFunctionality() {
SideEffectBean proxied = (SideEffectBean) beanFactory.getBean("swappable"); SideEffectBean proxied = (SideEffectBean) beanFactory.getBean("swappable");
assertEquals(INITIAL_COUNT, proxied.getCount()); assertThat(proxied.getCount()).isEqualTo(INITIAL_COUNT);
proxied.doWork(); proxied.doWork();
assertEquals(INITIAL_COUNT + 1, proxied.getCount()); assertThat(proxied.getCount()).isEqualTo((INITIAL_COUNT + 1));
proxied = (SideEffectBean) beanFactory.getBean("swappable"); proxied = (SideEffectBean) beanFactory.getBean("swappable");
proxied.doWork(); proxied.doWork();
assertEquals(INITIAL_COUNT + 2, proxied.getCount()); assertThat(proxied.getCount()).isEqualTo((INITIAL_COUNT + 2));
} }
@Test @Test
@ -85,25 +85,25 @@ public class HotSwappableTargetSourceTests {
SideEffectBean target2 = (SideEffectBean) beanFactory.getBean("target2"); SideEffectBean target2 = (SideEffectBean) beanFactory.getBean("target2");
SideEffectBean proxied = (SideEffectBean) beanFactory.getBean("swappable"); SideEffectBean proxied = (SideEffectBean) beanFactory.getBean("swappable");
assertEquals(target1.getCount(), proxied.getCount()); assertThat(proxied.getCount()).isEqualTo(target1.getCount());
proxied.doWork(); proxied.doWork();
assertEquals(INITIAL_COUNT + 1, proxied.getCount()); assertThat(proxied.getCount()).isEqualTo((INITIAL_COUNT + 1));
HotSwappableTargetSource swapper = (HotSwappableTargetSource) beanFactory.getBean("swapper"); HotSwappableTargetSource swapper = (HotSwappableTargetSource) beanFactory.getBean("swapper");
Object old = swapper.swap(target2); Object old = swapper.swap(target2);
assertEquals("Correct old target was returned", target1, old); assertThat(old).as("Correct old target was returned").isEqualTo(target1);
// TODO should be able to make this assertion: need to fix target handling // TODO should be able to make this assertion: need to fix target handling
// in AdvisedSupport // in AdvisedSupport
//assertEquals(target2, ((Advised) proxied).getTarget()); //assertEquals(target2, ((Advised) proxied).getTarget());
assertEquals(20, proxied.getCount()); assertThat(proxied.getCount()).isEqualTo(20);
proxied.doWork(); proxied.doWork();
assertEquals(21, target2.getCount()); assertThat(target2.getCount()).isEqualTo(21);
// Swap it back // Swap it back
swapper.swap(target1); swapper.swap(target1);
assertEquals(target1.getCount(), proxied.getCount()); assertThat(proxied.getCount()).isEqualTo(target1.getCount());
} }
@Test @Test
@ -130,16 +130,16 @@ public class HotSwappableTargetSourceTests {
pf.addAdvisor(new DefaultPointcutAdvisor(new SerializableNopInterceptor())); pf.addAdvisor(new DefaultPointcutAdvisor(new SerializableNopInterceptor()));
Person p = (Person) pf.getProxy(); Person p = (Person) pf.getProxy();
assertEquals(sp1.getName(), p.getName()); assertThat(p.getName()).isEqualTo(sp1.getName());
hts.swap(sp2); hts.swap(sp2);
assertEquals(sp2.getName(), p.getName()); assertThat(p.getName()).isEqualTo(sp2.getName());
p = (Person) SerializationTestUtils.serializeAndDeserialize(p); p = (Person) SerializationTestUtils.serializeAndDeserialize(p);
// We need to get a reference to the client-side targetsource // We need to get a reference to the client-side targetsource
hts = (HotSwappableTargetSource) ((Advised) p).getTargetSource(); hts = (HotSwappableTargetSource) ((Advised) p).getTargetSource();
assertEquals(sp2.getName(), p.getName()); assertThat(p.getName()).isEqualTo(sp2.getName());
hts.swap(sp1); hts.swap(sp1);
assertEquals(sp1.getName(), p.getName()); assertThat(p.getName()).isEqualTo(sp1.getName());
} }

View File

@ -21,7 +21,7 @@ import org.junit.Test;
import org.springframework.aop.TargetSource; import org.springframework.aop.TargetSource;
import org.springframework.aop.framework.ProxyFactory; import org.springframework.aop.framework.ProxyFactory;
import static org.junit.Assert.assertEquals; import static org.assertj.core.api.Assertions.assertThat;
/** /**
* @author Rob Harrop * @author Rob Harrop
@ -44,15 +44,15 @@ public class LazyCreationTargetSourceTests {
}; };
InitCountingBean proxy = (InitCountingBean) ProxyFactory.getProxy(targetSource); InitCountingBean proxy = (InitCountingBean) ProxyFactory.getProxy(targetSource);
assertEquals("Init count should be 0", 0, InitCountingBean.initCount); assertThat(InitCountingBean.initCount).as("Init count should be 0").isEqualTo(0);
assertEquals("Target class incorrect", InitCountingBean.class, targetSource.getTargetClass()); assertThat(targetSource.getTargetClass()).as("Target class incorrect").isEqualTo(InitCountingBean.class);
assertEquals("Init count should still be 0 after getTargetClass()", 0, InitCountingBean.initCount); assertThat(InitCountingBean.initCount).as("Init count should still be 0 after getTargetClass()").isEqualTo(0);
proxy.doSomething(); proxy.doSomething();
assertEquals("Init count should now be 1", 1, InitCountingBean.initCount); assertThat(InitCountingBean.initCount).as("Init count should now be 1").isEqualTo(1);
proxy.doSomething(); proxy.doSomething();
assertEquals("Init count should still be 1", 1, InitCountingBean.initCount); assertThat(InitCountingBean.initCount).as("Init count should still be 1").isEqualTo(1);
} }

View File

@ -25,9 +25,7 @@ import org.springframework.beans.factory.xml.XmlBeanDefinitionReader;
import org.springframework.core.io.Resource; import org.springframework.core.io.Resource;
import org.springframework.tests.sample.beans.ITestBean; import org.springframework.tests.sample.beans.ITestBean;
import static org.junit.Assert.assertEquals; import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.springframework.tests.TestResourceUtils.qualifiedResource; import static org.springframework.tests.TestResourceUtils.qualifiedResource;
/** /**
@ -51,9 +49,9 @@ public class LazyInitTargetSourceTests {
bf.preInstantiateSingletons(); bf.preInstantiateSingletons();
ITestBean tb = (ITestBean) bf.getBean("proxy"); ITestBean tb = (ITestBean) bf.getBean("proxy");
assertFalse(bf.containsSingleton("target")); assertThat(bf.containsSingleton("target")).isFalse();
assertEquals(10, tb.getAge()); assertThat(tb.getAge()).isEqualTo(10);
assertTrue(bf.containsSingleton("target")); assertThat(bf.containsSingleton("target")).isTrue();
} }
@Test @Test
@ -63,9 +61,9 @@ public class LazyInitTargetSourceTests {
bf.preInstantiateSingletons(); bf.preInstantiateSingletons();
ITestBean tb = (ITestBean) bf.getBean("proxy"); ITestBean tb = (ITestBean) bf.getBean("proxy");
assertFalse(bf.containsSingleton("target")); assertThat(bf.containsSingleton("target")).isFalse();
assertEquals("Rob Harrop", tb.getName()); assertThat(tb.getName()).isEqualTo("Rob Harrop");
assertTrue(bf.containsSingleton("target")); assertThat(bf.containsSingleton("target")).isTrue();
} }
@Test @Test
@ -75,14 +73,14 @@ public class LazyInitTargetSourceTests {
bf.preInstantiateSingletons(); bf.preInstantiateSingletons();
Set<?> set1 = (Set<?>) bf.getBean("proxy1"); Set<?> set1 = (Set<?>) bf.getBean("proxy1");
assertFalse(bf.containsSingleton("target1")); assertThat(bf.containsSingleton("target1")).isFalse();
assertTrue(set1.contains("10")); assertThat(set1.contains("10")).isTrue();
assertTrue(bf.containsSingleton("target1")); assertThat(bf.containsSingleton("target1")).isTrue();
Set<?> set2 = (Set<?>) bf.getBean("proxy2"); Set<?> set2 = (Set<?>) bf.getBean("proxy2");
assertFalse(bf.containsSingleton("target2")); assertThat(bf.containsSingleton("target2")).isFalse();
assertTrue(set2.contains("20")); assertThat(set2.contains("20")).isTrue();
assertTrue(bf.containsSingleton("target2")); assertThat(bf.containsSingleton("target2")).isTrue();
} }

View File

@ -26,8 +26,7 @@ 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.junit.Assert.assertNotNull; import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertTrue;
/** /**
* Unit tests relating to the abstract {@link AbstractPrototypeBasedTargetSource} * Unit tests relating to the abstract {@link AbstractPrototypeBasedTargetSource}
@ -56,10 +55,10 @@ public class PrototypeBasedTargetSourceTests {
TestTargetSource cpts = (TestTargetSource) bf.getBean("ts"); TestTargetSource cpts = (TestTargetSource) bf.getBean("ts");
TargetSource serialized = (TargetSource) SerializationTestUtils.serializeAndDeserialize(cpts); TargetSource serialized = (TargetSource) SerializationTestUtils.serializeAndDeserialize(cpts);
assertTrue("Changed to SingletonTargetSource on deserialization", boolean condition = serialized instanceof SingletonTargetSource;
serialized instanceof SingletonTargetSource); assertThat(condition).as("Changed to SingletonTargetSource on deserialization").isTrue();
SingletonTargetSource sts = (SingletonTargetSource) serialized; SingletonTargetSource sts = (SingletonTargetSource) serialized;
assertNotNull(sts.getTarget()); assertThat(sts.getTarget()).isNotNull();
} }
@ -71,6 +70,7 @@ public class PrototypeBasedTargetSourceTests {
* Nonserializable test field to check that subclass * Nonserializable test field to check that subclass
* state can't prevent serialization from working * state can't prevent serialization from working
*/ */
@SuppressWarnings("unused")
private TestBean thisFieldIsNotSerializable = new TestBean(); private TestBean thisFieldIsNotSerializable = new TestBean();
@Override @Override

View File

@ -23,7 +23,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.tests.sample.beans.SideEffectBean; import org.springframework.tests.sample.beans.SideEffectBean;
import static org.junit.Assert.assertEquals; import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.tests.TestResourceUtils.qualifiedResource; import static org.springframework.tests.TestResourceUtils.qualifiedResource;
/** /**
@ -54,14 +54,14 @@ public class PrototypeTargetSourceTests {
@Test @Test
public void testPrototypeAndSingletonBehaveDifferently() { public void testPrototypeAndSingletonBehaveDifferently() {
SideEffectBean singleton = (SideEffectBean) beanFactory.getBean("singleton"); SideEffectBean singleton = (SideEffectBean) beanFactory.getBean("singleton");
assertEquals(INITIAL_COUNT, singleton.getCount()); assertThat(singleton.getCount()).isEqualTo(INITIAL_COUNT);
singleton.doWork(); singleton.doWork();
assertEquals(INITIAL_COUNT + 1, singleton.getCount()); assertThat(singleton.getCount()).isEqualTo((INITIAL_COUNT + 1));
SideEffectBean prototype = (SideEffectBean) beanFactory.getBean("prototype"); SideEffectBean prototype = (SideEffectBean) beanFactory.getBean("prototype");
assertEquals(INITIAL_COUNT, prototype.getCount()); assertThat(prototype.getCount()).isEqualTo(INITIAL_COUNT);
prototype.doWork(); prototype.doWork();
assertEquals(INITIAL_COUNT, prototype.getCount()); assertThat(prototype.getCount()).isEqualTo(INITIAL_COUNT);
} }
} }

View File

@ -24,8 +24,7 @@ import org.springframework.beans.factory.xml.XmlBeanDefinitionReader;
import org.springframework.tests.sample.beans.ITestBean; import org.springframework.tests.sample.beans.ITestBean;
import org.springframework.tests.sample.beans.SideEffectBean; import org.springframework.tests.sample.beans.SideEffectBean;
import static org.junit.Assert.assertEquals; import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertNotNull;
import static org.springframework.tests.TestResourceUtils.qualifiedResource; import static org.springframework.tests.TestResourceUtils.qualifiedResource;
/** /**
@ -63,24 +62,24 @@ public class ThreadLocalTargetSourceTests {
@Test @Test
public void testUseDifferentManagedInstancesInSameThread() { public void testUseDifferentManagedInstancesInSameThread() {
SideEffectBean apartment = (SideEffectBean) beanFactory.getBean("apartment"); SideEffectBean apartment = (SideEffectBean) beanFactory.getBean("apartment");
assertEquals(INITIAL_COUNT, apartment.getCount()); assertThat(apartment.getCount()).isEqualTo(INITIAL_COUNT);
apartment.doWork(); apartment.doWork();
assertEquals(INITIAL_COUNT + 1, apartment.getCount()); assertThat(apartment.getCount()).isEqualTo((INITIAL_COUNT + 1));
ITestBean test = (ITestBean) beanFactory.getBean("threadLocal2"); ITestBean test = (ITestBean) beanFactory.getBean("threadLocal2");
assertEquals("Rod", test.getName()); assertThat(test.getName()).isEqualTo("Rod");
assertEquals("Kerry", test.getSpouse().getName()); assertThat(test.getSpouse().getName()).isEqualTo("Kerry");
} }
@Test @Test
public void testReuseInSameThread() { public void testReuseInSameThread() {
SideEffectBean apartment = (SideEffectBean) beanFactory.getBean("apartment"); SideEffectBean apartment = (SideEffectBean) beanFactory.getBean("apartment");
assertEquals(INITIAL_COUNT, apartment.getCount()); assertThat(apartment.getCount()).isEqualTo(INITIAL_COUNT);
apartment.doWork(); apartment.doWork();
assertEquals(INITIAL_COUNT + 1, apartment.getCount()); assertThat(apartment.getCount()).isEqualTo((INITIAL_COUNT + 1));
apartment = (SideEffectBean) beanFactory.getBean("apartment"); apartment = (SideEffectBean) beanFactory.getBean("apartment");
assertEquals(INITIAL_COUNT + 1, apartment.getCount()); assertThat(apartment.getCount()).isEqualTo((INITIAL_COUNT + 1));
} }
/** /**
@ -90,37 +89,37 @@ public class ThreadLocalTargetSourceTests {
public void testCanGetStatsViaMixin() { public void testCanGetStatsViaMixin() {
ThreadLocalTargetSourceStats stats = (ThreadLocalTargetSourceStats) beanFactory.getBean("apartment"); ThreadLocalTargetSourceStats stats = (ThreadLocalTargetSourceStats) beanFactory.getBean("apartment");
// +1 because creating target for stats call counts // +1 because creating target for stats call counts
assertEquals(1, stats.getInvocationCount()); assertThat(stats.getInvocationCount()).isEqualTo(1);
SideEffectBean apartment = (SideEffectBean) beanFactory.getBean("apartment"); SideEffectBean apartment = (SideEffectBean) beanFactory.getBean("apartment");
apartment.doWork(); apartment.doWork();
// +1 again // +1 again
assertEquals(3, stats.getInvocationCount()); assertThat(stats.getInvocationCount()).isEqualTo(3);
// + 1 for states call! // + 1 for states call!
assertEquals(3, stats.getHitCount()); assertThat(stats.getHitCount()).isEqualTo(3);
apartment.doWork(); apartment.doWork();
assertEquals(6, stats.getInvocationCount()); assertThat(stats.getInvocationCount()).isEqualTo(6);
assertEquals(6, stats.getHitCount()); assertThat(stats.getHitCount()).isEqualTo(6);
// Only one thread so only one object can have been bound // Only one thread so only one object can have been bound
assertEquals(1, stats.getObjectCount()); assertThat(stats.getObjectCount()).isEqualTo(1);
} }
@Test @Test
public void testNewThreadHasOwnInstance() throws InterruptedException { public void testNewThreadHasOwnInstance() throws InterruptedException {
SideEffectBean apartment = (SideEffectBean) beanFactory.getBean("apartment"); SideEffectBean apartment = (SideEffectBean) beanFactory.getBean("apartment");
assertEquals(INITIAL_COUNT, apartment.getCount()); assertThat(apartment.getCount()).isEqualTo(INITIAL_COUNT);
apartment.doWork(); apartment.doWork();
apartment.doWork(); apartment.doWork();
apartment.doWork(); apartment.doWork();
assertEquals(INITIAL_COUNT + 3, apartment.getCount()); assertThat(apartment.getCount()).isEqualTo((INITIAL_COUNT + 3));
class Runner implements Runnable { class Runner implements Runnable {
public SideEffectBean mine; public SideEffectBean mine;
@Override @Override
public void run() { public void run() {
this.mine = (SideEffectBean) beanFactory.getBean("apartment"); this.mine = (SideEffectBean) beanFactory.getBean("apartment");
assertEquals(INITIAL_COUNT, mine.getCount()); assertThat(mine.getCount()).isEqualTo(INITIAL_COUNT);
mine.doWork(); mine.doWork();
assertEquals(INITIAL_COUNT + 1, mine.getCount()); assertThat(mine.getCount()).isEqualTo((INITIAL_COUNT + 1));
} }
} }
Runner r = new Runner(); Runner r = new Runner();
@ -128,17 +127,17 @@ public class ThreadLocalTargetSourceTests {
t.start(); t.start();
t.join(); t.join();
assertNotNull(r); assertThat(r).isNotNull();
// Check it didn't affect the other thread's copy // Check it didn't affect the other thread's copy
assertEquals(INITIAL_COUNT + 3, apartment.getCount()); assertThat(apartment.getCount()).isEqualTo((INITIAL_COUNT + 3));
// When we use other thread's copy in this thread // When we use other thread's copy in this thread
// it should behave like ours // it should behave like ours
assertEquals(INITIAL_COUNT + 3, r.mine.getCount()); assertThat(r.mine.getCount()).isEqualTo((INITIAL_COUNT + 3));
// Bound to two threads // Bound to two threads
assertEquals(2, ((ThreadLocalTargetSourceStats) apartment).getObjectCount()); assertThat(((ThreadLocalTargetSourceStats) apartment).getObjectCount()).isEqualTo(2);
} }
/** /**

View File

@ -21,11 +21,7 @@ import org.junit.Test;
import org.springframework.tests.Assume; import org.springframework.tests.Assume;
import org.springframework.tests.TestGroup; import org.springframework.tests.TestGroup;
import static org.junit.Assert.assertEquals; import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNotSame;
import static org.junit.Assert.assertSame;
/** /**
* @author Rob Harrop * @author Rob Harrop
@ -45,8 +41,8 @@ public class RefreshableTargetSourceTests {
Thread.sleep(1); Thread.sleep(1);
Object b = ts.getTarget(); Object b = ts.getTarget();
assertEquals("Should be one call to freshTarget to get initial target", 1, ts.getCallCount()); assertThat(ts.getCallCount()).as("Should be one call to freshTarget to get initial target").isEqualTo(1);
assertSame("Returned objects should be the same - no refresh should occur", a, b); assertThat(b).as("Returned objects should be the same - no refresh should occur").isSameAs(a);
} }
/** /**
@ -61,8 +57,8 @@ public class RefreshableTargetSourceTests {
Thread.sleep(100); Thread.sleep(100);
Object b = ts.getTarget(); Object b = ts.getTarget();
assertEquals("Should have called freshTarget twice", 2, ts.getCallCount()); assertThat(ts.getCallCount()).as("Should have called freshTarget twice").isEqualTo(2);
assertNotSame("Should be different objects", a, b); assertThat(b).as("Should be different objects").isNotSameAs(a);
} }
/** /**
@ -76,8 +72,8 @@ public class RefreshableTargetSourceTests {
Object a = ts.getTarget(); Object a = ts.getTarget();
Object b = ts.getTarget(); Object b = ts.getTarget();
assertEquals("Refresh target should only be called once", 1, ts.getCallCount()); assertThat(ts.getCallCount()).as("Refresh target should only be called once").isEqualTo(1);
assertSame("Objects should be the same - refresh check delay not elapsed", a, b); assertThat(b).as("Objects should be the same - refresh check delay not elapsed").isSameAs(a);
} }
@Test @Test
@ -89,26 +85,26 @@ public class RefreshableTargetSourceTests {
Object a = ts.getTarget(); Object a = ts.getTarget();
Object b = ts.getTarget(); Object b = ts.getTarget();
assertEquals("Objects should be same", a, b); assertThat(b).as("Objects should be same").isEqualTo(a);
Thread.sleep(50); Thread.sleep(50);
Object c = ts.getTarget(); Object c = ts.getTarget();
assertEquals("A and C should be same", a, c); assertThat(c).as("A and C should be same").isEqualTo(a);
Thread.sleep(60); Thread.sleep(60);
Object d = ts.getTarget(); Object d = ts.getTarget();
assertNotNull("D should not be null", d); assertThat(d).as("D should not be null").isNotNull();
assertFalse("A and D should not be equal", a.equals(d)); assertThat(a.equals(d)).as("A and D should not be equal").isFalse();
Object e = ts.getTarget(); Object e = ts.getTarget();
assertEquals("D and E should be equal", d, e); assertThat(e).as("D and E should be equal").isEqualTo(d);
Thread.sleep(110); Thread.sleep(110);
Object f = ts.getTarget(); Object f = ts.getTarget();
assertFalse("E and F should be different", e.equals(f)); assertThat(e.equals(f)).as("E and F should be different").isFalse();
} }

View File

@ -20,7 +20,7 @@ import org.junit.Test;
import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext;
import static org.junit.Assert.assertEquals; import static org.assertj.core.api.Assertions.assertThat;
/** /**
* @author Chris Beams * @author Chris Beams
@ -33,7 +33,7 @@ public class XmlBeanConfigurerTests {
"org/springframework/beans/factory/aspectj/beanConfigurerTests.xml")) { "org/springframework/beans/factory/aspectj/beanConfigurerTests.xml")) {
ShouldBeConfiguredBySpring myObject = new ShouldBeConfiguredBySpring(); ShouldBeConfiguredBySpring myObject = new ShouldBeConfiguredBySpring();
assertEquals("Rod", myObject.getName()); assertThat(myObject.getName()).isEqualTo("Rod");
} }
} }

View File

@ -24,9 +24,7 @@ import org.springframework.cache.config.CacheableService;
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.junit.Assert.assertNotSame; import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame;
/** /**
* @author Costin Leau * @author Costin Leau
@ -43,7 +41,7 @@ public class AspectJCacheAnnotationTests extends AbstractCacheAnnotationTests {
public void testKeyStrategy() throws Exception { public void testKeyStrategy() throws Exception {
AnnotationCacheAspect aspect = ctx.getBean( AnnotationCacheAspect aspect = ctx.getBean(
"org.springframework.cache.config.internalCacheAspect", AnnotationCacheAspect.class); "org.springframework.cache.config.internalCacheAspect", AnnotationCacheAspect.class);
assertSame(ctx.getBean("keyGenerator"), aspect.getKeyGenerator()); assertThat(aspect.getKeyGenerator()).isSameAs(ctx.getBean("keyGenerator"));
} }
@Override @Override
@ -56,21 +54,21 @@ public class AspectJCacheAnnotationTests extends AbstractCacheAnnotationTests {
Cache primary = cm.getCache("primary"); Cache primary = cm.getCache("primary");
Cache secondary = cm.getCache("secondary"); Cache secondary = cm.getCache("secondary");
assertSame(r1, r2); assertThat(r2).isSameAs(r1);
assertSame(r1, primary.get(o1).get()); assertThat(primary.get(o1).get()).isSameAs(r1);
assertSame(r1, secondary.get(o1).get()); assertThat(secondary.get(o1).get()).isSameAs(r1);
service.multiEvict(o1); service.multiEvict(o1);
assertNull(primary.get(o1)); assertThat(primary.get(o1)).isNull();
assertNull(secondary.get(o1)); assertThat(secondary.get(o1)).isNull();
Object r3 = service.multiCache(o1); Object r3 = service.multiCache(o1);
Object r4 = service.multiCache(o1); Object r4 = service.multiCache(o1);
assertNotSame(r1, r3); assertThat(r3).isNotSameAs(r1);
assertSame(r3, r4); assertThat(r4).isSameAs(r3);
assertSame(r3, primary.get(o1).get()); assertThat(primary.get(o1).get()).isSameAs(r3);
assertSame(r4, secondary.get(o1).get()); assertThat(secondary.get(o1).get()).isSameAs(r4);
} }
} }

View File

@ -43,10 +43,7 @@ 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.junit.Assert.assertEquals; import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
/** /**
* @author Stephane Nicoll * @author Stephane Nicoll
@ -72,14 +69,14 @@ public class AspectJEnableCachingIsolatedTests {
public void testKeyStrategy() { public void testKeyStrategy() {
load(EnableCachingConfig.class); load(EnableCachingConfig.class);
AnnotationCacheAspect aspect = this.ctx.getBean(AnnotationCacheAspect.class); AnnotationCacheAspect aspect = this.ctx.getBean(AnnotationCacheAspect.class);
assertSame(this.ctx.getBean("keyGenerator", KeyGenerator.class), aspect.getKeyGenerator()); assertThat(aspect.getKeyGenerator()).isSameAs(this.ctx.getBean("keyGenerator", KeyGenerator.class));
} }
@Test @Test
public void testCacheErrorHandler() { public void testCacheErrorHandler() {
load(EnableCachingConfig.class); load(EnableCachingConfig.class);
AnnotationCacheAspect aspect = this.ctx.getBean(AnnotationCacheAspect.class); AnnotationCacheAspect aspect = this.ctx.getBean(AnnotationCacheAspect.class);
assertSame(this.ctx.getBean("errorHandler", CacheErrorHandler.class), aspect.getErrorHandler()); assertThat(aspect.getErrorHandler()).isSameAs(this.ctx.getBean("errorHandler", CacheErrorHandler.class));
} }
@ -96,7 +93,7 @@ public class AspectJEnableCachingIsolatedTests {
load(MultiCacheManagerConfig.class); load(MultiCacheManagerConfig.class);
} }
catch (IllegalStateException ex) { catch (IllegalStateException ex) {
assertTrue(ex.getMessage().contains("bean of type CacheManager")); assertThat(ex.getMessage().contains("bean of type CacheManager")).isTrue();
} }
} }
@ -112,8 +109,9 @@ public class AspectJEnableCachingIsolatedTests {
} }
catch (BeanCreationException ex) { catch (BeanCreationException ex) {
Throwable root = ex.getRootCause(); Throwable root = ex.getRootCause();
assertTrue(root instanceof IllegalStateException); boolean condition = root instanceof IllegalStateException;
assertTrue(ex.getMessage().contains("implementations of CachingConfigurer")); assertThat(condition).isTrue();
assertThat(ex.getMessage().contains("implementations of CachingConfigurer")).isTrue();
} }
} }
@ -123,7 +121,7 @@ public class AspectJEnableCachingIsolatedTests {
load(EmptyConfig.class); load(EmptyConfig.class);
} }
catch (IllegalStateException ex) { catch (IllegalStateException ex) {
assertTrue(ex.getMessage().contains("no bean of type CacheManager")); assertThat(ex.getMessage().contains("no bean of type CacheManager")).isTrue();
} }
} }
@ -132,10 +130,9 @@ public class AspectJEnableCachingIsolatedTests {
public void emptyConfigSupport() { public void emptyConfigSupport() {
load(EmptyConfigSupportConfig.class); load(EmptyConfigSupportConfig.class);
AnnotationCacheAspect aspect = this.ctx.getBean(AnnotationCacheAspect.class); AnnotationCacheAspect aspect = this.ctx.getBean(AnnotationCacheAspect.class);
assertNotNull(aspect.getCacheResolver()); assertThat(aspect.getCacheResolver()).isNotNull();
assertEquals(SimpleCacheResolver.class, aspect.getCacheResolver().getClass()); assertThat(aspect.getCacheResolver().getClass()).isEqualTo(SimpleCacheResolver.class);
assertSame(this.ctx.getBean(CacheManager.class), assertThat(((SimpleCacheResolver) aspect.getCacheResolver()).getCacheManager()).isSameAs(this.ctx.getBean(CacheManager.class));
((SimpleCacheResolver) aspect.getCacheResolver()).getCacheManager());
} }
@Test @Test
@ -143,8 +140,8 @@ public class AspectJEnableCachingIsolatedTests {
load(FullCachingConfig.class); load(FullCachingConfig.class);
AnnotationCacheAspect aspect = this.ctx.getBean(AnnotationCacheAspect.class); AnnotationCacheAspect aspect = this.ctx.getBean(AnnotationCacheAspect.class);
assertSame(this.ctx.getBean("cacheResolver"), aspect.getCacheResolver()); assertThat(aspect.getCacheResolver()).isSameAs(this.ctx.getBean("cacheResolver"));
assertSame(this.ctx.getBean("keyGenerator"), aspect.getKeyGenerator()); assertThat(aspect.getKeyGenerator()).isSameAs(this.ctx.getBean("keyGenerator"));
} }

View File

@ -23,7 +23,7 @@ import org.springframework.context.annotation.AnnotationConfigApplicationContext
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportResource; import org.springframework.context.annotation.ImportResource;
import static org.junit.Assert.assertEquals; import static org.assertj.core.api.Assertions.assertThat;
/** /**
* Tests that @EnableSpringConfigured properly registers an * Tests that @EnableSpringConfigured properly registers an
@ -39,7 +39,7 @@ public class AnnotationBeanConfigurerTests {
public void injection() { public void injection() {
try (AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(Config.class)) { try (AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(Config.class)) {
ShouldBeConfiguredBySpring myObject = new ShouldBeConfiguredBySpring(); ShouldBeConfiguredBySpring myObject = new ShouldBeConfiguredBySpring();
assertEquals("Rod", myObject.getName()); assertThat(myObject.getName()).isEqualTo("Rod");
} }
} }

View File

@ -39,8 +39,6 @@ import org.springframework.util.ReflectionUtils;
import org.springframework.util.concurrent.ListenableFuture; import org.springframework.util.concurrent.ListenableFuture;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
/** /**
* Unit tests for {@link AnnotationAsyncExecutionAspect}. * Unit tests for {@link AnnotationAsyncExecutionAspect}.
@ -71,9 +69,9 @@ public class AnnotationAsyncExecutionAspectTests {
ClassWithoutAsyncAnnotation obj = new ClassWithoutAsyncAnnotation(); ClassWithoutAsyncAnnotation obj = new ClassWithoutAsyncAnnotation();
obj.incrementAsync(); obj.incrementAsync();
executor.waitForCompletion(); executor.waitForCompletion();
assertEquals(1, obj.counter); assertThat(obj.counter).isEqualTo(1);
assertEquals(1, executor.submitStartCounter); assertThat(executor.submitStartCounter).isEqualTo(1);
assertEquals(1, executor.submitCompleteCounter); assertThat(executor.submitCompleteCounter).isEqualTo(1);
} }
@Test @Test
@ -81,19 +79,19 @@ public class AnnotationAsyncExecutionAspectTests {
ClassWithoutAsyncAnnotation obj = new ClassWithoutAsyncAnnotation(); ClassWithoutAsyncAnnotation obj = new ClassWithoutAsyncAnnotation();
Future<Integer> future = obj.incrementReturningAFuture(); Future<Integer> future = obj.incrementReturningAFuture();
// No need to executor.waitForCompletion() as future.get() will have the same effect // No need to executor.waitForCompletion() as future.get() will have the same effect
assertEquals(5, future.get().intValue()); assertThat(future.get().intValue()).isEqualTo(5);
assertEquals(1, obj.counter); assertThat(obj.counter).isEqualTo(1);
assertEquals(1, executor.submitStartCounter); assertThat(executor.submitStartCounter).isEqualTo(1);
assertEquals(1, executor.submitCompleteCounter); assertThat(executor.submitCompleteCounter).isEqualTo(1);
} }
@Test @Test
public void syncMethodGetsRoutedSynchronously() { public void syncMethodGetsRoutedSynchronously() {
ClassWithoutAsyncAnnotation obj = new ClassWithoutAsyncAnnotation(); ClassWithoutAsyncAnnotation obj = new ClassWithoutAsyncAnnotation();
obj.increment(); obj.increment();
assertEquals(1, obj.counter); assertThat(obj.counter).isEqualTo(1);
assertEquals(0, executor.submitStartCounter); assertThat(executor.submitStartCounter).isEqualTo(0);
assertEquals(0, executor.submitCompleteCounter); assertThat(executor.submitCompleteCounter).isEqualTo(0);
} }
@Test @Test
@ -103,19 +101,19 @@ public class AnnotationAsyncExecutionAspectTests {
ClassWithAsyncAnnotation obj = new ClassWithAsyncAnnotation(); ClassWithAsyncAnnotation obj = new ClassWithAsyncAnnotation();
obj.increment(); obj.increment();
executor.waitForCompletion(); executor.waitForCompletion();
assertEquals(1, obj.counter); assertThat(obj.counter).isEqualTo(1);
assertEquals(1, executor.submitStartCounter); assertThat(executor.submitStartCounter).isEqualTo(1);
assertEquals(1, executor.submitCompleteCounter); assertThat(executor.submitCompleteCounter).isEqualTo(1);
} }
@Test @Test
public void methodReturningFutureInAsyncClassGetsRoutedAsynchronouslyAndReturnsAFuture() throws InterruptedException, ExecutionException { public void methodReturningFutureInAsyncClassGetsRoutedAsynchronouslyAndReturnsAFuture() throws InterruptedException, ExecutionException {
ClassWithAsyncAnnotation obj = new ClassWithAsyncAnnotation(); ClassWithAsyncAnnotation obj = new ClassWithAsyncAnnotation();
Future<Integer> future = obj.incrementReturningAFuture(); Future<Integer> future = obj.incrementReturningAFuture();
assertEquals(5, future.get().intValue()); assertThat(future.get().intValue()).isEqualTo(5);
assertEquals(1, obj.counter); assertThat(obj.counter).isEqualTo(1);
assertEquals(1, executor.submitStartCounter); assertThat(executor.submitStartCounter).isEqualTo(1);
assertEquals(1, executor.submitCompleteCounter); assertThat(executor.submitCompleteCounter).isEqualTo(1);
} }
/* /*
@ -154,7 +152,7 @@ public class AnnotationAsyncExecutionAspectTests {
TestableAsyncUncaughtExceptionHandler exceptionHandler = new TestableAsyncUncaughtExceptionHandler(); TestableAsyncUncaughtExceptionHandler exceptionHandler = new TestableAsyncUncaughtExceptionHandler();
AnnotationAsyncExecutionAspect.aspectOf().setExceptionHandler(exceptionHandler); AnnotationAsyncExecutionAspect.aspectOf().setExceptionHandler(exceptionHandler);
try { try {
assertFalse("Handler should not have been called", exceptionHandler.isCalled()); assertThat(exceptionHandler.isCalled()).as("Handler should not have been called").isFalse();
ClassWithException obj = new ClassWithException(); ClassWithException obj = new ClassWithException();
obj.failWithVoid(); obj.failWithVoid();
exceptionHandler.await(3000); exceptionHandler.await(3000);
@ -171,7 +169,7 @@ public class AnnotationAsyncExecutionAspectTests {
TestableAsyncUncaughtExceptionHandler exceptionHandler = new TestableAsyncUncaughtExceptionHandler(true); TestableAsyncUncaughtExceptionHandler exceptionHandler = new TestableAsyncUncaughtExceptionHandler(true);
AnnotationAsyncExecutionAspect.aspectOf().setExceptionHandler(exceptionHandler); AnnotationAsyncExecutionAspect.aspectOf().setExceptionHandler(exceptionHandler);
try { try {
assertFalse("Handler should not have been called", exceptionHandler.isCalled()); assertThat(exceptionHandler.isCalled()).as("Handler should not have been called").isFalse();
ClassWithException obj = new ClassWithException(); ClassWithException obj = new ClassWithException();
obj.failWithVoid(); obj.failWithVoid();
exceptionHandler.await(3000); exceptionHandler.await(3000);

View File

@ -27,8 +27,7 @@ import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.scheduling.config.TaskManagementConfigUtils; import org.springframework.scheduling.config.TaskManagementConfigUtils;
import static org.junit.Assert.assertSame; import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertTrue;
/** /**
* @author Stephane Nicoll * @author Stephane Nicoll
@ -52,7 +51,7 @@ public class AnnotationDrivenBeanDefinitionParserTests {
@Test @Test
public void asyncAspectRegistered() { public void asyncAspectRegistered() {
assertTrue(context.containsBean(TaskManagementConfigUtils.ASYNC_EXECUTION_ASPECT_BEAN_NAME)); assertThat(context.containsBean(TaskManagementConfigUtils.ASYNC_EXECUTION_ASPECT_BEAN_NAME)).isTrue();
} }
@Test @Test
@ -60,7 +59,7 @@ public class AnnotationDrivenBeanDefinitionParserTests {
public void asyncPostProcessorExecutorReference() { public void asyncPostProcessorExecutorReference() {
Object executor = context.getBean("testExecutor"); Object executor = context.getBean("testExecutor");
Object aspect = context.getBean(TaskManagementConfigUtils.ASYNC_EXECUTION_ASPECT_BEAN_NAME); Object aspect = context.getBean(TaskManagementConfigUtils.ASYNC_EXECUTION_ASPECT_BEAN_NAME);
assertSame(executor, ((Supplier) new DirectFieldAccessor(aspect).getPropertyValue("defaultExecutor")).get()); assertThat(((Supplier) new DirectFieldAccessor(aspect).getPropertyValue("defaultExecutor")).get()).isSameAs(executor);
} }
@Test @Test
@ -68,7 +67,7 @@ public class AnnotationDrivenBeanDefinitionParserTests {
public void asyncPostProcessorExceptionHandlerReference() { public void asyncPostProcessorExceptionHandlerReference() {
Object exceptionHandler = context.getBean("testExceptionHandler"); Object exceptionHandler = context.getBean("testExceptionHandler");
Object aspect = context.getBean(TaskManagementConfigUtils.ASYNC_EXECUTION_ASPECT_BEAN_NAME); Object aspect = context.getBean(TaskManagementConfigUtils.ASYNC_EXECUTION_ASPECT_BEAN_NAME);
assertSame(exceptionHandler, ((Supplier) new DirectFieldAccessor(aspect).getPropertyValue("exceptionHandler")).get()); assertThat(((Supplier) new DirectFieldAccessor(aspect).getPropertyValue("exceptionHandler")).get()).isSameAs(exceptionHandler);
} }
} }

View File

@ -22,8 +22,7 @@ import java.util.concurrent.TimeUnit;
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler; import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import static org.junit.Assert.assertEquals; import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertNotNull;
/** /**
* A {@link AsyncUncaughtExceptionHandler} implementation used for testing purposes. * A {@link AsyncUncaughtExceptionHandler} implementation used for testing purposes.
@ -61,9 +60,9 @@ class TestableAsyncUncaughtExceptionHandler
} }
public void assertCalledWith(Method expectedMethod, Class<? extends Throwable> expectedExceptionType) { public void assertCalledWith(Method expectedMethod, Class<? extends Throwable> expectedExceptionType) {
assertNotNull("Handler not called", descriptor); assertThat(descriptor).as("Handler not called").isNotNull();
assertEquals("Wrong exception type", expectedExceptionType, descriptor.ex.getClass()); assertThat(descriptor.ex.getClass()).as("Wrong exception type").isEqualTo(expectedExceptionType);
assertEquals("Wrong method", expectedMethod, descriptor.method); assertThat(descriptor.method).as("Wrong method").isEqualTo(expectedMethod);
} }
public void await(long timeout) { public void await(long timeout) {

View File

@ -30,9 +30,9 @@ import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.tests.transaction.CallCountingTransactionManager; import org.springframework.tests.transaction.CallCountingTransactionManager;
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.junit.Assert.assertEquals;
/** /**
* @author Stephane Nicoll * @author Stephane Nicoll
@ -51,66 +51,66 @@ public class JtaTransactionAspectsTests {
@Test @Test
public void commitOnAnnotatedPublicMethod() throws Throwable { public void commitOnAnnotatedPublicMethod() throws Throwable {
assertEquals(0, this.txManager.begun); assertThat(this.txManager.begun).isEqualTo(0);
new JtaAnnotationPublicAnnotatedMember().echo(null); new JtaAnnotationPublicAnnotatedMember().echo(null);
assertEquals(1, this.txManager.commits); assertThat(this.txManager.commits).isEqualTo(1);
} }
@Test @Test
public void matchingRollbackOnApplied() throws Throwable { public void matchingRollbackOnApplied() throws Throwable {
assertEquals(0, this.txManager.begun); assertThat(this.txManager.begun).isEqualTo(0);
InterruptedException test = new InterruptedException(); InterruptedException test = new InterruptedException();
assertThatExceptionOfType(InterruptedException.class).isThrownBy(() -> assertThatExceptionOfType(InterruptedException.class).isThrownBy(() ->
new JtaAnnotationPublicAnnotatedMember().echo(test)) new JtaAnnotationPublicAnnotatedMember().echo(test))
.isSameAs(test); .isSameAs(test);
assertEquals(1, this.txManager.rollbacks); assertThat(this.txManager.rollbacks).isEqualTo(1);
assertEquals(0, this.txManager.commits); assertThat(this.txManager.commits).isEqualTo(0);
} }
@Test @Test
public void nonMatchingRollbackOnApplied() throws Throwable { public void nonMatchingRollbackOnApplied() throws Throwable {
assertEquals(0, this.txManager.begun); assertThat(this.txManager.begun).isEqualTo(0);
IOException test = new IOException(); IOException test = new IOException();
assertThatIOException().isThrownBy(() -> assertThatIOException().isThrownBy(() ->
new JtaAnnotationPublicAnnotatedMember().echo(test)) new JtaAnnotationPublicAnnotatedMember().echo(test))
.isSameAs(test); .isSameAs(test);
assertEquals(1, this.txManager.commits); assertThat(this.txManager.commits).isEqualTo(1);
assertEquals(0, this.txManager.rollbacks); assertThat(this.txManager.rollbacks).isEqualTo(0);
} }
@Test @Test
public void commitOnAnnotatedProtectedMethod() { public void commitOnAnnotatedProtectedMethod() {
assertEquals(0, this.txManager.begun); assertThat(this.txManager.begun).isEqualTo(0);
new JtaAnnotationProtectedAnnotatedMember().doInTransaction(); new JtaAnnotationProtectedAnnotatedMember().doInTransaction();
assertEquals(1, this.txManager.commits); assertThat(this.txManager.commits).isEqualTo(1);
} }
@Test @Test
public void nonAnnotatedMethodCallingProtectedMethod() { public void nonAnnotatedMethodCallingProtectedMethod() {
assertEquals(0, this.txManager.begun); assertThat(this.txManager.begun).isEqualTo(0);
new JtaAnnotationProtectedAnnotatedMember().doSomething(); new JtaAnnotationProtectedAnnotatedMember().doSomething();
assertEquals(1, this.txManager.commits); assertThat(this.txManager.commits).isEqualTo(1);
} }
@Test @Test
public void commitOnAnnotatedPrivateMethod() { public void commitOnAnnotatedPrivateMethod() {
assertEquals(0, this.txManager.begun); assertThat(this.txManager.begun).isEqualTo(0);
new JtaAnnotationPrivateAnnotatedMember().doInTransaction(); new JtaAnnotationPrivateAnnotatedMember().doInTransaction();
assertEquals(1, this.txManager.commits); assertThat(this.txManager.commits).isEqualTo(1);
} }
@Test @Test
public void nonAnnotatedMethodCallingPrivateMethod() { public void nonAnnotatedMethodCallingPrivateMethod() {
assertEquals(0, this.txManager.begun); assertThat(this.txManager.begun).isEqualTo(0);
new JtaAnnotationPrivateAnnotatedMember().doSomething(); new JtaAnnotationPrivateAnnotatedMember().doSomething();
assertEquals(1, this.txManager.commits); assertThat(this.txManager.commits).isEqualTo(1);
} }
@Test @Test
public void notTransactional() { public void notTransactional() {
assertEquals(0, this.txManager.begun); assertThat(this.txManager.begun).isEqualTo(0);
new TransactionAspectTests.NotTransactional().noop(); new TransactionAspectTests.NotTransactional().noop();
assertEquals(0, this.txManager.begun); assertThat(this.txManager.begun).isEqualTo(0);
} }

View File

@ -21,8 +21,8 @@ import org.junit.Test;
import org.springframework.tests.transaction.CallCountingTransactionManager; import org.springframework.tests.transaction.CallCountingTransactionManager;
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.junit.Assert.assertEquals;
/** /**
* @author Rod Johnson * @author Rod Johnson
@ -56,49 +56,49 @@ public class TransactionAspectTests {
@Test @Test
public void testCommitOnAnnotatedClass() throws Throwable { public void testCommitOnAnnotatedClass() throws Throwable {
txManager.clear(); txManager.clear();
assertEquals(0, txManager.begun); assertThat(txManager.begun).isEqualTo(0);
annotationOnlyOnClassWithNoInterface.echo(null); annotationOnlyOnClassWithNoInterface.echo(null);
assertEquals(1, txManager.commits); assertThat(txManager.commits).isEqualTo(1);
} }
@Test @Test
public void commitOnAnnotatedProtectedMethod() throws Throwable { public void commitOnAnnotatedProtectedMethod() throws Throwable {
txManager.clear(); txManager.clear();
assertEquals(0, txManager.begun); assertThat(txManager.begun).isEqualTo(0);
beanWithAnnotatedProtectedMethod.doInTransaction(); beanWithAnnotatedProtectedMethod.doInTransaction();
assertEquals(1, txManager.commits); assertThat(txManager.commits).isEqualTo(1);
} }
@Test @Test
public void commitOnAnnotatedPrivateMethod() throws Throwable { public void commitOnAnnotatedPrivateMethod() throws Throwable {
txManager.clear(); txManager.clear();
assertEquals(0, txManager.begun); assertThat(txManager.begun).isEqualTo(0);
beanWithAnnotatedPrivateMethod.doSomething(); beanWithAnnotatedPrivateMethod.doSomething();
assertEquals(1, txManager.commits); assertThat(txManager.commits).isEqualTo(1);
} }
@Test @Test
public void commitOnNonAnnotatedNonPublicMethodInTransactionalType() throws Throwable { public void commitOnNonAnnotatedNonPublicMethodInTransactionalType() throws Throwable {
txManager.clear(); txManager.clear();
assertEquals(0, txManager.begun); assertThat(txManager.begun).isEqualTo(0);
annotationOnlyOnClassWithNoInterface.nonTransactionalMethod(); annotationOnlyOnClassWithNoInterface.nonTransactionalMethod();
assertEquals(0, txManager.begun); assertThat(txManager.begun).isEqualTo(0);
} }
@Test @Test
public void commitOnAnnotatedMethod() throws Throwable { public void commitOnAnnotatedMethod() throws Throwable {
txManager.clear(); txManager.clear();
assertEquals(0, txManager.begun); assertThat(txManager.begun).isEqualTo(0);
methodAnnotationOnly.echo(null); methodAnnotationOnly.echo(null);
assertEquals(1, txManager.commits); assertThat(txManager.commits).isEqualTo(1);
} }
@Test @Test
public void notTransactional() throws Throwable { public void notTransactional() throws Throwable {
txManager.clear(); txManager.clear();
assertEquals(0, txManager.begun); assertThat(txManager.begun).isEqualTo(0);
new NotTransactional().noop(); new NotTransactional().noop();
assertEquals(0, txManager.begun); assertThat(txManager.begun).isEqualTo(0);
} }
@Test @Test
@ -149,23 +149,25 @@ public class TransactionAspectTests {
protected void testRollback(TransactionOperationCallback toc, boolean rollback) throws Throwable { protected void testRollback(TransactionOperationCallback toc, boolean rollback) throws Throwable {
txManager.clear(); txManager.clear();
assertEquals(0, txManager.begun); assertThat(txManager.begun).isEqualTo(0);
try { try {
toc.performTransactionalOperation(); toc.performTransactionalOperation();
} }
finally { finally {
assertEquals(1, txManager.begun); assertThat(txManager.begun).isEqualTo(1);
assertEquals(rollback ? 0 : 1, txManager.commits); long expected1 = rollback ? 0 : 1;
assertEquals(rollback ? 1 : 0, txManager.rollbacks); assertThat(txManager.commits).isEqualTo(expected1);
long expected = rollback ? 1 : 0;
assertThat(txManager.rollbacks).isEqualTo(expected);
} }
} }
protected void testNotTransactional(TransactionOperationCallback toc, Throwable expected) throws Throwable { protected void testNotTransactional(TransactionOperationCallback toc, Throwable expected) throws Throwable {
txManager.clear(); txManager.clear();
assertEquals(0, txManager.begun); assertThat(txManager.begun).isEqualTo(0);
assertThatExceptionOfType(Throwable.class).isThrownBy( assertThatExceptionOfType(Throwable.class).isThrownBy(
toc::performTransactionalOperation).isSameAs(expected); toc::performTransactionalOperation).isSameAs(expected);
assertEquals(0, txManager.begun); assertThat(txManager.begun).isEqualTo(0);
} }

View File

@ -19,7 +19,7 @@ package org.springframework.beans;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
import static org.junit.Assert.assertTrue; import static org.assertj.core.api.Assertions.assertThat;
/** /**
* @author Rod Johnson * @author Rod Johnson
@ -31,11 +31,12 @@ public abstract class AbstractPropertyValuesTests {
* Must contain: forname=Tony surname=Blair age=50 * Must contain: forname=Tony surname=Blair age=50
*/ */
protected void doTestTony(PropertyValues pvs) { protected void doTestTony(PropertyValues pvs) {
assertTrue("Contains 3", pvs.getPropertyValues().length == 3); assertThat(pvs.getPropertyValues().length == 3).as("Contains 3").isTrue();
assertTrue("Contains forname", pvs.contains("forname")); assertThat(pvs.contains("forname")).as("Contains forname").isTrue();
assertTrue("Contains surname", pvs.contains("surname")); assertThat(pvs.contains("surname")).as("Contains surname").isTrue();
assertTrue("Contains age", pvs.contains("age")); assertThat(pvs.contains("age")).as("Contains age").isTrue();
assertTrue("Doesn't contain tory", !pvs.contains("tory")); boolean condition1 = !pvs.contains("tory");
assertThat(condition1).as("Doesn't contain tory").isTrue();
PropertyValue[] ps = pvs.getPropertyValues(); PropertyValue[] ps = pvs.getPropertyValues();
Map<String, String> m = new HashMap<>(); Map<String, String> m = new HashMap<>();
@ -44,12 +45,13 @@ public abstract class AbstractPropertyValuesTests {
m.put("age", "50"); m.put("age", "50");
for (int i = 0; i < ps.length; i++) { for (int i = 0; i < ps.length; i++) {
Object val = m.get(ps[i].getName()); Object val = m.get(ps[i].getName());
assertTrue("Can't have unexpected value", val != null); assertThat(val != null).as("Can't have unexpected value").isTrue();
assertTrue("Val i string", val instanceof String); boolean condition = val instanceof String;
assertTrue("val matches expected", val.equals(ps[i].getValue())); assertThat(condition).as("Val i string").isTrue();
assertThat(val.equals(ps[i].getValue())).as("val matches expected").isTrue();
m.remove(ps[i].getName()); m.remove(ps[i].getName());
} }
assertTrue("Map size is 0", m.size() == 0); assertThat(m.size() == 0).as("Map size is 0").isTrue();
} }
} }

View File

@ -33,12 +33,9 @@ import org.springframework.tests.sample.beans.DerivedTestBean;
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.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
/** /**
* Unit tests for {@link BeanUtils}. * Unit tests for {@link BeanUtils}.
@ -68,18 +65,18 @@ public class BeanUtilsTests {
Constructor<BeanWithNullableTypes> ctor = BeanWithNullableTypes.class.getDeclaredConstructor( Constructor<BeanWithNullableTypes> ctor = BeanWithNullableTypes.class.getDeclaredConstructor(
Integer.class, Boolean.class, String.class); Integer.class, Boolean.class, String.class);
BeanWithNullableTypes bean = BeanUtils.instantiateClass(ctor, null, null, "foo"); BeanWithNullableTypes bean = BeanUtils.instantiateClass(ctor, null, null, "foo");
assertNull(bean.getCounter()); assertThat(bean.getCounter()).isNull();
assertNull(bean.isFlag()); assertThat(bean.isFlag()).isNull();
assertEquals("foo", bean.getValue()); assertThat(bean.getValue()).isEqualTo("foo");
} }
@Test // gh-22531 @Test // gh-22531
public void testInstantiateClassWithOptionalPrimitiveType() throws NoSuchMethodException { public void testInstantiateClassWithOptionalPrimitiveType() throws NoSuchMethodException {
Constructor<BeanWithPrimitiveTypes> ctor = BeanWithPrimitiveTypes.class.getDeclaredConstructor(int.class, boolean.class, String.class); Constructor<BeanWithPrimitiveTypes> ctor = BeanWithPrimitiveTypes.class.getDeclaredConstructor(int.class, boolean.class, String.class);
BeanWithPrimitiveTypes bean = BeanUtils.instantiateClass(ctor, null, null, "foo"); BeanWithPrimitiveTypes bean = BeanUtils.instantiateClass(ctor, null, null, "foo");
assertEquals(0, bean.getCounter()); assertThat(bean.getCounter()).isEqualTo(0);
assertEquals(false, bean.isFlag()); assertThat(bean.isFlag()).isEqualTo(false);
assertEquals("foo", bean.getValue()); assertThat(bean.getValue()).isEqualTo("foo");
} }
@Test // gh-22531 @Test // gh-22531
@ -93,8 +90,8 @@ public class BeanUtilsTests {
public void testGetPropertyDescriptors() throws Exception { public void testGetPropertyDescriptors() throws Exception {
PropertyDescriptor[] actual = Introspector.getBeanInfo(TestBean.class).getPropertyDescriptors(); PropertyDescriptor[] actual = Introspector.getBeanInfo(TestBean.class).getPropertyDescriptors();
PropertyDescriptor[] descriptors = BeanUtils.getPropertyDescriptors(TestBean.class); PropertyDescriptor[] descriptors = BeanUtils.getPropertyDescriptors(TestBean.class);
assertNotNull("Descriptors should not be null", descriptors); assertThat(descriptors).as("Descriptors should not be null").isNotNull();
assertEquals("Invalid number of descriptors returned", actual.length, descriptors.length); assertThat(descriptors.length).as("Invalid number of descriptors returned").isEqualTo(actual.length);
} }
@Test @Test
@ -102,15 +99,15 @@ public class BeanUtilsTests {
PropertyDescriptor[] descriptors = BeanUtils.getPropertyDescriptors(ContainerBean.class); PropertyDescriptor[] descriptors = BeanUtils.getPropertyDescriptors(ContainerBean.class);
for (PropertyDescriptor descriptor : descriptors) { for (PropertyDescriptor descriptor : descriptors) {
if ("containedBeans".equals(descriptor.getName())) { if ("containedBeans".equals(descriptor.getName())) {
assertTrue("Property should be an array", descriptor.getPropertyType().isArray()); assertThat(descriptor.getPropertyType().isArray()).as("Property should be an array").isTrue();
assertEquals(descriptor.getPropertyType().getComponentType(), ContainedBean.class); assertThat(ContainedBean.class).isEqualTo(descriptor.getPropertyType().getComponentType());
} }
} }
} }
@Test @Test
public void testFindEditorByConvention() { public void testFindEditorByConvention() {
assertEquals(ResourceEditor.class, BeanUtils.findEditorByConvention(Resource.class).getClass()); assertThat(BeanUtils.findEditorByConvention(Resource.class).getClass()).isEqualTo(ResourceEditor.class);
} }
@Test @Test
@ -120,13 +117,13 @@ public class BeanUtilsTests {
tb.setAge(32); tb.setAge(32);
tb.setTouchy("touchy"); tb.setTouchy("touchy");
TestBean tb2 = new TestBean(); TestBean tb2 = new TestBean();
assertTrue("Name empty", tb2.getName() == null); assertThat(tb2.getName() == null).as("Name empty").isTrue();
assertTrue("Age empty", tb2.getAge() == 0); assertThat(tb2.getAge() == 0).as("Age empty").isTrue();
assertTrue("Touchy empty", tb2.getTouchy() == null); assertThat(tb2.getTouchy() == null).as("Touchy empty").isTrue();
BeanUtils.copyProperties(tb, tb2); BeanUtils.copyProperties(tb, tb2);
assertTrue("Name copied", tb2.getName().equals(tb.getName())); assertThat(tb2.getName().equals(tb.getName())).as("Name copied").isTrue();
assertTrue("Age copied", tb2.getAge() == tb.getAge()); assertThat(tb2.getAge() == tb.getAge()).as("Age copied").isTrue();
assertTrue("Touchy copied", tb2.getTouchy().equals(tb.getTouchy())); assertThat(tb2.getTouchy().equals(tb.getTouchy())).as("Touchy copied").isTrue();
} }
@Test @Test
@ -136,13 +133,13 @@ public class BeanUtilsTests {
tb.setAge(32); tb.setAge(32);
tb.setTouchy("touchy"); tb.setTouchy("touchy");
TestBean tb2 = new TestBean(); TestBean tb2 = new TestBean();
assertTrue("Name empty", tb2.getName() == null); assertThat(tb2.getName() == null).as("Name empty").isTrue();
assertTrue("Age empty", tb2.getAge() == 0); assertThat(tb2.getAge() == 0).as("Age empty").isTrue();
assertTrue("Touchy empty", tb2.getTouchy() == null); assertThat(tb2.getTouchy() == null).as("Touchy empty").isTrue();
BeanUtils.copyProperties(tb, tb2); BeanUtils.copyProperties(tb, tb2);
assertTrue("Name copied", tb2.getName().equals(tb.getName())); assertThat(tb2.getName().equals(tb.getName())).as("Name copied").isTrue();
assertTrue("Age copied", tb2.getAge() == tb.getAge()); assertThat(tb2.getAge() == tb.getAge()).as("Age copied").isTrue();
assertTrue("Touchy copied", tb2.getTouchy().equals(tb.getTouchy())); assertThat(tb2.getTouchy().equals(tb.getTouchy())).as("Touchy copied").isTrue();
} }
@Test @Test
@ -152,49 +149,49 @@ public class BeanUtilsTests {
tb.setAge(32); tb.setAge(32);
tb.setTouchy("touchy"); tb.setTouchy("touchy");
DerivedTestBean tb2 = new DerivedTestBean(); DerivedTestBean tb2 = new DerivedTestBean();
assertTrue("Name empty", tb2.getName() == null); assertThat(tb2.getName() == null).as("Name empty").isTrue();
assertTrue("Age empty", tb2.getAge() == 0); assertThat(tb2.getAge() == 0).as("Age empty").isTrue();
assertTrue("Touchy empty", tb2.getTouchy() == null); assertThat(tb2.getTouchy() == null).as("Touchy empty").isTrue();
BeanUtils.copyProperties(tb, tb2); BeanUtils.copyProperties(tb, tb2);
assertTrue("Name copied", tb2.getName().equals(tb.getName())); assertThat(tb2.getName().equals(tb.getName())).as("Name copied").isTrue();
assertTrue("Age copied", tb2.getAge() == tb.getAge()); assertThat(tb2.getAge() == tb.getAge()).as("Age copied").isTrue();
assertTrue("Touchy copied", tb2.getTouchy().equals(tb.getTouchy())); assertThat(tb2.getTouchy().equals(tb.getTouchy())).as("Touchy copied").isTrue();
} }
@Test @Test
public void testCopyPropertiesWithEditable() throws Exception { public void testCopyPropertiesWithEditable() throws Exception {
TestBean tb = new TestBean(); TestBean tb = new TestBean();
assertTrue("Name empty", tb.getName() == null); assertThat(tb.getName() == null).as("Name empty").isTrue();
tb.setAge(32); tb.setAge(32);
tb.setTouchy("bla"); tb.setTouchy("bla");
TestBean tb2 = new TestBean(); TestBean tb2 = new TestBean();
tb2.setName("rod"); tb2.setName("rod");
assertTrue("Age empty", tb2.getAge() == 0); assertThat(tb2.getAge() == 0).as("Age empty").isTrue();
assertTrue("Touchy empty", tb2.getTouchy() == null); assertThat(tb2.getTouchy() == null).as("Touchy empty").isTrue();
// "touchy" should not be copied: it's not defined in ITestBean // "touchy" should not be copied: it's not defined in ITestBean
BeanUtils.copyProperties(tb, tb2, ITestBean.class); BeanUtils.copyProperties(tb, tb2, ITestBean.class);
assertTrue("Name copied", tb2.getName() == null); assertThat(tb2.getName() == null).as("Name copied").isTrue();
assertTrue("Age copied", tb2.getAge() == 32); assertThat(tb2.getAge() == 32).as("Age copied").isTrue();
assertTrue("Touchy still empty", tb2.getTouchy() == null); assertThat(tb2.getTouchy() == null).as("Touchy still empty").isTrue();
} }
@Test @Test
public void testCopyPropertiesWithIgnore() throws Exception { public void testCopyPropertiesWithIgnore() throws Exception {
TestBean tb = new TestBean(); TestBean tb = new TestBean();
assertTrue("Name empty", tb.getName() == null); assertThat(tb.getName() == null).as("Name empty").isTrue();
tb.setAge(32); tb.setAge(32);
tb.setTouchy("bla"); tb.setTouchy("bla");
TestBean tb2 = new TestBean(); TestBean tb2 = new TestBean();
tb2.setName("rod"); tb2.setName("rod");
assertTrue("Age empty", tb2.getAge() == 0); assertThat(tb2.getAge() == 0).as("Age empty").isTrue();
assertTrue("Touchy empty", tb2.getTouchy() == null); assertThat(tb2.getTouchy() == null).as("Touchy empty").isTrue();
// "spouse", "touchy", "age" should not be copied // "spouse", "touchy", "age" should not be copied
BeanUtils.copyProperties(tb, tb2, "spouse", "touchy", "age"); BeanUtils.copyProperties(tb, tb2, "spouse", "touchy", "age");
assertTrue("Name copied", tb2.getName() == null); assertThat(tb2.getName() == null).as("Name copied").isTrue();
assertTrue("Age still empty", tb2.getAge() == 0); assertThat(tb2.getAge() == 0).as("Age still empty").isTrue();
assertTrue("Touchy still empty", tb2.getTouchy() == null); assertThat(tb2.getTouchy() == null).as("Touchy still empty").isTrue();
} }
@Test @Test
@ -203,7 +200,7 @@ public class BeanUtilsTests {
source.setName("name"); source.setName("name");
TestBean target = new TestBean(); TestBean target = new TestBean();
BeanUtils.copyProperties(source, target, "specialProperty"); BeanUtils.copyProperties(source, target, "specialProperty");
assertEquals(target.getName(), "name"); assertThat("name").isEqualTo(target.getName());
} }
@Test @Test
@ -214,9 +211,9 @@ public class BeanUtilsTests {
source.setFlag2(true); source.setFlag2(true);
InvalidProperty target = new InvalidProperty(); InvalidProperty target = new InvalidProperty();
BeanUtils.copyProperties(source, target); BeanUtils.copyProperties(source, target);
assertEquals("name", target.getName()); assertThat(target.getName()).isEqualTo("name");
assertTrue(target.getFlag1()); assertThat((boolean) target.getFlag1()).isTrue();
assertTrue(target.getFlag2()); assertThat(target.getFlag2()).isTrue();
} }
@Test @Test
@ -242,7 +239,7 @@ public class BeanUtilsTests {
public void testResolveWithAndWithoutArgList() throws Exception { public void testResolveWithAndWithoutArgList() throws Exception {
Method desiredMethod = MethodSignatureBean.class.getMethod("doSomethingElse", String.class, int.class); Method desiredMethod = MethodSignatureBean.class.getMethod("doSomethingElse", String.class, int.class);
assertSignatureEquals(desiredMethod, "doSomethingElse"); assertSignatureEquals(desiredMethod, "doSomethingElse");
assertNull(BeanUtils.resolveSignature("doSomethingElse()", MethodSignatureBean.class)); assertThat(BeanUtils.resolveSignature("doSomethingElse()", MethodSignatureBean.class)).isNull();
} }
@Test @Test
@ -280,17 +277,16 @@ public class BeanUtilsTests {
PropertyDescriptor[] descrs = BeanUtils.getPropertyDescriptors(Bean.class); PropertyDescriptor[] descrs = BeanUtils.getPropertyDescriptors(Bean.class);
PropertyDescriptor keyDescr = BeanUtils.getPropertyDescriptor(Bean.class, "value"); PropertyDescriptor keyDescr = BeanUtils.getPropertyDescriptor(Bean.class, "value");
assertEquals(String.class, keyDescr.getPropertyType()); assertThat(keyDescr.getPropertyType()).isEqualTo(String.class);
for (PropertyDescriptor propertyDescriptor : descrs) { for (PropertyDescriptor propertyDescriptor : descrs) {
if (propertyDescriptor.getName().equals(keyDescr.getName())) { if (propertyDescriptor.getName().equals(keyDescr.getName())) {
assertEquals(propertyDescriptor.getName() + " has unexpected type", assertThat(propertyDescriptor.getPropertyType()).as(propertyDescriptor.getName() + " has unexpected type").isEqualTo(keyDescr.getPropertyType());
keyDescr.getPropertyType(), propertyDescriptor.getPropertyType());
} }
} }
} }
private void assertSignatureEquals(Method desiredMethod, String signature) { private void assertSignatureEquals(Method desiredMethod, String signature) {
assertEquals(desiredMethod, BeanUtils.resolveSignature(signature, MethodSignatureBean.class)); assertThat(BeanUtils.resolveSignature(signature, MethodSignatureBean.class)).isEqualTo(desiredMethod);
} }

View File

@ -24,9 +24,6 @@ import org.junit.Test;
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.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
/** /**
* @author Keith Donald * @author Keith Donald
@ -47,13 +44,13 @@ public class BeanWrapperAutoGrowingTests {
@Test @Test
public void getPropertyValueNullValueInNestedPath() { public void getPropertyValueNullValueInNestedPath() {
assertNull(wrapper.getPropertyValue("nested.prop")); assertThat(wrapper.getPropertyValue("nested.prop")).isNull();
} }
@Test @Test
public void setPropertyValueNullValueInNestedPath() { public void setPropertyValueNullValueInNestedPath() {
wrapper.setPropertyValue("nested.prop", "test"); wrapper.setPropertyValue("nested.prop", "test");
assertEquals("test", bean.getNested().getProp()); assertThat(bean.getNested().getProp()).isEqualTo("test");
} }
@Test @Test
@ -65,20 +62,25 @@ public class BeanWrapperAutoGrowingTests {
@Test @Test
public void getPropertyValueAutoGrowArray() { public void getPropertyValueAutoGrowArray() {
assertNotNull(wrapper.getPropertyValue("array[0]")); assertNotNull(wrapper.getPropertyValue("array[0]"));
assertEquals(1, bean.getArray().length); assertThat(bean.getArray().length).isEqualTo(1);
assertThat(bean.getArray()[0]).isInstanceOf(Bean.class); assertThat(bean.getArray()[0]).isInstanceOf(Bean.class);
} }
private void assertNotNull(Object propertyValue) {
assertThat(propertyValue).isNotNull();
}
@Test @Test
public void setPropertyValueAutoGrowArray() { public void setPropertyValueAutoGrowArray() {
wrapper.setPropertyValue("array[0].prop", "test"); wrapper.setPropertyValue("array[0].prop", "test");
assertEquals("test", bean.getArray()[0].getProp()); assertThat(bean.getArray()[0].getProp()).isEqualTo("test");
} }
@Test @Test
public void getPropertyValueAutoGrowArrayBySeveralElements() { public void getPropertyValueAutoGrowArrayBySeveralElements() {
assertNotNull(wrapper.getPropertyValue("array[4]")); assertNotNull(wrapper.getPropertyValue("array[4]"));
assertEquals(5, bean.getArray().length); assertThat(bean.getArray().length).isEqualTo(5);
assertThat(bean.getArray()[0]).isInstanceOf(Bean.class); assertThat(bean.getArray()[0]).isInstanceOf(Bean.class);
assertThat(bean.getArray()[1]).isInstanceOf(Bean.class); assertThat(bean.getArray()[1]).isInstanceOf(Bean.class);
assertThat(bean.getArray()[2]).isInstanceOf(Bean.class); assertThat(bean.getArray()[2]).isInstanceOf(Bean.class);
@ -93,27 +95,27 @@ public class BeanWrapperAutoGrowingTests {
@Test @Test
public void getPropertyValueAutoGrowMultiDimensionalArray() { public void getPropertyValueAutoGrowMultiDimensionalArray() {
assertNotNull(wrapper.getPropertyValue("multiArray[0][0]")); assertNotNull(wrapper.getPropertyValue("multiArray[0][0]"));
assertEquals(1, bean.getMultiArray()[0].length); assertThat(bean.getMultiArray()[0].length).isEqualTo(1);
assertThat(bean.getMultiArray()[0][0]).isInstanceOf(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()); assertThat(bean.getList().size()).isEqualTo(1);
assertThat(bean.getList().get(0)).isInstanceOf(Bean.class); assertThat(bean.getList().get(0)).isInstanceOf(Bean.class);
} }
@Test @Test
public void setPropertyValueAutoGrowList() { public void setPropertyValueAutoGrowList() {
wrapper.setPropertyValue("list[0].prop", "test"); wrapper.setPropertyValue("list[0].prop", "test");
assertEquals("test", bean.getList().get(0).getProp()); assertThat(bean.getList().get(0).getProp()).isEqualTo("test");
} }
@Test @Test
public void getPropertyValueAutoGrowListBySeveralElements() { public void getPropertyValueAutoGrowListBySeveralElements() {
assertNotNull(wrapper.getPropertyValue("list[4]")); assertNotNull(wrapper.getPropertyValue("list[4]"));
assertEquals(5, bean.getList().size()); assertThat(bean.getList().size()).isEqualTo(5);
assertThat(bean.getList().get(0)).isInstanceOf(Bean.class); assertThat(bean.getList().get(0)).isInstanceOf(Bean.class);
assertThat(bean.getList().get(1)).isInstanceOf(Bean.class); assertThat(bean.getList().get(1)).isInstanceOf(Bean.class);
assertThat(bean.getList().get(2)).isInstanceOf(Bean.class); assertThat(bean.getList().get(2)).isInstanceOf(Bean.class);
@ -136,7 +138,7 @@ public class BeanWrapperAutoGrowingTests {
@Test @Test
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()); assertThat(bean.getMultiList().get(0).size()).isEqualTo(1);
assertThat(bean.getMultiList().get(0).get(0)).isInstanceOf(Bean.class); assertThat(bean.getMultiList().get(0).get(0)).isInstanceOf(Bean.class);
} }

View File

@ -25,9 +25,7 @@ import org.springframework.core.convert.support.DefaultConversionService;
import org.springframework.tests.sample.beans.CustomEnum; import org.springframework.tests.sample.beans.CustomEnum;
import org.springframework.tests.sample.beans.GenericBean; import org.springframework.tests.sample.beans.GenericBean;
import static org.junit.Assert.assertEquals; import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
/** /**
* @author Juergen Hoeller * @author Juergen Hoeller
@ -40,7 +38,7 @@ public class BeanWrapperEnumTests {
GenericBean<?> gb = new GenericBean<>(); GenericBean<?> gb = new GenericBean<>();
BeanWrapper bw = new BeanWrapperImpl(gb); BeanWrapper bw = new BeanWrapperImpl(gb);
bw.setPropertyValue("customEnum", "VALUE_1"); bw.setPropertyValue("customEnum", "VALUE_1");
assertEquals(CustomEnum.VALUE_1, gb.getCustomEnum()); assertThat(gb.getCustomEnum()).isEqualTo(CustomEnum.VALUE_1);
} }
@Test @Test
@ -48,7 +46,7 @@ public class BeanWrapperEnumTests {
GenericBean<?> gb = new GenericBean<>(); GenericBean<?> gb = new GenericBean<>();
BeanWrapper bw = new BeanWrapperImpl(gb); BeanWrapper bw = new BeanWrapperImpl(gb);
bw.setPropertyValue("customEnum", null); bw.setPropertyValue("customEnum", null);
assertEquals(null, gb.getCustomEnum()); assertThat(gb.getCustomEnum()).isEqualTo(null);
} }
@Test @Test
@ -56,7 +54,7 @@ public class BeanWrapperEnumTests {
GenericBean<?> gb = new GenericBean<>(); GenericBean<?> gb = new GenericBean<>();
BeanWrapper bw = new BeanWrapperImpl(gb); BeanWrapper bw = new BeanWrapperImpl(gb);
bw.setPropertyValue("customEnum", ""); bw.setPropertyValue("customEnum", "");
assertEquals(null, gb.getCustomEnum()); assertThat(gb.getCustomEnum()).isEqualTo(null);
} }
@Test @Test
@ -64,8 +62,8 @@ public class BeanWrapperEnumTests {
GenericBean<?> gb = new GenericBean<>(); GenericBean<?> gb = new GenericBean<>();
BeanWrapper bw = new BeanWrapperImpl(gb); BeanWrapper bw = new BeanWrapperImpl(gb);
bw.setPropertyValue("customEnumArray", "VALUE_1"); bw.setPropertyValue("customEnumArray", "VALUE_1");
assertEquals(1, gb.getCustomEnumArray().length); assertThat(gb.getCustomEnumArray().length).isEqualTo(1);
assertEquals(CustomEnum.VALUE_1, gb.getCustomEnumArray()[0]); assertThat(gb.getCustomEnumArray()[0]).isEqualTo(CustomEnum.VALUE_1);
} }
@Test @Test
@ -73,9 +71,9 @@ public class BeanWrapperEnumTests {
GenericBean<?> gb = new GenericBean<>(); GenericBean<?> gb = new GenericBean<>();
BeanWrapper bw = new BeanWrapperImpl(gb); BeanWrapper bw = new BeanWrapperImpl(gb);
bw.setPropertyValue("customEnumArray", new String[] {"VALUE_1", "VALUE_2"}); bw.setPropertyValue("customEnumArray", new String[] {"VALUE_1", "VALUE_2"});
assertEquals(2, gb.getCustomEnumArray().length); assertThat(gb.getCustomEnumArray().length).isEqualTo(2);
assertEquals(CustomEnum.VALUE_1, gb.getCustomEnumArray()[0]); assertThat(gb.getCustomEnumArray()[0]).isEqualTo(CustomEnum.VALUE_1);
assertEquals(CustomEnum.VALUE_2, gb.getCustomEnumArray()[1]); assertThat(gb.getCustomEnumArray()[1]).isEqualTo(CustomEnum.VALUE_2);
} }
@Test @Test
@ -83,9 +81,9 @@ public class BeanWrapperEnumTests {
GenericBean<?> gb = new GenericBean<>(); GenericBean<?> gb = new GenericBean<>();
BeanWrapper bw = new BeanWrapperImpl(gb); BeanWrapper bw = new BeanWrapperImpl(gb);
bw.setPropertyValue("customEnumArray", "VALUE_1,VALUE_2"); bw.setPropertyValue("customEnumArray", "VALUE_1,VALUE_2");
assertEquals(2, gb.getCustomEnumArray().length); assertThat(gb.getCustomEnumArray().length).isEqualTo(2);
assertEquals(CustomEnum.VALUE_1, gb.getCustomEnumArray()[0]); assertThat(gb.getCustomEnumArray()[0]).isEqualTo(CustomEnum.VALUE_1);
assertEquals(CustomEnum.VALUE_2, gb.getCustomEnumArray()[1]); assertThat(gb.getCustomEnumArray()[1]).isEqualTo(CustomEnum.VALUE_2);
} }
@Test @Test
@ -93,8 +91,8 @@ public class BeanWrapperEnumTests {
GenericBean<?> gb = new GenericBean<>(); GenericBean<?> gb = new GenericBean<>();
BeanWrapper bw = new BeanWrapperImpl(gb); BeanWrapper bw = new BeanWrapperImpl(gb);
bw.setPropertyValue("customEnumSet", "VALUE_1"); bw.setPropertyValue("customEnumSet", "VALUE_1");
assertEquals(1, gb.getCustomEnumSet().size()); assertThat(gb.getCustomEnumSet().size()).isEqualTo(1);
assertTrue(gb.getCustomEnumSet().contains(CustomEnum.VALUE_1)); assertThat(gb.getCustomEnumSet().contains(CustomEnum.VALUE_1)).isTrue();
} }
@Test @Test
@ -102,9 +100,9 @@ public class BeanWrapperEnumTests {
GenericBean<?> gb = new GenericBean<>(); GenericBean<?> gb = new GenericBean<>();
BeanWrapper bw = new BeanWrapperImpl(gb); BeanWrapper bw = new BeanWrapperImpl(gb);
bw.setPropertyValue("customEnumSet", new String[] {"VALUE_1", "VALUE_2"}); bw.setPropertyValue("customEnumSet", new String[] {"VALUE_1", "VALUE_2"});
assertEquals(2, gb.getCustomEnumSet().size()); assertThat(gb.getCustomEnumSet().size()).isEqualTo(2);
assertTrue(gb.getCustomEnumSet().contains(CustomEnum.VALUE_1)); assertThat(gb.getCustomEnumSet().contains(CustomEnum.VALUE_1)).isTrue();
assertTrue(gb.getCustomEnumSet().contains(CustomEnum.VALUE_2)); assertThat(gb.getCustomEnumSet().contains(CustomEnum.VALUE_2)).isTrue();
} }
@Test @Test
@ -112,9 +110,9 @@ public class BeanWrapperEnumTests {
GenericBean<?> gb = new GenericBean<>(); GenericBean<?> gb = new GenericBean<>();
BeanWrapper bw = new BeanWrapperImpl(gb); BeanWrapper bw = new BeanWrapperImpl(gb);
bw.setPropertyValue("customEnumSet", "VALUE_1,VALUE_2"); bw.setPropertyValue("customEnumSet", "VALUE_1,VALUE_2");
assertEquals(2, gb.getCustomEnumSet().size()); assertThat(gb.getCustomEnumSet().size()).isEqualTo(2);
assertTrue(gb.getCustomEnumSet().contains(CustomEnum.VALUE_1)); assertThat(gb.getCustomEnumSet().contains(CustomEnum.VALUE_1)).isTrue();
assertTrue(gb.getCustomEnumSet().contains(CustomEnum.VALUE_2)); assertThat(gb.getCustomEnumSet().contains(CustomEnum.VALUE_2)).isTrue();
} }
@Test @Test
@ -122,9 +120,9 @@ public class BeanWrapperEnumTests {
GenericBean<?> gb = new GenericBean<>(); GenericBean<?> gb = new GenericBean<>();
BeanWrapper bw = new BeanWrapperImpl(gb); BeanWrapper bw = new BeanWrapperImpl(gb);
bw.setPropertyValue("customEnumSetMismatch", new String[] {"VALUE_1", "VALUE_2"}); bw.setPropertyValue("customEnumSetMismatch", new String[] {"VALUE_1", "VALUE_2"});
assertEquals(2, gb.getCustomEnumSet().size()); assertThat(gb.getCustomEnumSet().size()).isEqualTo(2);
assertTrue(gb.getCustomEnumSet().contains(CustomEnum.VALUE_1)); assertThat(gb.getCustomEnumSet().contains(CustomEnum.VALUE_1)).isTrue();
assertTrue(gb.getCustomEnumSet().contains(CustomEnum.VALUE_2)); assertThat(gb.getCustomEnumSet().contains(CustomEnum.VALUE_2)).isTrue();
} }
@Test @Test
@ -132,11 +130,11 @@ public class BeanWrapperEnumTests {
GenericBean<?> gb = new GenericBean<>(); GenericBean<?> gb = new GenericBean<>();
BeanWrapper bw = new BeanWrapperImpl(gb); BeanWrapper bw = new BeanWrapperImpl(gb);
bw.setConversionService(new DefaultConversionService()); bw.setConversionService(new DefaultConversionService());
assertNull(gb.getStandardEnumSet()); assertThat(gb.getStandardEnumSet()).isNull();
bw.setPropertyValue("standardEnumSet", new String[] {"VALUE_1", "VALUE_2"}); bw.setPropertyValue("standardEnumSet", new String[] {"VALUE_1", "VALUE_2"});
assertEquals(2, gb.getStandardEnumSet().size()); assertThat(gb.getStandardEnumSet().size()).isEqualTo(2);
assertTrue(gb.getStandardEnumSet().contains(CustomEnum.VALUE_1)); assertThat(gb.getStandardEnumSet().contains(CustomEnum.VALUE_1)).isTrue();
assertTrue(gb.getStandardEnumSet().contains(CustomEnum.VALUE_2)); assertThat(gb.getStandardEnumSet().contains(CustomEnum.VALUE_2)).isTrue();
} }
@Test @Test
@ -144,9 +142,9 @@ public class BeanWrapperEnumTests {
GenericBean<?> gb = new GenericBean<>(); GenericBean<?> gb = new GenericBean<>();
BeanWrapper bw = new BeanWrapperImpl(gb); BeanWrapper bw = new BeanWrapperImpl(gb);
bw.setAutoGrowNestedPaths(true); bw.setAutoGrowNestedPaths(true);
assertNull(gb.getStandardEnumSet()); assertThat(gb.getStandardEnumSet()).isNull();
bw.getPropertyValue("standardEnumSet.class"); bw.getPropertyValue("standardEnumSet.class");
assertEquals(0, gb.getStandardEnumSet().size()); assertThat(gb.getStandardEnumSet().size()).isEqualTo(0);
} }
@Test @Test
@ -154,14 +152,14 @@ public class BeanWrapperEnumTests {
GenericBean<?> gb = new GenericBean<>(); GenericBean<?> gb = new GenericBean<>();
BeanWrapper bw = new BeanWrapperImpl(gb); BeanWrapper bw = new BeanWrapperImpl(gb);
bw.setConversionService(new DefaultConversionService()); bw.setConversionService(new DefaultConversionService());
assertNull(gb.getStandardEnumMap()); assertThat(gb.getStandardEnumMap()).isNull();
Map<String, Integer> map = new LinkedHashMap<>(); Map<String, Integer> map = new LinkedHashMap<>();
map.put("VALUE_1", 1); map.put("VALUE_1", 1);
map.put("VALUE_2", 2); map.put("VALUE_2", 2);
bw.setPropertyValue("standardEnumMap", map); bw.setPropertyValue("standardEnumMap", map);
assertEquals(2, gb.getStandardEnumMap().size()); assertThat(gb.getStandardEnumMap().size()).isEqualTo(2);
assertEquals(new Integer(1), gb.getStandardEnumMap().get(CustomEnum.VALUE_1)); assertThat(gb.getStandardEnumMap().get(CustomEnum.VALUE_1)).isEqualTo(new Integer(1));
assertEquals(new Integer(2), gb.getStandardEnumMap().get(CustomEnum.VALUE_2)); assertThat(gb.getStandardEnumMap().get(CustomEnum.VALUE_2)).isEqualTo(new Integer(2));
} }
@Test @Test
@ -169,10 +167,10 @@ public class BeanWrapperEnumTests {
GenericBean<?> gb = new GenericBean<>(); GenericBean<?> gb = new GenericBean<>();
BeanWrapper bw = new BeanWrapperImpl(gb); BeanWrapper bw = new BeanWrapperImpl(gb);
bw.setAutoGrowNestedPaths(true); bw.setAutoGrowNestedPaths(true);
assertNull(gb.getStandardEnumMap()); assertThat(gb.getStandardEnumMap()).isNull();
bw.setPropertyValue("standardEnumMap[VALUE_1]", 1); bw.setPropertyValue("standardEnumMap[VALUE_1]", 1);
assertEquals(1, gb.getStandardEnumMap().size()); assertThat(gb.getStandardEnumMap().size()).isEqualTo(1);
assertEquals(new Integer(1), gb.getStandardEnumMap().get(CustomEnum.VALUE_1)); assertThat(gb.getStandardEnumMap().get(CustomEnum.VALUE_1)).isEqualTo(new Integer(1));
} }
@Test @Test
@ -180,7 +178,7 @@ public class BeanWrapperEnumTests {
NonPublicEnumHolder holder = new NonPublicEnumHolder(); NonPublicEnumHolder holder = new NonPublicEnumHolder();
BeanWrapper bw = new BeanWrapperImpl(holder); BeanWrapper bw = new BeanWrapperImpl(holder);
bw.setPropertyValue("nonPublicEnum", "VALUE_1"); bw.setPropertyValue("nonPublicEnum", "VALUE_1");
assertEquals(NonPublicEnum.VALUE_1, holder.getNonPublicEnum()); assertThat(holder.getNonPublicEnum()).isEqualTo(NonPublicEnum.VALUE_1);
} }

View File

@ -39,9 +39,8 @@ import org.springframework.tests.sample.beans.GenericIntegerBean;
import org.springframework.tests.sample.beans.GenericSetOfIntegerBean; import org.springframework.tests.sample.beans.GenericSetOfIntegerBean;
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.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
/** /**
* @author Juergen Hoeller * @author Juergen Hoeller
@ -58,8 +57,8 @@ public class BeanWrapperGenericsTests {
input.add("4"); input.add("4");
input.add("5"); input.add("5");
bw.setPropertyValue("integerSet", input); bw.setPropertyValue("integerSet", input);
assertTrue(gb.getIntegerSet().contains(new Integer(4))); assertThat(gb.getIntegerSet().contains(new Integer(4))).isTrue();
assertTrue(gb.getIntegerSet().contains(new Integer(5))); assertThat(gb.getIntegerSet().contains(new Integer(5))).isTrue();
} }
@Test @Test
@ -71,8 +70,8 @@ public class BeanWrapperGenericsTests {
input.add("4"); input.add("4");
input.add("5"); input.add("5");
bw.setPropertyValue("numberSet", input); bw.setPropertyValue("numberSet", input);
assertTrue(gb.getNumberSet().contains(new Integer(4))); assertThat(gb.getNumberSet().contains(new Integer(4))).isTrue();
assertTrue(gb.getNumberSet().contains(new Integer(5))); assertThat(gb.getNumberSet().contains(new Integer(5))).isTrue();
} }
@Test @Test
@ -94,8 +93,8 @@ public class BeanWrapperGenericsTests {
input.add("http://localhost:8080"); input.add("http://localhost:8080");
input.add("http://localhost:9090"); input.add("http://localhost:9090");
bw.setPropertyValue("resourceList", input); bw.setPropertyValue("resourceList", input);
assertEquals(new UrlResource("http://localhost:8080"), gb.getResourceList().get(0)); assertThat(gb.getResourceList().get(0)).isEqualTo(new UrlResource("http://localhost:8080"));
assertEquals(new UrlResource("http://localhost:9090"), gb.getResourceList().get(1)); assertThat(gb.getResourceList().get(1)).isEqualTo(new UrlResource("http://localhost:9090"));
} }
@Test @Test
@ -104,7 +103,7 @@ public class BeanWrapperGenericsTests {
gb.setResourceList(new ArrayList<>()); gb.setResourceList(new ArrayList<>());
BeanWrapper bw = new BeanWrapperImpl(gb); BeanWrapper bw = new BeanWrapperImpl(gb);
bw.setPropertyValue("resourceList[0]", "http://localhost:8080"); bw.setPropertyValue("resourceList[0]", "http://localhost:8080");
assertEquals(new UrlResource("http://localhost:8080"), gb.getResourceList().get(0)); assertThat(gb.getResourceList().get(0)).isEqualTo(new UrlResource("http://localhost:8080"));
} }
@Test @Test
@ -115,8 +114,8 @@ public class BeanWrapperGenericsTests {
input.put("4", "5"); input.put("4", "5");
input.put("6", "7"); input.put("6", "7");
bw.setPropertyValue("shortMap", input); bw.setPropertyValue("shortMap", input);
assertEquals(new Integer(5), gb.getShortMap().get(new Short("4"))); assertThat(gb.getShortMap().get(new Short("4"))).isEqualTo(new Integer(5));
assertEquals(new Integer(7), gb.getShortMap().get(new Short("6"))); assertThat(gb.getShortMap().get(new Short("6"))).isEqualTo(new Integer(7));
} }
@Test @Test
@ -125,8 +124,8 @@ public class BeanWrapperGenericsTests {
gb.setShortMap(new HashMap<>()); gb.setShortMap(new HashMap<>());
BeanWrapper bw = new BeanWrapperImpl(gb); BeanWrapper bw = new BeanWrapperImpl(gb);
bw.setPropertyValue("shortMap[4]", "5"); bw.setPropertyValue("shortMap[4]", "5");
assertEquals(new Integer(5), bw.getPropertyValue("shortMap[4]")); assertThat(bw.getPropertyValue("shortMap[4]")).isEqualTo(new Integer(5));
assertEquals(new Integer(5), gb.getShortMap().get(new Short("4"))); assertThat(gb.getShortMap().get(new Short("4"))).isEqualTo(new Integer(5));
} }
@Test @Test
@ -137,8 +136,8 @@ public class BeanWrapperGenericsTests {
input.put("4", "5"); input.put("4", "5");
input.put("6", "7"); input.put("6", "7");
bw.setPropertyValue("longMap", input); bw.setPropertyValue("longMap", input);
assertEquals("5", gb.getLongMap().get(new Long("4"))); assertThat(gb.getLongMap().get(new Long("4"))).isEqualTo("5");
assertEquals("7", gb.getLongMap().get(new Long("6"))); assertThat(gb.getLongMap().get(new Long("6"))).isEqualTo("7");
} }
@Test @Test
@ -147,8 +146,8 @@ public class BeanWrapperGenericsTests {
gb.setLongMap(new HashMap<Long, Integer>()); gb.setLongMap(new HashMap<Long, Integer>());
BeanWrapper bw = new BeanWrapperImpl(gb); BeanWrapper bw = new BeanWrapperImpl(gb);
bw.setPropertyValue("longMap[4]", "5"); bw.setPropertyValue("longMap[4]", "5");
assertEquals("5", gb.getLongMap().get(new Long("4"))); assertThat(gb.getLongMap().get(new Long("4"))).isEqualTo("5");
assertEquals("5", bw.getPropertyValue("longMap[4]")); assertThat(bw.getPropertyValue("longMap[4]")).isEqualTo("5");
} }
@Test @Test
@ -164,8 +163,10 @@ public class BeanWrapperGenericsTests {
value2.add(Boolean.TRUE); value2.add(Boolean.TRUE);
input.put("2", value2); input.put("2", value2);
bw.setPropertyValue("collectionMap", input); bw.setPropertyValue("collectionMap", input);
assertTrue(gb.getCollectionMap().get(new Integer(1)) instanceof HashSet); boolean condition1 = gb.getCollectionMap().get(new Integer(1)) instanceof HashSet;
assertTrue(gb.getCollectionMap().get(new Integer(2)) instanceof ArrayList); assertThat(condition1).isTrue();
boolean condition = gb.getCollectionMap().get(new Integer(2)) instanceof ArrayList;
assertThat(condition).isTrue();
} }
@Test @Test
@ -177,7 +178,8 @@ public class BeanWrapperGenericsTests {
HashSet<Integer> value1 = new HashSet<>(); HashSet<Integer> value1 = new HashSet<>();
value1.add(new Integer(1)); value1.add(new Integer(1));
bw.setPropertyValue("collectionMap[1]", value1); bw.setPropertyValue("collectionMap[1]", value1);
assertTrue(gb.getCollectionMap().get(new Integer(1)) instanceof HashSet); boolean condition = gb.getCollectionMap().get(new Integer(1)) instanceof HashSet;
assertThat(condition).isTrue();
} }
@Test @Test
@ -188,8 +190,8 @@ public class BeanWrapperGenericsTests {
input.setProperty("4", "5"); input.setProperty("4", "5");
input.setProperty("6", "7"); input.setProperty("6", "7");
bw.setPropertyValue("shortMap", input); bw.setPropertyValue("shortMap", input);
assertEquals(new Integer(5), gb.getShortMap().get(new Short("4"))); assertThat(gb.getShortMap().get(new Short("4"))).isEqualTo(new Integer(5));
assertEquals(new Integer(7), gb.getShortMap().get(new Short("6"))); assertThat(gb.getShortMap().get(new Short("6"))).isEqualTo(new Integer(7));
} }
@Test @Test
@ -200,8 +202,8 @@ public class BeanWrapperGenericsTests {
gb.setListOfLists(list); gb.setListOfLists(list);
BeanWrapper bw = new BeanWrapperImpl(gb); BeanWrapper bw = new BeanWrapperImpl(gb);
bw.setPropertyValue("listOfLists[0][0]", new Integer(5)); bw.setPropertyValue("listOfLists[0][0]", new Integer(5));
assertEquals(new Integer(5), bw.getPropertyValue("listOfLists[0][0]")); assertThat(bw.getPropertyValue("listOfLists[0][0]")).isEqualTo(new Integer(5));
assertEquals(new Integer(5), gb.getListOfLists().get(0).get(0)); assertThat(gb.getListOfLists().get(0).get(0)).isEqualTo(new Integer(5));
} }
@Test @Test
@ -212,8 +214,8 @@ public class BeanWrapperGenericsTests {
gb.setListOfLists(list); gb.setListOfLists(list);
BeanWrapper bw = new BeanWrapperImpl(gb); BeanWrapper bw = new BeanWrapperImpl(gb);
bw.setPropertyValue("listOfLists[0][0]", "5"); bw.setPropertyValue("listOfLists[0][0]", "5");
assertEquals(new Integer(5), bw.getPropertyValue("listOfLists[0][0]")); assertThat(bw.getPropertyValue("listOfLists[0][0]")).isEqualTo(new Integer(5));
assertEquals(new Integer(5), gb.getListOfLists().get(0).get(0)); assertThat(gb.getListOfLists().get(0).get(0)).isEqualTo(new Integer(5));
} }
@Test @Test
@ -224,8 +226,8 @@ public class BeanWrapperGenericsTests {
gb.setListOfArrays(list); gb.setListOfArrays(list);
BeanWrapper bw = new BeanWrapperImpl(gb); BeanWrapper bw = new BeanWrapperImpl(gb);
bw.setPropertyValue("listOfArrays[0][1]", "str3 "); bw.setPropertyValue("listOfArrays[0][1]", "str3 ");
assertEquals("str3 ", bw.getPropertyValue("listOfArrays[0][1]")); assertThat(bw.getPropertyValue("listOfArrays[0][1]")).isEqualTo("str3 ");
assertEquals("str3 ", gb.getListOfArrays().get(0)[1]); assertThat(gb.getListOfArrays().get(0)[1]).isEqualTo("str3 ");
} }
@Test @Test
@ -237,8 +239,8 @@ public class BeanWrapperGenericsTests {
BeanWrapper bw = new BeanWrapperImpl(gb); BeanWrapper bw = new BeanWrapperImpl(gb);
bw.registerCustomEditor(String.class, new StringTrimmerEditor(false)); bw.registerCustomEditor(String.class, new StringTrimmerEditor(false));
bw.setPropertyValue("listOfArrays[0][1]", "str3 "); bw.setPropertyValue("listOfArrays[0][1]", "str3 ");
assertEquals("str3", bw.getPropertyValue("listOfArrays[0][1]")); assertThat(bw.getPropertyValue("listOfArrays[0][1]")).isEqualTo("str3");
assertEquals("str3", gb.getListOfArrays().get(0)[1]); assertThat(gb.getListOfArrays().get(0)[1]).isEqualTo("str3");
} }
@Test @Test
@ -249,8 +251,8 @@ public class BeanWrapperGenericsTests {
gb.setListOfMaps(list); gb.setListOfMaps(list);
BeanWrapper bw = new BeanWrapperImpl(gb); BeanWrapper bw = new BeanWrapperImpl(gb);
bw.setPropertyValue("listOfMaps[0][10]", new Long(5)); bw.setPropertyValue("listOfMaps[0][10]", new Long(5));
assertEquals(new Long(5), bw.getPropertyValue("listOfMaps[0][10]")); assertThat(bw.getPropertyValue("listOfMaps[0][10]")).isEqualTo(new Long(5));
assertEquals(new Long(5), gb.getListOfMaps().get(0).get(10)); assertThat(gb.getListOfMaps().get(0).get(10)).isEqualTo(new Long(5));
} }
@Test @Test
@ -261,8 +263,8 @@ public class BeanWrapperGenericsTests {
gb.setListOfMaps(list); gb.setListOfMaps(list);
BeanWrapper bw = new BeanWrapperImpl(gb); BeanWrapper bw = new BeanWrapperImpl(gb);
bw.setPropertyValue("listOfMaps[0][10]", "5"); bw.setPropertyValue("listOfMaps[0][10]", "5");
assertEquals(new Long(5), bw.getPropertyValue("listOfMaps[0][10]")); assertThat(bw.getPropertyValue("listOfMaps[0][10]")).isEqualTo(new Long(5));
assertEquals(new Long(5), gb.getListOfMaps().get(0).get(10)); assertThat(gb.getListOfMaps().get(0).get(10)).isEqualTo(new Long(5));
} }
@Test @Test
@ -273,8 +275,8 @@ public class BeanWrapperGenericsTests {
gb.setMapOfMaps(map); gb.setMapOfMaps(map);
BeanWrapper bw = new BeanWrapperImpl(gb); BeanWrapper bw = new BeanWrapperImpl(gb);
bw.setPropertyValue("mapOfMaps[mykey][10]", new Long(5)); bw.setPropertyValue("mapOfMaps[mykey][10]", new Long(5));
assertEquals(new Long(5), bw.getPropertyValue("mapOfMaps[mykey][10]")); assertThat(bw.getPropertyValue("mapOfMaps[mykey][10]")).isEqualTo(new Long(5));
assertEquals(new Long(5), gb.getMapOfMaps().get("mykey").get(10)); assertThat(gb.getMapOfMaps().get("mykey").get(10)).isEqualTo(new Long(5));
} }
@Test @Test
@ -285,8 +287,8 @@ public class BeanWrapperGenericsTests {
gb.setMapOfMaps(map); gb.setMapOfMaps(map);
BeanWrapper bw = new BeanWrapperImpl(gb); BeanWrapper bw = new BeanWrapperImpl(gb);
bw.setPropertyValue("mapOfMaps[mykey][10]", "5"); bw.setPropertyValue("mapOfMaps[mykey][10]", "5");
assertEquals(new Long(5), bw.getPropertyValue("mapOfMaps[mykey][10]")); assertThat(bw.getPropertyValue("mapOfMaps[mykey][10]")).isEqualTo(new Long(5));
assertEquals(new Long(5), gb.getMapOfMaps().get("mykey").get(10)); assertThat(gb.getMapOfMaps().get("mykey").get(10)).isEqualTo(new Long(5));
} }
@Test @Test
@ -297,8 +299,8 @@ public class BeanWrapperGenericsTests {
gb.setMapOfLists(map); gb.setMapOfLists(map);
BeanWrapper bw = new BeanWrapperImpl(gb); BeanWrapper bw = new BeanWrapperImpl(gb);
bw.setPropertyValue("mapOfLists[1][0]", new Integer(5)); bw.setPropertyValue("mapOfLists[1][0]", new Integer(5));
assertEquals(new Integer(5), bw.getPropertyValue("mapOfLists[1][0]")); assertThat(bw.getPropertyValue("mapOfLists[1][0]")).isEqualTo(new Integer(5));
assertEquals(new Integer(5), gb.getMapOfLists().get(new Integer(1)).get(0)); assertThat(gb.getMapOfLists().get(new Integer(1)).get(0)).isEqualTo(new Integer(5));
} }
@Test @Test
@ -309,8 +311,8 @@ public class BeanWrapperGenericsTests {
gb.setMapOfLists(map); gb.setMapOfLists(map);
BeanWrapper bw = new BeanWrapperImpl(gb); BeanWrapper bw = new BeanWrapperImpl(gb);
bw.setPropertyValue("mapOfLists[1][0]", "5"); bw.setPropertyValue("mapOfLists[1][0]", "5");
assertEquals(new Integer(5), bw.getPropertyValue("mapOfLists[1][0]")); assertThat(bw.getPropertyValue("mapOfLists[1][0]")).isEqualTo(new Integer(5));
assertEquals(new Integer(5), gb.getMapOfLists().get(new Integer(1)).get(0)); assertThat(gb.getMapOfLists().get(new Integer(1)).get(0)).isEqualTo(new Integer(5));
} }
@Test @Test
@ -323,7 +325,8 @@ public class BeanWrapperGenericsTests {
bw.setPropertyValue("mapOfInteger", map); bw.setPropertyValue("mapOfInteger", map);
Object obj = gb.getMapOfInteger().get("testKey"); Object obj = gb.getMapOfInteger().get("testKey");
assertTrue(obj instanceof Integer); boolean condition = obj instanceof Integer;
assertThat(condition).isTrue();
} }
@Test @Test
@ -337,8 +340,9 @@ public class BeanWrapperGenericsTests {
bw.setPropertyValue("mapOfListOfInteger", map); bw.setPropertyValue("mapOfListOfInteger", map);
Object obj = gb.getMapOfListOfInteger().get("testKey").get(0); Object obj = gb.getMapOfListOfInteger().get("testKey").get(0);
assertTrue(obj instanceof Integer); boolean condition = obj instanceof Integer;
assertEquals(1, ((Integer) obj).intValue()); assertThat(condition).isTrue();
assertThat(((Integer) obj).intValue()).isEqualTo(1);
} }
@Test @Test
@ -353,8 +357,9 @@ public class BeanWrapperGenericsTests {
bw.setPropertyValue("listOfMapOfInteger", list); bw.setPropertyValue("listOfMapOfInteger", list);
Object obj = gb.getListOfMapOfInteger().get(0).get("testKey"); Object obj = gb.getListOfMapOfInteger().get(0).get("testKey");
assertTrue(obj instanceof Integer); boolean condition = obj instanceof Integer;
assertEquals(5, ((Integer) obj).intValue()); assertThat(condition).isTrue();
assertThat(((Integer) obj).intValue()).isEqualTo(5);
} }
@Test @Test
@ -368,8 +373,9 @@ public class BeanWrapperGenericsTests {
bw.setPropertyValue("mapOfListOfListOfInteger", map); bw.setPropertyValue("mapOfListOfListOfInteger", map);
Object obj = gb.getMapOfListOfListOfInteger().get("testKey").get(0).get(0); Object obj = gb.getMapOfListOfListOfInteger().get("testKey").get(0).get(0);
assertTrue(obj instanceof Integer); boolean condition = obj instanceof Integer;
assertEquals(1, ((Integer) obj).intValue()); assertThat(condition).isTrue();
assertThat(((Integer) obj).intValue()).isEqualTo(1);
} }
@Test @Test
@ -385,8 +391,8 @@ public class BeanWrapperGenericsTests {
BeanWrapper bw = new BeanWrapperImpl(holder); BeanWrapper bw = new BeanWrapperImpl(holder);
bw.setPropertyValue("genericMap", inputMap); bw.setPropertyValue("genericMap", inputMap);
assertEquals(new Integer(1), holder.getGenericMap().keySet().iterator().next().get(0)); assertThat(holder.getGenericMap().keySet().iterator().next().get(0)).isEqualTo(new Integer(1));
assertEquals(new Long(10), holder.getGenericMap().values().iterator().next().get(0)); assertThat(holder.getGenericMap().values().iterator().next().get(0)).isEqualTo(new Long(10));
} }
@Test @Test
@ -402,8 +408,8 @@ public class BeanWrapperGenericsTests {
BeanWrapper bw = new BeanWrapperImpl(holder); BeanWrapper bw = new BeanWrapperImpl(holder);
bw.setPropertyValue("genericMap", inputMap); bw.setPropertyValue("genericMap", inputMap);
assertEquals(new Integer(1), holder.getGenericMap().keySet().iterator().next().get(0)); assertThat(holder.getGenericMap().keySet().iterator().next().get(0)).isEqualTo(new Integer(1));
assertEquals(new Long(10), holder.getGenericMap().values().iterator().next().get(0)); assertThat(holder.getGenericMap().values().iterator().next().get(0)).isEqualTo(new Long(10));
} }
@Test @Test
@ -415,8 +421,8 @@ public class BeanWrapperGenericsTests {
BeanWrapper bw = new BeanWrapperImpl(holder); BeanWrapper bw = new BeanWrapperImpl(holder);
bw.setPropertyValue("genericIndexedMap[1]", inputValue); bw.setPropertyValue("genericIndexedMap[1]", inputValue);
assertEquals(new Integer(1), holder.getGenericIndexedMap().keySet().iterator().next()); assertThat(holder.getGenericIndexedMap().keySet().iterator().next()).isEqualTo(new Integer(1));
assertEquals(new Long(10), holder.getGenericIndexedMap().values().iterator().next().get(0)); assertThat(holder.getGenericIndexedMap().values().iterator().next().get(0)).isEqualTo(new Long(10));
} }
@Test @Test
@ -428,8 +434,8 @@ public class BeanWrapperGenericsTests {
BeanWrapper bw = new BeanWrapperImpl(holder); BeanWrapper bw = new BeanWrapperImpl(holder);
bw.setPropertyValue("genericIndexedMap[1]", inputValue); bw.setPropertyValue("genericIndexedMap[1]", inputValue);
assertEquals(new Integer(1), holder.getGenericIndexedMap().keySet().iterator().next()); assertThat(holder.getGenericIndexedMap().keySet().iterator().next()).isEqualTo(new Integer(1));
assertEquals(new Long(10), holder.getGenericIndexedMap().values().iterator().next().get(0)); assertThat(holder.getGenericIndexedMap().values().iterator().next().get(0)).isEqualTo(new Long(10));
} }
@Test @Test
@ -441,8 +447,8 @@ public class BeanWrapperGenericsTests {
BeanWrapper bw = new BeanWrapperImpl(holder); BeanWrapper bw = new BeanWrapperImpl(holder);
bw.setPropertyValue("derivedIndexedMap[1]", inputValue); bw.setPropertyValue("derivedIndexedMap[1]", inputValue);
assertEquals(new Integer(1), holder.getDerivedIndexedMap().keySet().iterator().next()); assertThat(holder.getDerivedIndexedMap().keySet().iterator().next()).isEqualTo(new Integer(1));
assertEquals(new Long(10), holder.getDerivedIndexedMap().values().iterator().next().get(0)); assertThat(holder.getDerivedIndexedMap().values().iterator().next().get(0)).isEqualTo(new Long(10));
} }
@Test @Test
@ -454,8 +460,8 @@ public class BeanWrapperGenericsTests {
BeanWrapper bw = new BeanWrapperImpl(holder); BeanWrapper bw = new BeanWrapperImpl(holder);
bw.setPropertyValue("derivedIndexedMap[1]", inputValue); bw.setPropertyValue("derivedIndexedMap[1]", inputValue);
assertEquals(new Integer(1), holder.getDerivedIndexedMap().keySet().iterator().next()); assertThat(holder.getDerivedIndexedMap().keySet().iterator().next()).isEqualTo(new Integer(1));
assertEquals(new Long(10), holder.getDerivedIndexedMap().values().iterator().next().get(0)); assertThat(holder.getDerivedIndexedMap().values().iterator().next().get(0)).isEqualTo(new Long(10));
} }
@Test @Test
@ -464,9 +470,9 @@ public class BeanWrapperGenericsTests {
BeanWrapper bw = new BeanWrapperImpl(gb); BeanWrapper bw = new BeanWrapperImpl(gb);
bw.setPropertyValue("genericProperty", "10"); bw.setPropertyValue("genericProperty", "10");
bw.setPropertyValue("genericListProperty", new String[] {"20", "30"}); bw.setPropertyValue("genericListProperty", new String[] {"20", "30"});
assertEquals(new Integer(10), gb.getGenericProperty()); assertThat(gb.getGenericProperty()).isEqualTo(new Integer(10));
assertEquals(new Integer(20), gb.getGenericListProperty().get(0)); assertThat(gb.getGenericListProperty().get(0)).isEqualTo(new Integer(20));
assertEquals(new Integer(30), gb.getGenericListProperty().get(1)); assertThat(gb.getGenericListProperty().get(1)).isEqualTo(new Integer(30));
} }
@Test @Test
@ -475,9 +481,9 @@ public class BeanWrapperGenericsTests {
BeanWrapper bw = new BeanWrapperImpl(gb); BeanWrapper bw = new BeanWrapperImpl(gb);
bw.setPropertyValue("genericProperty", "10"); bw.setPropertyValue("genericProperty", "10");
bw.setPropertyValue("genericListProperty", new String[] {"20", "30"}); bw.setPropertyValue("genericListProperty", new String[] {"20", "30"});
assertEquals(new Integer(10), gb.getGenericProperty().iterator().next()); assertThat(gb.getGenericProperty().iterator().next()).isEqualTo(new Integer(10));
assertEquals(new Integer(20), gb.getGenericListProperty().get(0).iterator().next()); assertThat(gb.getGenericListProperty().get(0).iterator().next()).isEqualTo(new Integer(20));
assertEquals(new Integer(30), gb.getGenericListProperty().get(1).iterator().next()); assertThat(gb.getGenericListProperty().get(1).iterator().next()).isEqualTo(new Integer(30));
} }
@Test @Test
@ -485,7 +491,7 @@ public class BeanWrapperGenericsTests {
Bar bar = new Bar(); Bar bar = new Bar();
BeanWrapper bw = new BeanWrapperImpl(bar); BeanWrapper bw = new BeanWrapperImpl(bar);
bw.setPropertyValue("version", "10"); bw.setPropertyValue("version", "10");
assertEquals(new Double(10.0), bar.getVersion()); assertThat(bar.getVersion()).isEqualTo(new Double(10.0));
} }
@Test @Test
@ -493,7 +499,7 @@ public class BeanWrapperGenericsTests {
Promotion bean = new Promotion(); Promotion bean = new Promotion();
BeanWrapper bw = new BeanWrapperImpl(bean); BeanWrapper bw = new BeanWrapperImpl(bean);
bw.setPropertyValue("id", "10"); bw.setPropertyValue("id", "10");
assertEquals(new Long(10), bean.getId()); assertThat(bean.getId()).isEqualTo(new Long(10));
} }
@Test @Test
@ -514,10 +520,10 @@ public class BeanWrapperGenericsTests {
Holder<Map<String, Object>> context = new Holder<>(data); Holder<Map<String, Object>> context = new Holder<>(data);
BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(context); BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(context);
assertEquals("y", bw.getPropertyValue("data['x']")); assertThat(bw.getPropertyValue("data['x']")).isEqualTo("y");
bw.setPropertyValue("data['message']", "it works!"); bw.setPropertyValue("data['message']", "it works!");
assertEquals("it works!", data.get("message")); assertThat(data.get("message")).isEqualTo("it works!");
} }

View File

@ -26,10 +26,6 @@ import org.springframework.tests.sample.beans.TestBean;
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.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
/** /**
* Specific {@link BeanWrapperImpl} tests. * Specific {@link BeanWrapperImpl} tests.
@ -54,8 +50,8 @@ public class BeanWrapperTests extends AbstractPropertyAccessorTests {
GetterBean target = new GetterBean(); GetterBean target = new GetterBean();
BeanWrapper accessor = createAccessor(target); BeanWrapper accessor = createAccessor(target);
accessor.setPropertyValue("name", "tom"); accessor.setPropertyValue("name", "tom");
assertEquals("tom", target.getAliasedName()); assertThat(target.getAliasedName()).isEqualTo("tom");
assertEquals("tom", accessor.getPropertyValue("aliasedName")); assertThat(accessor.getPropertyValue("aliasedName")).isEqualTo("tom");
} }
@Test @Test
@ -64,8 +60,8 @@ public class BeanWrapperTests extends AbstractPropertyAccessorTests {
BeanWrapper accessor = createAccessor(target); BeanWrapper accessor = createAccessor(target);
accessor.setExtractOldValueForEditor(true); // This will call the getter accessor.setExtractOldValueForEditor(true); // This will call the getter
accessor.setPropertyValue("name", "tom"); accessor.setPropertyValue("name", "tom");
assertEquals("tom", target.getAliasedName()); assertThat(target.getAliasedName()).isEqualTo("tom");
assertEquals("tom", accessor.getPropertyValue("aliasedName")); assertThat(accessor.getPropertyValue("aliasedName")).isEqualTo("tom");
} }
@Test @Test
@ -73,8 +69,8 @@ public class BeanWrapperTests extends AbstractPropertyAccessorTests {
GetterBean target = new GetterBean(); GetterBean target = new GetterBean();
BeanWrapper accessor = createAccessor(target); BeanWrapper accessor = createAccessor(target);
accessor.setPropertyValue("aliasedName", "tom"); accessor.setPropertyValue("aliasedName", "tom");
assertEquals("tom", target.getAliasedName()); assertThat(target.getAliasedName()).isEqualTo("tom");
assertEquals("tom", accessor.getPropertyValue("aliasedName")); assertThat(accessor.getPropertyValue("aliasedName")).isEqualTo("tom");
} }
@Test @Test
@ -95,8 +91,8 @@ public class BeanWrapperTests extends AbstractPropertyAccessorTests {
.getNewValue()).isEqualTo(invalidTouchy); .getNewValue()).isEqualTo(invalidTouchy);
}); });
// Test validly set property matches // Test validly set property matches
assertTrue("Valid set property must stick", target.getName().equals(newName)); assertThat(target.getName().equals(newName)).as("Valid set property must stick").isTrue();
assertTrue("Invalid set property must retain old value", target.getAge() == 0); assertThat(target.getAge() == 0).as("Invalid set property must retain old value").isTrue();
} }
@Test @Test
@ -124,8 +120,8 @@ public class BeanWrapperTests extends AbstractPropertyAccessorTests {
bw.setPropertyValue("names", "Alef"); bw.setPropertyValue("names", "Alef");
} }
catch (NotWritablePropertyException ex) { catch (NotWritablePropertyException ex) {
assertNotNull("Possible matches not determined", ex.getPossibleMatches()); assertThat(ex.getPossibleMatches()).as("Possible matches not determined").isNotNull();
assertEquals("Invalid amount of alternatives", 1, ex.getPossibleMatches().length); assertThat(ex.getPossibleMatches().length).as("Invalid amount of alternatives").isEqualTo(1);
} }
} }
@ -137,8 +133,8 @@ public class BeanWrapperTests extends AbstractPropertyAccessorTests {
bw.setPropertyValue("mystring", "Arjen"); bw.setPropertyValue("mystring", "Arjen");
} }
catch (NotWritablePropertyException ex) { catch (NotWritablePropertyException ex) {
assertNotNull("Possible matches not determined", ex.getPossibleMatches()); assertThat(ex.getPossibleMatches()).as("Possible matches not determined").isNotNull();
assertEquals("Invalid amount of alternatives", 3, ex.getPossibleMatches().length); assertThat(ex.getPossibleMatches().length).as("Invalid amount of alternatives").isEqualTo(3);
} }
} }
@ -147,9 +143,9 @@ public class BeanWrapperTests extends AbstractPropertyAccessorTests {
PropertyTypeMismatch target = new PropertyTypeMismatch(); PropertyTypeMismatch target = new PropertyTypeMismatch();
BeanWrapper accessor = createAccessor(target); BeanWrapper accessor = createAccessor(target);
accessor.setPropertyValue("object", "a String"); accessor.setPropertyValue("object", "a String");
assertEquals("a String", target.value); assertThat(target.value).isEqualTo("a String");
assertTrue(target.getObject() == 8); assertThat(target.getObject() == 8).isTrue();
assertEquals(8, accessor.getPropertyValue("object")); assertThat(accessor.getPropertyValue("object")).isEqualTo(8);
} }
@Test @Test
@ -159,12 +155,12 @@ public class BeanWrapperTests extends AbstractPropertyAccessorTests {
BeanWrapper accessor = createAccessor(target); BeanWrapper accessor = createAccessor(target);
accessor.setPropertyValue("name", "a"); accessor.setPropertyValue("name", "a");
accessor.setPropertyValue("spouse.name", "b"); accessor.setPropertyValue("spouse.name", "b");
assertEquals("a", target.getName()); assertThat(target.getName()).isEqualTo("a");
assertEquals("b", target.getSpouse().getName()); assertThat(target.getSpouse().getName()).isEqualTo("b");
assertEquals("a", accessor.getPropertyValue("name")); assertThat(accessor.getPropertyValue("name")).isEqualTo("a");
assertEquals("b", accessor.getPropertyValue("spouse.name")); assertThat(accessor.getPropertyValue("spouse.name")).isEqualTo("b");
assertEquals(String.class, accessor.getPropertyDescriptor("name").getPropertyType()); assertThat(accessor.getPropertyDescriptor("name").getPropertyType()).isEqualTo(String.class);
assertEquals(String.class, accessor.getPropertyDescriptor("spouse.name").getPropertyType()); assertThat(accessor.getPropertyDescriptor("spouse.name").getPropertyType()).isEqualTo(String.class);
} }
@Test @Test
@ -175,20 +171,20 @@ public class BeanWrapperTests extends AbstractPropertyAccessorTests {
BeanWrapper accessor = createAccessor(target); BeanWrapper accessor = createAccessor(target);
accessor.setPropertyValue("object", tb); accessor.setPropertyValue("object", tb);
assertSame(tb, target.value); assertThat(target.value).isSameAs(tb);
assertSame(tb, target.getObject().get()); assertThat(target.getObject().get()).isSameAs(tb);
assertSame(tb, ((Optional<String>) accessor.getPropertyValue("object")).get()); assertThat(((Optional<TestBean>) accessor.getPropertyValue("object")).get()).isSameAs(tb);
assertEquals("x", target.value.getName()); assertThat(target.value.getName()).isEqualTo("x");
assertEquals("x", target.getObject().get().getName()); assertThat(target.getObject().get().getName()).isEqualTo("x");
assertEquals("x", accessor.getPropertyValue("object.name")); assertThat(accessor.getPropertyValue("object.name")).isEqualTo("x");
accessor.setPropertyValue("object.name", "y"); accessor.setPropertyValue("object.name", "y");
assertSame(tb, target.value); assertThat(target.value).isSameAs(tb);
assertSame(tb, target.getObject().get()); assertThat(target.getObject().get()).isSameAs(tb);
assertSame(tb, ((Optional<String>) accessor.getPropertyValue("object")).get()); assertThat(((Optional<TestBean>) accessor.getPropertyValue("object")).get()).isSameAs(tb);
assertEquals("y", target.value.getName()); assertThat(target.value.getName()).isEqualTo("y");
assertEquals("y", target.getObject().get().getName()); assertThat(target.getObject().get().getName()).isEqualTo("y");
assertEquals("y", accessor.getPropertyValue("object.name")); assertThat(accessor.getPropertyValue("object.name")).isEqualTo("y");
} }
@Test @Test
@ -198,9 +194,9 @@ public class BeanWrapperTests extends AbstractPropertyAccessorTests {
accessor.setAutoGrowNestedPaths(true); accessor.setAutoGrowNestedPaths(true);
accessor.setPropertyValue("object.name", "x"); accessor.setPropertyValue("object.name", "x");
assertEquals("x", target.value.getName()); assertThat(target.value.getName()).isEqualTo("x");
assertEquals("x", target.getObject().get().getName()); assertThat(target.getObject().get().getName()).isEqualTo("x");
assertEquals("x", accessor.getPropertyValue("object.name")); assertThat(accessor.getPropertyValue("object.name")).isEqualTo("x");
} }
@Test @Test

View File

@ -26,8 +26,6 @@ import org.springframework.core.OverridingClassLoader;
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.assertThat;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
/** /**
* @author Juergen Hoeller * @author Juergen Hoeller
@ -39,30 +37,30 @@ public class CachedIntrospectionResultsTests {
@Test @Test
public void acceptAndClearClassLoader() throws Exception { public void acceptAndClearClassLoader() throws Exception {
BeanWrapper bw = new BeanWrapperImpl(TestBean.class); BeanWrapper bw = new BeanWrapperImpl(TestBean.class);
assertTrue(bw.isWritableProperty("name")); assertThat(bw.isWritableProperty("name")).isTrue();
assertTrue(bw.isWritableProperty("age")); assertThat(bw.isWritableProperty("age")).isTrue();
assertTrue(CachedIntrospectionResults.strongClassCache.containsKey(TestBean.class)); assertThat(CachedIntrospectionResults.strongClassCache.containsKey(TestBean.class)).isTrue();
ClassLoader child = new OverridingClassLoader(getClass().getClassLoader()); ClassLoader child = new OverridingClassLoader(getClass().getClassLoader());
Class<?> tbClass = child.loadClass("org.springframework.tests.sample.beans.TestBean"); Class<?> tbClass = child.loadClass("org.springframework.tests.sample.beans.TestBean");
assertFalse(CachedIntrospectionResults.strongClassCache.containsKey(tbClass)); assertThat(CachedIntrospectionResults.strongClassCache.containsKey(tbClass)).isFalse();
CachedIntrospectionResults.acceptClassLoader(child); CachedIntrospectionResults.acceptClassLoader(child);
bw = new BeanWrapperImpl(tbClass); bw = new BeanWrapperImpl(tbClass);
assertTrue(bw.isWritableProperty("name")); assertThat(bw.isWritableProperty("name")).isTrue();
assertTrue(bw.isWritableProperty("age")); assertThat(bw.isWritableProperty("age")).isTrue();
assertTrue(CachedIntrospectionResults.strongClassCache.containsKey(tbClass)); assertThat(CachedIntrospectionResults.strongClassCache.containsKey(tbClass)).isTrue();
CachedIntrospectionResults.clearClassLoader(child); CachedIntrospectionResults.clearClassLoader(child);
assertFalse(CachedIntrospectionResults.strongClassCache.containsKey(tbClass)); assertThat(CachedIntrospectionResults.strongClassCache.containsKey(tbClass)).isFalse();
assertTrue(CachedIntrospectionResults.strongClassCache.containsKey(TestBean.class)); assertThat(CachedIntrospectionResults.strongClassCache.containsKey(TestBean.class)).isTrue();
} }
@Test @Test
public void clearClassLoaderForSystemClassLoader() throws Exception { public void clearClassLoaderForSystemClassLoader() throws Exception {
BeanUtils.getPropertyDescriptors(ArrayList.class); BeanUtils.getPropertyDescriptors(ArrayList.class);
assertTrue(CachedIntrospectionResults.strongClassCache.containsKey(ArrayList.class)); assertThat(CachedIntrospectionResults.strongClassCache.containsKey(ArrayList.class)).isTrue();
CachedIntrospectionResults.clearClassLoader(ArrayList.class.getClassLoader()); CachedIntrospectionResults.clearClassLoader(ArrayList.class.getClassLoader());
assertFalse(CachedIntrospectionResults.strongClassCache.containsKey(ArrayList.class)); assertThat(CachedIntrospectionResults.strongClassCache.containsKey(ArrayList.class)).isFalse();
} }
@Test @Test

View File

@ -28,8 +28,7 @@ import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import org.junit.Test; import org.junit.Test;
import static org.junit.Assert.assertEquals; import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertTrue;
/** /**
* @author Guillaume Poirier * @author Guillaume Poirier
@ -83,7 +82,7 @@ public class ConcurrentBeanWrapperTests {
Properties p = (Properties) System.getProperties().clone(); Properties p = (Properties) System.getProperties().clone();
assertTrue("The System properties must not be empty", p.size() != 0); assertThat(p.size() != 0).as("The System properties must not be empty").isTrue();
for (Iterator<?> i = p.entrySet().iterator(); i.hasNext();) { for (Iterator<?> i = p.entrySet().iterator(); i.hasNext();) {
i.next(); i.next();
@ -104,7 +103,7 @@ public class ConcurrentBeanWrapperTests {
BeanWrapperImpl wrapper = new BeanWrapperImpl(bean); BeanWrapperImpl wrapper = new BeanWrapperImpl(bean);
wrapper.setPropertyValue("properties", value); wrapper.setPropertyValue("properties", value);
assertEquals(p, bean.getProperties()); assertThat(bean.getProperties()).isEqualTo(p);
} }

View File

@ -20,7 +20,7 @@ import org.junit.Test;
import org.springframework.tests.sample.beans.TestBean; import org.springframework.tests.sample.beans.TestBean;
import static org.junit.Assert.assertEquals; import static org.assertj.core.api.Assertions.assertThat;
/** /**
* Specific {@link DirectFieldAccessor} tests. * Specific {@link DirectFieldAccessor} tests.
@ -48,8 +48,8 @@ public class DirectFieldAccessorTests extends AbstractPropertyAccessorTests {
}; };
DirectFieldAccessor dfa = createAccessor(target); DirectFieldAccessor dfa = createAccessor(target);
assertEquals(StringBuilder.class, dfa.getPropertyType("name")); assertThat(dfa.getPropertyType("name")).isEqualTo(StringBuilder.class);
assertEquals(sb, dfa.getPropertyValue("name")); assertThat(dfa.getPropertyValue("name")).isEqualTo(sb);
} }
} }

View File

@ -28,7 +28,6 @@ import org.junit.Test;
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.assertThat;
import static org.junit.Assert.assertEquals;
/** /**
* @author Chris Beams * @author Chris Beams
@ -323,7 +322,7 @@ public class ExtendedBeanInfoTests {
assertThat(hasReadMethodForProperty(bi, "foo")).isTrue(); assertThat(hasReadMethodForProperty(bi, "foo")).isTrue();
assertThat(hasReadMethodForProperty(ebi, "foo")).isTrue(); assertThat(hasReadMethodForProperty(ebi, "foo")).isTrue();
assertEquals(hasWriteMethodForProperty(bi, "foo"), hasWriteMethodForProperty(ebi, "foo")); assertThat(hasWriteMethodForProperty(ebi, "foo")).isEqualTo(hasWriteMethodForProperty(bi, "foo"));
} }
@Test @Test
@ -338,7 +337,7 @@ public class ExtendedBeanInfoTests {
assertThat(hasIndexedReadMethodForProperty(bi, "foos")).isTrue(); assertThat(hasIndexedReadMethodForProperty(bi, "foos")).isTrue();
assertThat(hasIndexedReadMethodForProperty(ebi, "foos")).isTrue(); assertThat(hasIndexedReadMethodForProperty(ebi, "foos")).isTrue();
assertEquals(hasIndexedWriteMethodForProperty(bi, "foos"), hasIndexedWriteMethodForProperty(ebi, "foos")); assertThat(hasIndexedWriteMethodForProperty(ebi, "foos")).isEqualTo(hasIndexedWriteMethodForProperty(bi, "foos"));
} }
/** /**
@ -849,10 +848,10 @@ public class ExtendedBeanInfoTests {
// ExtendedBeanInfo needs to behave exactly like BeanInfo... // ExtendedBeanInfo needs to behave exactly like BeanInfo...
BeanInfo ebi = new ExtendedBeanInfo(bi); BeanInfo ebi = new ExtendedBeanInfo(bi);
assertEquals(hasReadMethod, hasReadMethodForProperty(ebi, "address")); assertThat(hasReadMethodForProperty(ebi, "address")).isEqualTo(hasReadMethod);
assertEquals(hasWriteMethod, hasWriteMethodForProperty(ebi, "address")); assertThat(hasWriteMethodForProperty(ebi, "address")).isEqualTo(hasWriteMethod);
assertEquals(hasIndexedReadMethod, hasIndexedReadMethodForProperty(ebi, "address")); assertThat(hasIndexedReadMethodForProperty(ebi, "address")).isEqualTo(hasIndexedReadMethod);
assertEquals(hasIndexedWriteMethod, hasIndexedWriteMethodForProperty(ebi, "address")); assertThat(hasIndexedWriteMethodForProperty(ebi, "address")).isEqualTo(hasIndexedWriteMethod);
} }
@Test @Test

View File

@ -22,9 +22,6 @@ import org.junit.Test;
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.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
/** /**
* Tests for {@link MutablePropertyValues}. * Tests for {@link MutablePropertyValues}.
@ -47,7 +44,7 @@ public class MutablePropertyValuesTests extends AbstractPropertyValuesTests {
doTestTony(deepCopy); doTestTony(deepCopy);
deepCopy.setPropertyValueAt(new PropertyValue("name", "Gordon"), 0); deepCopy.setPropertyValueAt(new PropertyValue("name", "Gordon"), 0);
doTestTony(pvs); doTestTony(pvs);
assertEquals("Gordon", deepCopy.getPropertyValue("name").getValue()); assertThat(deepCopy.getPropertyValue("name").getValue()).isEqualTo("Gordon");
} }
@Test @Test
@ -59,10 +56,10 @@ public class MutablePropertyValuesTests extends AbstractPropertyValuesTests {
doTestTony(pvs); doTestTony(pvs);
PropertyValue addedPv = new PropertyValue("rod", "Rod"); PropertyValue addedPv = new PropertyValue("rod", "Rod");
pvs.addPropertyValue(addedPv); pvs.addPropertyValue(addedPv);
assertTrue(pvs.getPropertyValue("rod").equals(addedPv)); assertThat(pvs.getPropertyValue("rod").equals(addedPv)).isTrue();
PropertyValue changedPv = new PropertyValue("forname", "Greg"); PropertyValue changedPv = new PropertyValue("forname", "Greg");
pvs.addPropertyValue(changedPv); pvs.addPropertyValue(changedPv);
assertTrue(pvs.getPropertyValue("forname").equals(changedPv)); assertThat(pvs.getPropertyValue("forname").equals(changedPv)).isTrue();
} }
@Test @Test
@ -73,7 +70,7 @@ public class MutablePropertyValuesTests extends AbstractPropertyValuesTests {
pvs.addPropertyValue(new PropertyValue("age", "50")); pvs.addPropertyValue(new PropertyValue("age", "50"));
MutablePropertyValues pvs2 = pvs; MutablePropertyValues pvs2 = pvs;
PropertyValues changes = pvs2.changesSince(pvs); PropertyValues changes = pvs2.changesSince(pvs);
assertTrue("changes are empty", changes.getPropertyValues().length == 0); assertThat(changes.getPropertyValues().length == 0).as("changes are empty").isTrue();
} }
@Test @Test
@ -85,29 +82,27 @@ public class MutablePropertyValuesTests extends AbstractPropertyValuesTests {
MutablePropertyValues pvs2 = new MutablePropertyValues(pvs); MutablePropertyValues pvs2 = new MutablePropertyValues(pvs);
PropertyValues changes = pvs2.changesSince(pvs); PropertyValues changes = pvs2.changesSince(pvs);
assertTrue("changes are empty, not of length " + changes.getPropertyValues().length, assertThat(changes.getPropertyValues().length == 0).as("changes are empty, not of length " + changes.getPropertyValues().length).isTrue();
changes.getPropertyValues().length == 0);
pvs2.addPropertyValue(new PropertyValue("forname", "Gordon")); pvs2.addPropertyValue(new PropertyValue("forname", "Gordon"));
changes = pvs2.changesSince(pvs); changes = pvs2.changesSince(pvs);
assertEquals("1 change", 1, changes.getPropertyValues().length); assertThat(changes.getPropertyValues().length).as("1 change").isEqualTo(1);
PropertyValue fn = changes.getPropertyValue("forname"); PropertyValue fn = changes.getPropertyValue("forname");
assertTrue("change is forname", fn != null); assertThat(fn != null).as("change is forname").isTrue();
assertTrue("new value is gordon", fn.getValue().equals("Gordon")); assertThat(fn.getValue().equals("Gordon")).as("new value is gordon").isTrue();
MutablePropertyValues pvs3 = new MutablePropertyValues(pvs); MutablePropertyValues pvs3 = new MutablePropertyValues(pvs);
changes = pvs3.changesSince(pvs); changes = pvs3.changesSince(pvs);
assertTrue("changes are empty, not of length " + changes.getPropertyValues().length, assertThat(changes.getPropertyValues().length == 0).as("changes are empty, not of length " + changes.getPropertyValues().length).isTrue();
changes.getPropertyValues().length == 0);
// add new // add new
pvs3.addPropertyValue(new PropertyValue("foo", "bar")); pvs3.addPropertyValue(new PropertyValue("foo", "bar"));
pvs3.addPropertyValue(new PropertyValue("fi", "fum")); pvs3.addPropertyValue(new PropertyValue("fi", "fum"));
changes = pvs3.changesSince(pvs); changes = pvs3.changesSince(pvs);
assertTrue("2 change", changes.getPropertyValues().length == 2); assertThat(changes.getPropertyValues().length == 2).as("2 change").isTrue();
fn = changes.getPropertyValue("foo"); fn = changes.getPropertyValue("foo");
assertTrue("change in foo", fn != null); assertThat(fn != null).as("change in foo").isTrue();
assertTrue("new value is bar", fn.getValue().equals("bar")); assertThat(fn.getValue().equals("bar")).as("new value is bar").isTrue();
} }
@Test @Test
@ -116,19 +111,19 @@ public class MutablePropertyValuesTests extends AbstractPropertyValuesTests {
pvs.add("foo", "bar"); pvs.add("foo", "bar");
Iterator<PropertyValue> it = pvs.iterator(); Iterator<PropertyValue> it = pvs.iterator();
assertTrue(it.hasNext()); assertThat(it.hasNext()).isTrue();
PropertyValue pv = it.next(); PropertyValue pv = it.next();
assertEquals("foo", pv.getName()); assertThat(pv.getName()).isEqualTo("foo");
assertEquals("bar", pv.getValue()); assertThat(pv.getValue()).isEqualTo("bar");
assertThatExceptionOfType(UnsupportedOperationException.class).isThrownBy(it::remove); assertThatExceptionOfType(UnsupportedOperationException.class).isThrownBy(it::remove);
assertFalse(it.hasNext()); assertThat(it.hasNext()).isFalse();
} }
@Test @Test
public void iteratorIsEmptyForEmptyValues() { public void iteratorIsEmptyForEmptyValues() {
MutablePropertyValues pvs = new MutablePropertyValues(); MutablePropertyValues pvs = new MutablePropertyValues();
Iterator<PropertyValue> it = pvs.iterator(); Iterator<PropertyValue> it = pvs.iterator();
assertFalse(it.hasNext()); assertThat(it.hasNext()).isFalse();
} }
@Test @Test

View File

@ -20,8 +20,7 @@ import java.util.Arrays;
import org.junit.Test; import org.junit.Test;
import static org.junit.Assert.assertEquals; import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertTrue;
/** /**
* @author Juergen Hoeller * @author Juergen Hoeller
@ -31,15 +30,15 @@ public class PropertyAccessorUtilsTests {
@Test @Test
public void testCanonicalPropertyName() { public void testCanonicalPropertyName() {
assertEquals("map", PropertyAccessorUtils.canonicalPropertyName("map")); assertThat(PropertyAccessorUtils.canonicalPropertyName("map")).isEqualTo("map");
assertEquals("map[key1]", PropertyAccessorUtils.canonicalPropertyName("map[key1]")); assertThat(PropertyAccessorUtils.canonicalPropertyName("map[key1]")).isEqualTo("map[key1]");
assertEquals("map[key1]", PropertyAccessorUtils.canonicalPropertyName("map['key1']")); assertThat(PropertyAccessorUtils.canonicalPropertyName("map['key1']")).isEqualTo("map[key1]");
assertEquals("map[key1]", PropertyAccessorUtils.canonicalPropertyName("map[\"key1\"]")); assertThat(PropertyAccessorUtils.canonicalPropertyName("map[\"key1\"]")).isEqualTo("map[key1]");
assertEquals("map[key1][key2]", PropertyAccessorUtils.canonicalPropertyName("map[key1][key2]")); assertThat(PropertyAccessorUtils.canonicalPropertyName("map[key1][key2]")).isEqualTo("map[key1][key2]");
assertEquals("map[key1][key2]", PropertyAccessorUtils.canonicalPropertyName("map['key1'][\"key2\"]")); assertThat(PropertyAccessorUtils.canonicalPropertyName("map['key1'][\"key2\"]")).isEqualTo("map[key1][key2]");
assertEquals("map[key1].name", PropertyAccessorUtils.canonicalPropertyName("map[key1].name")); assertThat(PropertyAccessorUtils.canonicalPropertyName("map[key1].name")).isEqualTo("map[key1].name");
assertEquals("map[key1].name", PropertyAccessorUtils.canonicalPropertyName("map['key1'].name")); assertThat(PropertyAccessorUtils.canonicalPropertyName("map['key1'].name")).isEqualTo("map[key1].name");
assertEquals("map[key1].name", PropertyAccessorUtils.canonicalPropertyName("map[\"key1\"].name")); assertThat(PropertyAccessorUtils.canonicalPropertyName("map[\"key1\"].name")).isEqualTo("map[key1].name");
} }
@Test @Test
@ -51,7 +50,7 @@ public class PropertyAccessorUtilsTests {
new String[] {"map", "map[key1]", "map[key1]", "map[key1]", "map[key1][key2]", new String[] {"map", "map[key1]", "map[key1]", "map[key1]", "map[key1][key2]",
"map[key1][key2]", "map[key1].name", "map[key1].name", "map[key1].name"}; "map[key1][key2]", "map[key1].name", "map[key1].name", "map[key1].name"};
assertTrue(Arrays.equals(canonical, PropertyAccessorUtils.canonicalPropertyNames(original))); assertThat(Arrays.equals(canonical, PropertyAccessorUtils.canonicalPropertyNames(original))).isTrue();
} }
} }

View File

@ -36,8 +36,7 @@ import org.springframework.tests.sample.beans.TestBean;
import org.springframework.tests.sample.beans.factory.DummyFactory; import org.springframework.tests.sample.beans.factory.DummyFactory;
import org.springframework.util.ObjectUtils; import org.springframework.util.ObjectUtils;
import static org.junit.Assert.assertEquals; import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertTrue;
import static org.springframework.tests.TestResourceUtils.qualifiedResource; import static org.springframework.tests.TestResourceUtils.qualifiedResource;
/** /**
@ -83,7 +82,7 @@ public class BeanFactoryUtilsTests {
StaticListableBeanFactory lbf = new StaticListableBeanFactory(); StaticListableBeanFactory lbf = new StaticListableBeanFactory();
lbf.addBean("t1", new TestBean()); lbf.addBean("t1", new TestBean());
lbf.addBean("t2", new TestBean()); lbf.addBean("t2", new TestBean());
assertTrue(BeanFactoryUtils.countBeansIncludingAncestors(lbf) == 2); assertThat(BeanFactoryUtils.countBeansIncludingAncestors(lbf) == 2).isTrue();
} }
/** /**
@ -92,27 +91,26 @@ public class BeanFactoryUtilsTests {
@Test @Test
public void testHierarchicalCountBeansWithOverride() throws Exception { public void testHierarchicalCountBeansWithOverride() throws Exception {
// Leaf count // Leaf count
assertTrue(this.listableBeanFactory.getBeanDefinitionCount() == 1); assertThat(this.listableBeanFactory.getBeanDefinitionCount() == 1).isTrue();
// Count minus duplicate // Count minus duplicate
assertTrue("Should count 8 beans, not " + BeanFactoryUtils.countBeansIncludingAncestors(this.listableBeanFactory), assertThat(BeanFactoryUtils.countBeansIncludingAncestors(this.listableBeanFactory) == 8).as("Should count 8 beans, not " + BeanFactoryUtils.countBeansIncludingAncestors(this.listableBeanFactory)).isTrue();
BeanFactoryUtils.countBeansIncludingAncestors(this.listableBeanFactory) == 8);
} }
@Test @Test
public void testHierarchicalNamesWithNoMatch() throws Exception { public void testHierarchicalNamesWithNoMatch() throws Exception {
List<String> names = Arrays.asList( List<String> names = Arrays.asList(
BeanFactoryUtils.beanNamesForTypeIncludingAncestors(this.listableBeanFactory, NoOp.class)); BeanFactoryUtils.beanNamesForTypeIncludingAncestors(this.listableBeanFactory, NoOp.class));
assertEquals(0, names.size()); assertThat(names.size()).isEqualTo(0);
} }
@Test @Test
public void testHierarchicalNamesWithMatchOnlyInRoot() throws Exception { public void testHierarchicalNamesWithMatchOnlyInRoot() throws Exception {
List<String> names = Arrays.asList( List<String> names = Arrays.asList(
BeanFactoryUtils.beanNamesForTypeIncludingAncestors(this.listableBeanFactory, IndexedTestBean.class)); BeanFactoryUtils.beanNamesForTypeIncludingAncestors(this.listableBeanFactory, IndexedTestBean.class));
assertEquals(1, names.size()); assertThat(names.size()).isEqualTo(1);
assertTrue(names.contains("indexedBean")); assertThat(names.contains("indexedBean")).isTrue();
// Distinguish from default ListableBeanFactory behavior // Distinguish from default ListableBeanFactory behavior
assertTrue(listableBeanFactory.getBeanNamesForType(IndexedTestBean.class).length == 0); assertThat(listableBeanFactory.getBeanNamesForType(IndexedTestBean.class).length == 0).isTrue();
} }
@Test @Test
@ -120,11 +118,11 @@ public class BeanFactoryUtilsTests {
List<String> names = Arrays.asList( List<String> names = Arrays.asList(
BeanFactoryUtils.beanNamesForTypeIncludingAncestors(this.listableBeanFactory, ITestBean.class)); BeanFactoryUtils.beanNamesForTypeIncludingAncestors(this.listableBeanFactory, ITestBean.class));
// includes 2 TestBeans from FactoryBeans (DummyFactory definitions) // includes 2 TestBeans from FactoryBeans (DummyFactory definitions)
assertEquals(4, names.size()); assertThat(names.size()).isEqualTo(4);
assertTrue(names.contains("test")); assertThat(names.contains("test")).isTrue();
assertTrue(names.contains("test3")); assertThat(names.contains("test3")).isTrue();
assertTrue(names.contains("testFactory1")); assertThat(names.contains("testFactory1")).isTrue();
assertTrue(names.contains("testFactory2")); assertThat(names.contains("testFactory2")).isTrue();
} }
@Test @Test
@ -132,7 +130,7 @@ public class BeanFactoryUtilsTests {
StaticListableBeanFactory lbf = new StaticListableBeanFactory(); StaticListableBeanFactory lbf = new StaticListableBeanFactory();
lbf.addBean("foo", new Object()); lbf.addBean("foo", new Object());
Map<String, ?> beans = BeanFactoryUtils.beansOfTypeIncludingAncestors(lbf, ITestBean.class, true, false); Map<String, ?> beans = BeanFactoryUtils.beansOfTypeIncludingAncestors(lbf, ITestBean.class, true, false);
assertTrue(beans.isEmpty()); assertThat(beans.isEmpty()).isTrue();
} }
@Test @Test
@ -149,21 +147,22 @@ public class BeanFactoryUtilsTests {
lbf.addBean("t4", t4); lbf.addBean("t4", t4);
Map<String, ?> beans = BeanFactoryUtils.beansOfTypeIncludingAncestors(lbf, ITestBean.class, true, true); Map<String, ?> beans = BeanFactoryUtils.beansOfTypeIncludingAncestors(lbf, ITestBean.class, true, true);
assertEquals(4, beans.size()); assertThat(beans.size()).isEqualTo(4);
assertEquals(t1, beans.get("t1")); assertThat(beans.get("t1")).isEqualTo(t1);
assertEquals(t2, beans.get("t2")); assertThat(beans.get("t2")).isEqualTo(t2);
assertEquals(t3.getObject(), beans.get("t3")); assertThat(beans.get("t3")).isEqualTo(t3.getObject());
assertTrue(beans.get("t4") instanceof TestBean); boolean condition = beans.get("t4") instanceof TestBean;
assertThat(condition).isTrue();
beans = BeanFactoryUtils.beansOfTypeIncludingAncestors(lbf, DummyFactory.class, true, true); beans = BeanFactoryUtils.beansOfTypeIncludingAncestors(lbf, DummyFactory.class, true, true);
assertEquals(2, beans.size()); assertThat(beans.size()).isEqualTo(2);
assertEquals(t3, beans.get("&t3")); assertThat(beans.get("&t3")).isEqualTo(t3);
assertEquals(t4, beans.get("&t4")); assertThat(beans.get("&t4")).isEqualTo(t4);
beans = BeanFactoryUtils.beansOfTypeIncludingAncestors(lbf, FactoryBean.class, true, true); beans = BeanFactoryUtils.beansOfTypeIncludingAncestors(lbf, FactoryBean.class, true, true);
assertEquals(2, beans.size()); assertThat(beans.size()).isEqualTo(2);
assertEquals(t3, beans.get("&t3")); assertThat(beans.get("&t3")).isEqualTo(t3);
assertEquals(t4, beans.get("&t4")); assertThat(beans.get("&t4")).isEqualTo(t4);
} }
@Test @Test
@ -183,50 +182,53 @@ public class BeanFactoryUtilsTests {
Map<String, ?> beans = Map<String, ?> beans =
BeanFactoryUtils.beansOfTypeIncludingAncestors(this.listableBeanFactory, ITestBean.class, true, false); BeanFactoryUtils.beansOfTypeIncludingAncestors(this.listableBeanFactory, ITestBean.class, true, false);
assertEquals(6, beans.size()); assertThat(beans.size()).isEqualTo(6);
assertEquals(test3, beans.get("test3")); assertThat(beans.get("test3")).isEqualTo(test3);
assertEquals(test, beans.get("test")); assertThat(beans.get("test")).isEqualTo(test);
assertEquals(t1, beans.get("t1")); assertThat(beans.get("t1")).isEqualTo(t1);
assertEquals(t2, beans.get("t2")); assertThat(beans.get("t2")).isEqualTo(t2);
assertEquals(t3.getObject(), beans.get("t3")); assertThat(beans.get("t3")).isEqualTo(t3.getObject());
assertTrue(beans.get("t4") instanceof TestBean); boolean condition2 = beans.get("t4") instanceof TestBean;
assertThat(condition2).isTrue();
// t3 and t4 are found here as of Spring 2.0, since they are pre-registered // t3 and t4 are found here as of Spring 2.0, since they are pre-registered
// singleton instances, while testFactory1 and testFactory are *not* found // singleton instances, while testFactory1 and testFactory are *not* found
// because they are FactoryBean definitions that haven't been initialized yet. // because they are FactoryBean definitions that haven't been initialized yet.
beans = BeanFactoryUtils.beansOfTypeIncludingAncestors(this.listableBeanFactory, ITestBean.class, false, true); beans = BeanFactoryUtils.beansOfTypeIncludingAncestors(this.listableBeanFactory, ITestBean.class, false, true);
Object testFactory1 = this.listableBeanFactory.getBean("testFactory1"); Object testFactory1 = this.listableBeanFactory.getBean("testFactory1");
assertEquals(5, beans.size()); assertThat(beans.size()).isEqualTo(5);
assertEquals(test, beans.get("test")); assertThat(beans.get("test")).isEqualTo(test);
assertEquals(testFactory1, beans.get("testFactory1")); assertThat(beans.get("testFactory1")).isEqualTo(testFactory1);
assertEquals(t1, beans.get("t1")); assertThat(beans.get("t1")).isEqualTo(t1);
assertEquals(t2, beans.get("t2")); assertThat(beans.get("t2")).isEqualTo(t2);
assertEquals(t3.getObject(), beans.get("t3")); assertThat(beans.get("t3")).isEqualTo(t3.getObject());
beans = BeanFactoryUtils.beansOfTypeIncludingAncestors(this.listableBeanFactory, ITestBean.class, true, true); beans = BeanFactoryUtils.beansOfTypeIncludingAncestors(this.listableBeanFactory, ITestBean.class, true, true);
assertEquals(8, beans.size()); assertThat(beans.size()).isEqualTo(8);
assertEquals(test3, beans.get("test3")); assertThat(beans.get("test3")).isEqualTo(test3);
assertEquals(test, beans.get("test")); assertThat(beans.get("test")).isEqualTo(test);
assertEquals(testFactory1, beans.get("testFactory1")); assertThat(beans.get("testFactory1")).isEqualTo(testFactory1);
assertTrue(beans.get("testFactory2") instanceof TestBean); boolean condition1 = beans.get("testFactory2") instanceof TestBean;
assertEquals(t1, beans.get("t1")); assertThat(condition1).isTrue();
assertEquals(t2, beans.get("t2")); assertThat(beans.get("t1")).isEqualTo(t1);
assertEquals(t3.getObject(), beans.get("t3")); assertThat(beans.get("t2")).isEqualTo(t2);
assertTrue(beans.get("t4") instanceof TestBean); assertThat(beans.get("t3")).isEqualTo(t3.getObject());
boolean condition = beans.get("t4") instanceof TestBean;
assertThat(condition).isTrue();
beans = BeanFactoryUtils.beansOfTypeIncludingAncestors(this.listableBeanFactory, DummyFactory.class, true, true); beans = BeanFactoryUtils.beansOfTypeIncludingAncestors(this.listableBeanFactory, DummyFactory.class, true, true);
assertEquals(4, beans.size()); assertThat(beans.size()).isEqualTo(4);
assertEquals(this.listableBeanFactory.getBean("&testFactory1"), beans.get("&testFactory1")); assertThat(beans.get("&testFactory1")).isEqualTo(this.listableBeanFactory.getBean("&testFactory1"));
assertEquals(this.listableBeanFactory.getBean("&testFactory2"), beans.get("&testFactory2")); assertThat(beans.get("&testFactory2")).isEqualTo(this.listableBeanFactory.getBean("&testFactory2"));
assertEquals(t3, beans.get("&t3")); assertThat(beans.get("&t3")).isEqualTo(t3);
assertEquals(t4, beans.get("&t4")); assertThat(beans.get("&t4")).isEqualTo(t4);
beans = BeanFactoryUtils.beansOfTypeIncludingAncestors(this.listableBeanFactory, FactoryBean.class, true, true); beans = BeanFactoryUtils.beansOfTypeIncludingAncestors(this.listableBeanFactory, FactoryBean.class, true, true);
assertEquals(4, beans.size()); assertThat(beans.size()).isEqualTo(4);
assertEquals(this.listableBeanFactory.getBean("&testFactory1"), beans.get("&testFactory1")); assertThat(beans.get("&testFactory1")).isEqualTo(this.listableBeanFactory.getBean("&testFactory1"));
assertEquals(this.listableBeanFactory.getBean("&testFactory2"), beans.get("&testFactory2")); assertThat(beans.get("&testFactory2")).isEqualTo(this.listableBeanFactory.getBean("&testFactory2"));
assertEquals(t3, beans.get("&t3")); assertThat(beans.get("&t3")).isEqualTo(t3);
assertEquals(t4, beans.get("&t4")); assertThat(beans.get("&t4")).isEqualTo(t4);
} }
@Test @Test
@ -236,53 +238,54 @@ public class BeanFactoryUtilsTests {
Map<String, ?> beans = Map<String, ?> beans =
BeanFactoryUtils.beansOfTypeIncludingAncestors(this.listableBeanFactory, ITestBean.class, true, false); BeanFactoryUtils.beansOfTypeIncludingAncestors(this.listableBeanFactory, ITestBean.class, true, false);
assertEquals(2, beans.size()); assertThat(beans.size()).isEqualTo(2);
assertEquals(test3, beans.get("test3")); assertThat(beans.get("test3")).isEqualTo(test3);
assertEquals(test, beans.get("test")); assertThat(beans.get("test")).isEqualTo(test);
beans = BeanFactoryUtils.beansOfTypeIncludingAncestors(this.listableBeanFactory, ITestBean.class, false, false); beans = BeanFactoryUtils.beansOfTypeIncludingAncestors(this.listableBeanFactory, ITestBean.class, false, false);
assertEquals(1, beans.size()); assertThat(beans.size()).isEqualTo(1);
assertEquals(test, beans.get("test")); assertThat(beans.get("test")).isEqualTo(test);
beans = BeanFactoryUtils.beansOfTypeIncludingAncestors(this.listableBeanFactory, ITestBean.class, false, true); beans = BeanFactoryUtils.beansOfTypeIncludingAncestors(this.listableBeanFactory, ITestBean.class, false, true);
Object testFactory1 = this.listableBeanFactory.getBean("testFactory1"); Object testFactory1 = this.listableBeanFactory.getBean("testFactory1");
assertEquals(2, beans.size()); assertThat(beans.size()).isEqualTo(2);
assertEquals(test, beans.get("test")); assertThat(beans.get("test")).isEqualTo(test);
assertEquals(testFactory1, beans.get("testFactory1")); assertThat(beans.get("testFactory1")).isEqualTo(testFactory1);
beans = BeanFactoryUtils.beansOfTypeIncludingAncestors(this.listableBeanFactory, ITestBean.class, true, true); beans = BeanFactoryUtils.beansOfTypeIncludingAncestors(this.listableBeanFactory, ITestBean.class, true, true);
assertEquals(4, beans.size()); assertThat(beans.size()).isEqualTo(4);
assertEquals(test3, beans.get("test3")); assertThat(beans.get("test3")).isEqualTo(test3);
assertEquals(test, beans.get("test")); assertThat(beans.get("test")).isEqualTo(test);
assertEquals(testFactory1, beans.get("testFactory1")); assertThat(beans.get("testFactory1")).isEqualTo(testFactory1);
assertTrue(beans.get("testFactory2") instanceof TestBean); boolean condition = beans.get("testFactory2") instanceof TestBean;
assertThat(condition).isTrue();
beans = BeanFactoryUtils.beansOfTypeIncludingAncestors(this.listableBeanFactory, DummyFactory.class, true, true); beans = BeanFactoryUtils.beansOfTypeIncludingAncestors(this.listableBeanFactory, DummyFactory.class, true, true);
assertEquals(2, beans.size()); assertThat(beans.size()).isEqualTo(2);
assertEquals(this.listableBeanFactory.getBean("&testFactory1"), beans.get("&testFactory1")); assertThat(beans.get("&testFactory1")).isEqualTo(this.listableBeanFactory.getBean("&testFactory1"));
assertEquals(this.listableBeanFactory.getBean("&testFactory2"), beans.get("&testFactory2")); assertThat(beans.get("&testFactory2")).isEqualTo(this.listableBeanFactory.getBean("&testFactory2"));
beans = BeanFactoryUtils.beansOfTypeIncludingAncestors(this.listableBeanFactory, FactoryBean.class, true, true); beans = BeanFactoryUtils.beansOfTypeIncludingAncestors(this.listableBeanFactory, FactoryBean.class, true, true);
assertEquals(2, beans.size()); assertThat(beans.size()).isEqualTo(2);
assertEquals(this.listableBeanFactory.getBean("&testFactory1"), beans.get("&testFactory1")); assertThat(beans.get("&testFactory1")).isEqualTo(this.listableBeanFactory.getBean("&testFactory1"));
assertEquals(this.listableBeanFactory.getBean("&testFactory2"), beans.get("&testFactory2")); assertThat(beans.get("&testFactory2")).isEqualTo(this.listableBeanFactory.getBean("&testFactory2"));
} }
@Test @Test
public void testHierarchicalNamesForAnnotationWithNoMatch() throws Exception { public void testHierarchicalNamesForAnnotationWithNoMatch() throws Exception {
List<String> names = Arrays.asList( List<String> names = Arrays.asList(
BeanFactoryUtils.beanNamesForAnnotationIncludingAncestors(this.listableBeanFactory, Override.class)); BeanFactoryUtils.beanNamesForAnnotationIncludingAncestors(this.listableBeanFactory, Override.class));
assertEquals(0, names.size()); assertThat(names.size()).isEqualTo(0);
} }
@Test @Test
public void testHierarchicalNamesForAnnotationWithMatchOnlyInRoot() throws Exception { public void testHierarchicalNamesForAnnotationWithMatchOnlyInRoot() throws Exception {
List<String> names = Arrays.asList( List<String> names = Arrays.asList(
BeanFactoryUtils.beanNamesForAnnotationIncludingAncestors(this.listableBeanFactory, TestAnnotation.class)); BeanFactoryUtils.beanNamesForAnnotationIncludingAncestors(this.listableBeanFactory, TestAnnotation.class));
assertEquals(1, names.size()); assertThat(names.size()).isEqualTo(1);
assertTrue(names.contains("annotatedBean")); assertThat(names.contains("annotatedBean")).isTrue();
// Distinguish from default ListableBeanFactory behavior // Distinguish from default ListableBeanFactory behavior
assertTrue(listableBeanFactory.getBeanNamesForAnnotation(TestAnnotation.class).length == 0); assertThat(listableBeanFactory.getBeanNamesForAnnotation(TestAnnotation.class).length == 0).isTrue();
} }
@Test @Test
@ -291,33 +294,33 @@ public class BeanFactoryUtilsTests {
this.listableBeanFactory.registerSingleton("anotherAnnotatedBean", annotatedBean); this.listableBeanFactory.registerSingleton("anotherAnnotatedBean", annotatedBean);
List<String> names = Arrays.asList( List<String> names = Arrays.asList(
BeanFactoryUtils.beanNamesForAnnotationIncludingAncestors(this.listableBeanFactory, TestAnnotation.class)); BeanFactoryUtils.beanNamesForAnnotationIncludingAncestors(this.listableBeanFactory, TestAnnotation.class));
assertEquals(2, names.size()); assertThat(names.size()).isEqualTo(2);
assertTrue(names.contains("annotatedBean")); assertThat(names.contains("annotatedBean")).isTrue();
assertTrue(names.contains("anotherAnnotatedBean")); assertThat(names.contains("anotherAnnotatedBean")).isTrue();
} }
@Test @Test
public void testADependencies() { public void testADependencies() {
String[] deps = this.dependentBeansFactory.getDependentBeans("a"); String[] deps = this.dependentBeansFactory.getDependentBeans("a");
assertTrue(ObjectUtils.isEmpty(deps)); assertThat(ObjectUtils.isEmpty(deps)).isTrue();
} }
@Test @Test
public void testBDependencies() { public void testBDependencies() {
String[] deps = this.dependentBeansFactory.getDependentBeans("b"); String[] deps = this.dependentBeansFactory.getDependentBeans("b");
assertTrue(Arrays.equals(new String[] { "c" }, deps)); assertThat(Arrays.equals(new String[] { "c" }, deps)).isTrue();
} }
@Test @Test
public void testCDependencies() { public void testCDependencies() {
String[] deps = this.dependentBeansFactory.getDependentBeans("c"); String[] deps = this.dependentBeansFactory.getDependentBeans("c");
assertTrue(Arrays.equals(new String[] { "int", "long" }, deps)); assertThat(Arrays.equals(new String[] { "int", "long" }, deps)).isTrue();
} }
@Test @Test
public void testIntDependencies() { public void testIntDependencies() {
String[] deps = this.dependentBeansFactory.getDependentBeans("int"); String[] deps = this.dependentBeansFactory.getDependentBeans("int");
assertTrue(Arrays.equals(new String[] { "buffer" }, deps)); assertThat(Arrays.equals(new String[] { "buffer" }, deps)).isTrue();
} }
} }

View File

@ -36,7 +36,7 @@ import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.tests.Assume; import org.springframework.tests.Assume;
import org.springframework.tests.TestGroup; import org.springframework.tests.TestGroup;
import static org.junit.Assert.assertEquals; import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.tests.TestResourceUtils.qualifiedResource; import static org.springframework.tests.TestResourceUtils.qualifiedResource;
/** /**
@ -126,8 +126,8 @@ public class ConcurrentBeanFactoryTests {
ConcurrentBean b1 = (ConcurrentBean) factory.getBean("bean1"); ConcurrentBean b1 = (ConcurrentBean) factory.getBean("bean1");
ConcurrentBean b2 = (ConcurrentBean) factory.getBean("bean2"); ConcurrentBean b2 = (ConcurrentBean) factory.getBean("bean2");
assertEquals(DATE_1, b1.getDate()); assertThat(b1.getDate()).isEqualTo(DATE_1);
assertEquals(DATE_2, b2.getDate()); assertThat(b2.getDate()).isEqualTo(DATE_2);
} }

View File

@ -26,7 +26,6 @@ import org.springframework.beans.factory.xml.XmlBeanDefinitionReader;
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.assertThat;
import static org.junit.Assert.assertNotNull;
/** /**
* Written with the intention of reproducing SPR-7318. * Written with the intention of reproducing SPR-7318.
@ -52,13 +51,13 @@ public class FactoryBeanLookupTests {
@Test @Test
public void factoryBeanLookupByType() { public void factoryBeanLookupByType() {
FooFactoryBean fooFactory = beanFactory.getBean(FooFactoryBean.class); FooFactoryBean fooFactory = beanFactory.getBean(FooFactoryBean.class);
assertNotNull(fooFactory); assertThat(fooFactory).isNotNull();
} }
@Test @Test
public void factoryBeanLookupByTypeAndNameDereference() { public void factoryBeanLookupByTypeAndNameDereference() {
FooFactoryBean fooFactory = beanFactory.getBean("&fooFactory", FooFactoryBean.class); FooFactoryBean fooFactory = beanFactory.getBean("&fooFactory", FooFactoryBean.class);
assertNotNull(fooFactory); assertThat(fooFactory).isNotNull();
} }
@Test @Test
@ -70,7 +69,7 @@ public class FactoryBeanLookupTests {
@Test @Test
public void factoryBeanObjectLookupByNameAndType() { public void factoryBeanObjectLookupByNameAndType() {
Foo foo = beanFactory.getBean("fooFactory", Foo.class); Foo foo = beanFactory.getBean("fooFactory", Foo.class);
assertNotNull(foo); assertThat(foo).isNotNull();
} }
} }

View File

@ -30,10 +30,7 @@ import org.springframework.core.io.Resource;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import org.springframework.util.Assert; import org.springframework.util.Assert;
import static org.junit.Assert.assertEquals; import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame;
import static org.springframework.tests.TestResourceUtils.qualifiedResource; import static org.springframework.tests.TestResourceUtils.qualifiedResource;
/** /**
@ -55,7 +52,7 @@ public class FactoryBeanTests {
DefaultListableBeanFactory factory = new DefaultListableBeanFactory(); DefaultListableBeanFactory factory = new DefaultListableBeanFactory();
new XmlBeanDefinitionReader(factory).loadBeanDefinitions(RETURNS_NULL_CONTEXT); new XmlBeanDefinitionReader(factory).loadBeanDefinitions(RETURNS_NULL_CONTEXT);
assertEquals("null", factory.getBean("factoryBean").toString()); assertThat(factory.getBean("factoryBean").toString()).isEqualTo("null");
} }
@Test @Test
@ -66,17 +63,17 @@ public class FactoryBeanTests {
BeanFactoryPostProcessor ppc = (BeanFactoryPostProcessor) factory.getBean("propertyPlaceholderConfigurer"); BeanFactoryPostProcessor ppc = (BeanFactoryPostProcessor) factory.getBean("propertyPlaceholderConfigurer");
ppc.postProcessBeanFactory(factory); ppc.postProcessBeanFactory(factory);
assertNull(factory.getType("betaFactory")); assertThat(factory.getType("betaFactory")).isNull();
Alpha alpha = (Alpha) factory.getBean("alpha"); Alpha alpha = (Alpha) factory.getBean("alpha");
Beta beta = (Beta) factory.getBean("beta"); Beta beta = (Beta) factory.getBean("beta");
Gamma gamma = (Gamma) factory.getBean("gamma"); Gamma gamma = (Gamma) factory.getBean("gamma");
Gamma gamma2 = (Gamma) factory.getBean("gammaFactory"); Gamma gamma2 = (Gamma) factory.getBean("gammaFactory");
assertSame(beta, alpha.getBeta()); assertThat(alpha.getBeta()).isSameAs(beta);
assertSame(gamma, beta.getGamma()); assertThat(beta.getGamma()).isSameAs(gamma);
assertSame(gamma2, beta.getGamma()); assertThat(beta.getGamma()).isSameAs(gamma2);
assertEquals("yourName", beta.getName()); assertThat(beta.getName()).isEqualTo("yourName");
} }
@Test @Test
@ -90,8 +87,8 @@ public class FactoryBeanTests {
Beta beta = (Beta) factory.getBean("beta"); Beta beta = (Beta) factory.getBean("beta");
Alpha alpha = (Alpha) factory.getBean("alpha"); Alpha alpha = (Alpha) factory.getBean("alpha");
Gamma gamma = (Gamma) factory.getBean("gamma"); Gamma gamma = (Gamma) factory.getBean("gamma");
assertSame(beta, alpha.getBeta()); assertThat(alpha.getBeta()).isSameAs(beta);
assertSame(gamma, beta.getGamma()); assertThat(beta.getGamma()).isSameAs(gamma);
} }
@Test @Test
@ -117,12 +114,12 @@ public class FactoryBeanTests {
factory.addBeanPostProcessor(counter); factory.addBeanPostProcessor(counter);
BeanImpl1 impl1 = factory.getBean(BeanImpl1.class); BeanImpl1 impl1 = factory.getBean(BeanImpl1.class);
assertNotNull(impl1); assertThat(impl1).isNotNull();
assertNotNull(impl1.getImpl2()); assertThat(impl1.getImpl2()).isNotNull();
assertNotNull(impl1.getImpl2()); assertThat(impl1.getImpl2()).isNotNull();
assertSame(impl1, impl1.getImpl2().getImpl1()); assertThat(impl1.getImpl2().getImpl1()).isSameAs(impl1);
assertEquals(1, counter.getCount("bean1")); assertThat(counter.getCount("bean1")).isEqualTo(1);
assertEquals(1, counter.getCount("bean2")); assertThat(counter.getCount("bean2")).isEqualTo(1);
} }

View File

@ -20,11 +20,8 @@ import org.junit.Test;
import org.springframework.beans.factory.wiring.BeanWiringInfo; import org.springframework.beans.factory.wiring.BeanWiringInfo;
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.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
/** /**
* @author Rick Evans * @author Rick Evans
@ -42,32 +39,32 @@ public class AnnotationBeanWiringInfoResolverTests {
public void testResolveWiringInfoWithAnInstanceOfANonAnnotatedClass() { public void testResolveWiringInfoWithAnInstanceOfANonAnnotatedClass() {
AnnotationBeanWiringInfoResolver resolver = new AnnotationBeanWiringInfoResolver(); AnnotationBeanWiringInfoResolver resolver = new AnnotationBeanWiringInfoResolver();
BeanWiringInfo info = resolver.resolveWiringInfo("java.lang.String is not @Configurable"); BeanWiringInfo info = resolver.resolveWiringInfo("java.lang.String is not @Configurable");
assertNull("Must be returning null for a non-@Configurable class instance", info); assertThat(info).as("Must be returning null for a non-@Configurable class instance").isNull();
} }
@Test @Test
public void testResolveWiringInfoWithAnInstanceOfAnAnnotatedClass() { public void testResolveWiringInfoWithAnInstanceOfAnAnnotatedClass() {
AnnotationBeanWiringInfoResolver resolver = new AnnotationBeanWiringInfoResolver(); AnnotationBeanWiringInfoResolver resolver = new AnnotationBeanWiringInfoResolver();
BeanWiringInfo info = resolver.resolveWiringInfo(new Soap()); BeanWiringInfo info = resolver.resolveWiringInfo(new Soap());
assertNotNull("Must *not* be returning null for a non-@Configurable class instance", info); assertThat(info).as("Must *not* be returning null for a non-@Configurable class instance").isNotNull();
} }
@Test @Test
public void testResolveWiringInfoWithAnInstanceOfAnAnnotatedClassWithAutowiringTurnedOffExplicitly() { public void testResolveWiringInfoWithAnInstanceOfAnAnnotatedClassWithAutowiringTurnedOffExplicitly() {
AnnotationBeanWiringInfoResolver resolver = new AnnotationBeanWiringInfoResolver(); AnnotationBeanWiringInfoResolver resolver = new AnnotationBeanWiringInfoResolver();
BeanWiringInfo info = resolver.resolveWiringInfo(new WirelessSoap()); BeanWiringInfo info = resolver.resolveWiringInfo(new WirelessSoap());
assertNotNull("Must *not* be returning null for an @Configurable class instance even when autowiring is NO", info); assertThat(info).as("Must *not* be returning null for an @Configurable class instance even when autowiring is NO").isNotNull();
assertFalse(info.indicatesAutowiring()); assertThat(info.indicatesAutowiring()).isFalse();
assertEquals(WirelessSoap.class.getName(), info.getBeanName()); assertThat(info.getBeanName()).isEqualTo(WirelessSoap.class.getName());
} }
@Test @Test
public void testResolveWiringInfoWithAnInstanceOfAnAnnotatedClassWithAutowiringTurnedOffExplicitlyAndCustomBeanName() { public void testResolveWiringInfoWithAnInstanceOfAnAnnotatedClassWithAutowiringTurnedOffExplicitlyAndCustomBeanName() {
AnnotationBeanWiringInfoResolver resolver = new AnnotationBeanWiringInfoResolver(); AnnotationBeanWiringInfoResolver resolver = new AnnotationBeanWiringInfoResolver();
BeanWiringInfo info = resolver.resolveWiringInfo(new NamedWirelessSoap()); BeanWiringInfo info = resolver.resolveWiringInfo(new NamedWirelessSoap());
assertNotNull("Must *not* be returning null for an @Configurable class instance even when autowiring is NO", info); assertThat(info).as("Must *not* be returning null for an @Configurable class instance even when autowiring is NO").isNotNull();
assertFalse(info.indicatesAutowiring()); assertThat(info.indicatesAutowiring()).isFalse();
assertEquals("DerBigStick", info.getBeanName()); assertThat(info.getBeanName()).isEqualTo("DerBigStick");
} }

View File

@ -24,7 +24,7 @@ import org.springframework.beans.factory.support.AutowireCandidateResolver;
import org.springframework.beans.factory.support.DefaultListableBeanFactory; import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.beans.factory.xml.XmlBeanDefinitionReader; import org.springframework.beans.factory.xml.XmlBeanDefinitionReader;
import static org.junit.Assert.assertEquals; import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.tests.TestResourceUtils.qualifiedResource; import static org.springframework.tests.TestResourceUtils.qualifiedResource;
/** /**
@ -47,7 +47,7 @@ public class CustomAutowireConfigurerTests {
bf.setAutowireCandidateResolver(customResolver); bf.setAutowireCandidateResolver(customResolver);
cac.postProcessBeanFactory(bf); cac.postProcessBeanFactory(bf);
TestBean testBean = (TestBean) bf.getBean("testBean"); TestBean testBean = (TestBean) bf.getBean("testBean");
assertEquals("#1!", testBean.getName()); assertThat(testBean.getName()).isEqualTo("#1!");
} }

View File

@ -45,14 +45,8 @@ import org.springframework.tests.sample.beans.NestedTestBean;
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.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNotSame;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
/** /**
* Unit tests for {@link org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor} * Unit tests for {@link org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor}
@ -91,7 +85,8 @@ public class InjectAnnotationBeanPostProcessorTests {
bf.getBean("testBean"); bf.getBean("testBean");
} }
catch (BeanCreationException ex) { catch (BeanCreationException ex) {
assertTrue(ex.getRootCause() instanceof IllegalStateException); boolean condition = ex.getRootCause() instanceof IllegalStateException;
assertThat(condition).isTrue();
} }
} }
@ -104,12 +99,12 @@ public class InjectAnnotationBeanPostProcessorTests {
bf.registerSingleton("testBean", tb); bf.registerSingleton("testBean", tb);
ResourceInjectionBean bean = (ResourceInjectionBean) bf.getBean("annotatedBean"); ResourceInjectionBean bean = (ResourceInjectionBean) bf.getBean("annotatedBean");
assertSame(tb, bean.getTestBean()); assertThat(bean.getTestBean()).isSameAs(tb);
assertSame(tb, bean.getTestBean2()); assertThat(bean.getTestBean2()).isSameAs(tb);
bean = (ResourceInjectionBean) bf.getBean("annotatedBean"); bean = (ResourceInjectionBean) bf.getBean("annotatedBean");
assertSame(tb, bean.getTestBean()); assertThat(bean.getTestBean()).isSameAs(tb);
assertSame(tb, bean.getTestBean2()); assertThat(bean.getTestBean2()).isSameAs(tb);
} }
@Test @Test
@ -123,20 +118,20 @@ public class InjectAnnotationBeanPostProcessorTests {
bf.registerSingleton("nestedTestBean", ntb); bf.registerSingleton("nestedTestBean", ntb);
TypedExtendedResourceInjectionBean bean = (TypedExtendedResourceInjectionBean) bf.getBean("annotatedBean"); TypedExtendedResourceInjectionBean bean = (TypedExtendedResourceInjectionBean) bf.getBean("annotatedBean");
assertSame(tb, bean.getTestBean()); assertThat(bean.getTestBean()).isSameAs(tb);
assertSame(tb, bean.getTestBean2()); assertThat(bean.getTestBean2()).isSameAs(tb);
assertSame(tb, bean.getTestBean3()); assertThat(bean.getTestBean3()).isSameAs(tb);
assertSame(tb, bean.getTestBean4()); assertThat(bean.getTestBean4()).isSameAs(tb);
assertSame(ntb, bean.getNestedTestBean()); assertThat(bean.getNestedTestBean()).isSameAs(ntb);
assertSame(bf, bean.getBeanFactory()); assertThat(bean.getBeanFactory()).isSameAs(bf);
bean = (TypedExtendedResourceInjectionBean) bf.getBean("annotatedBean"); bean = (TypedExtendedResourceInjectionBean) bf.getBean("annotatedBean");
assertSame(tb, bean.getTestBean()); assertThat(bean.getTestBean()).isSameAs(tb);
assertSame(tb, bean.getTestBean2()); assertThat(bean.getTestBean2()).isSameAs(tb);
assertSame(tb, bean.getTestBean3()); assertThat(bean.getTestBean3()).isSameAs(tb);
assertSame(tb, bean.getTestBean4()); assertThat(bean.getTestBean4()).isSameAs(tb);
assertSame(ntb, bean.getNestedTestBean()); assertThat(bean.getNestedTestBean()).isSameAs(ntb);
assertSame(bf, bean.getBeanFactory()); assertThat(bean.getBeanFactory()).isSameAs(bf);
} }
@Test @Test
@ -151,12 +146,12 @@ public class InjectAnnotationBeanPostProcessorTests {
bf.registerSingleton("nestedTestBean", ntb); bf.registerSingleton("nestedTestBean", ntb);
TypedExtendedResourceInjectionBean bean = (TypedExtendedResourceInjectionBean) bf.getBean("annotatedBean"); TypedExtendedResourceInjectionBean bean = (TypedExtendedResourceInjectionBean) bf.getBean("annotatedBean");
assertSame(tb, bean.getTestBean()); assertThat(bean.getTestBean()).isSameAs(tb);
assertSame(tb2, bean.getTestBean2()); assertThat(bean.getTestBean2()).isSameAs(tb2);
assertSame(tb, bean.getTestBean3()); assertThat(bean.getTestBean3()).isSameAs(tb);
assertSame(tb, bean.getTestBean4()); assertThat(bean.getTestBean4()).isSameAs(tb);
assertSame(ntb, bean.getNestedTestBean()); assertThat(bean.getNestedTestBean()).isSameAs(ntb);
assertSame(bf, bean.getBeanFactory()); assertThat(bean.getBeanFactory()).isSameAs(bf);
} }
@Test @Test
@ -172,12 +167,12 @@ public class InjectAnnotationBeanPostProcessorTests {
bf.registerSingleton("nestedTestBean", ntb); bf.registerSingleton("nestedTestBean", ntb);
TypedExtendedResourceInjectionBean bean = (TypedExtendedResourceInjectionBean) bf.getBean("annotatedBean"); TypedExtendedResourceInjectionBean bean = (TypedExtendedResourceInjectionBean) bf.getBean("annotatedBean");
assertSame(tb, bean.getTestBean()); assertThat(bean.getTestBean()).isSameAs(tb);
assertSame(tb, bean.getTestBean2()); assertThat(bean.getTestBean2()).isSameAs(tb);
assertSame(tb, bean.getTestBean3()); assertThat(bean.getTestBean3()).isSameAs(tb);
assertSame(tb, bean.getTestBean4()); assertThat(bean.getTestBean4()).isSameAs(tb);
assertSame(ntb, bean.getNestedTestBean()); assertThat(bean.getNestedTestBean()).isSameAs(ntb);
assertSame(bf, bean.getBeanFactory()); assertThat(bean.getBeanFactory()).isSameAs(bf);
} }
@Test @Test
@ -191,20 +186,20 @@ public class InjectAnnotationBeanPostProcessorTests {
bf.registerSingleton("nestedTestBean", ntb); bf.registerSingleton("nestedTestBean", ntb);
ConstructorResourceInjectionBean bean = (ConstructorResourceInjectionBean) bf.getBean("annotatedBean"); ConstructorResourceInjectionBean bean = (ConstructorResourceInjectionBean) bf.getBean("annotatedBean");
assertSame(tb, bean.getTestBean()); assertThat(bean.getTestBean()).isSameAs(tb);
assertSame(tb, bean.getTestBean2()); assertThat(bean.getTestBean2()).isSameAs(tb);
assertSame(tb, bean.getTestBean3()); assertThat(bean.getTestBean3()).isSameAs(tb);
assertSame(tb, bean.getTestBean4()); assertThat(bean.getTestBean4()).isSameAs(tb);
assertSame(ntb, bean.getNestedTestBean()); assertThat(bean.getNestedTestBean()).isSameAs(ntb);
assertSame(bf, bean.getBeanFactory()); assertThat(bean.getBeanFactory()).isSameAs(bf);
bean = (ConstructorResourceInjectionBean) bf.getBean("annotatedBean"); bean = (ConstructorResourceInjectionBean) bf.getBean("annotatedBean");
assertSame(tb, bean.getTestBean()); assertThat(bean.getTestBean()).isSameAs(tb);
assertSame(tb, bean.getTestBean2()); assertThat(bean.getTestBean2()).isSameAs(tb);
assertSame(tb, bean.getTestBean3()); assertThat(bean.getTestBean3()).isSameAs(tb);
assertSame(tb, bean.getTestBean4()); assertThat(bean.getTestBean4()).isSameAs(tb);
assertSame(ntb, bean.getNestedTestBean()); assertThat(bean.getNestedTestBean()).isSameAs(ntb);
assertSame(bf, bean.getBeanFactory()); assertThat(bean.getBeanFactory()).isSameAs(bf);
} }
@Test @Test
@ -219,11 +214,11 @@ public class InjectAnnotationBeanPostProcessorTests {
bf.registerSingleton("nestedTestBean2", ntb2); bf.registerSingleton("nestedTestBean2", ntb2);
ConstructorsCollectionResourceInjectionBean bean = (ConstructorsCollectionResourceInjectionBean) bf.getBean("annotatedBean"); ConstructorsCollectionResourceInjectionBean bean = (ConstructorsCollectionResourceInjectionBean) bf.getBean("annotatedBean");
assertNull(bean.getTestBean3()); assertThat(bean.getTestBean3()).isNull();
assertSame(tb, bean.getTestBean4()); assertThat(bean.getTestBean4()).isSameAs(tb);
assertEquals(2, bean.getNestedTestBeans().size()); assertThat(bean.getNestedTestBeans().size()).isEqualTo(2);
assertSame(ntb1, bean.getNestedTestBeans().get(0)); assertThat(bean.getNestedTestBeans().get(0)).isSameAs(ntb1);
assertSame(ntb2, bean.getNestedTestBeans().get(1)); assertThat(bean.getNestedTestBeans().get(1)).isSameAs(ntb2);
} }
@Test @Test
@ -233,8 +228,8 @@ public class InjectAnnotationBeanPostProcessorTests {
bf.registerSingleton("testBean", tb); bf.registerSingleton("testBean", tb);
ConstructorsResourceInjectionBean bean = (ConstructorsResourceInjectionBean) bf.getBean("annotatedBean"); ConstructorsResourceInjectionBean bean = (ConstructorsResourceInjectionBean) bf.getBean("annotatedBean");
assertSame(tb, bean.getTestBean3()); assertThat(bean.getTestBean3()).isSameAs(tb);
assertNull(bean.getTestBean4()); assertThat(bean.getTestBean4()).isNull();
} }
@Test @Test
@ -248,18 +243,18 @@ public class InjectAnnotationBeanPostProcessorTests {
bf.registerSingleton("testBean2", tb1); bf.registerSingleton("testBean2", tb1);
MapConstructorInjectionBean bean = (MapConstructorInjectionBean) bf.getBean("annotatedBean"); MapConstructorInjectionBean bean = (MapConstructorInjectionBean) bf.getBean("annotatedBean");
assertEquals(2, bean.getTestBeanMap().size()); assertThat(bean.getTestBeanMap().size()).isEqualTo(2);
assertTrue(bean.getTestBeanMap().keySet().contains("testBean1")); assertThat(bean.getTestBeanMap().keySet().contains("testBean1")).isTrue();
assertTrue(bean.getTestBeanMap().keySet().contains("testBean2")); assertThat(bean.getTestBeanMap().keySet().contains("testBean2")).isTrue();
assertTrue(bean.getTestBeanMap().values().contains(tb1)); assertThat(bean.getTestBeanMap().values().contains(tb1)).isTrue();
assertTrue(bean.getTestBeanMap().values().contains(tb2)); assertThat(bean.getTestBeanMap().values().contains(tb2)).isTrue();
bean = (MapConstructorInjectionBean) bf.getBean("annotatedBean"); bean = (MapConstructorInjectionBean) bf.getBean("annotatedBean");
assertEquals(2, bean.getTestBeanMap().size()); assertThat(bean.getTestBeanMap().size()).isEqualTo(2);
assertTrue(bean.getTestBeanMap().keySet().contains("testBean1")); assertThat(bean.getTestBeanMap().keySet().contains("testBean1")).isTrue();
assertTrue(bean.getTestBeanMap().keySet().contains("testBean2")); assertThat(bean.getTestBeanMap().keySet().contains("testBean2")).isTrue();
assertTrue(bean.getTestBeanMap().values().contains(tb1)); assertThat(bean.getTestBeanMap().values().contains(tb1)).isTrue();
assertTrue(bean.getTestBeanMap().values().contains(tb2)); assertThat(bean.getTestBeanMap().values().contains(tb2)).isTrue();
} }
@Test @Test
@ -273,18 +268,18 @@ public class InjectAnnotationBeanPostProcessorTests {
bf.registerSingleton("testBean2", tb1); bf.registerSingleton("testBean2", tb1);
MapFieldInjectionBean bean = (MapFieldInjectionBean) bf.getBean("annotatedBean"); MapFieldInjectionBean bean = (MapFieldInjectionBean) bf.getBean("annotatedBean");
assertEquals(2, bean.getTestBeanMap().size()); assertThat(bean.getTestBeanMap().size()).isEqualTo(2);
assertTrue(bean.getTestBeanMap().keySet().contains("testBean1")); assertThat(bean.getTestBeanMap().keySet().contains("testBean1")).isTrue();
assertTrue(bean.getTestBeanMap().keySet().contains("testBean2")); assertThat(bean.getTestBeanMap().keySet().contains("testBean2")).isTrue();
assertTrue(bean.getTestBeanMap().values().contains(tb1)); assertThat(bean.getTestBeanMap().values().contains(tb1)).isTrue();
assertTrue(bean.getTestBeanMap().values().contains(tb2)); assertThat(bean.getTestBeanMap().values().contains(tb2)).isTrue();
bean = (MapFieldInjectionBean) bf.getBean("annotatedBean"); bean = (MapFieldInjectionBean) bf.getBean("annotatedBean");
assertEquals(2, bean.getTestBeanMap().size()); assertThat(bean.getTestBeanMap().size()).isEqualTo(2);
assertTrue(bean.getTestBeanMap().keySet().contains("testBean1")); assertThat(bean.getTestBeanMap().keySet().contains("testBean1")).isTrue();
assertTrue(bean.getTestBeanMap().keySet().contains("testBean2")); assertThat(bean.getTestBeanMap().keySet().contains("testBean2")).isTrue();
assertTrue(bean.getTestBeanMap().values().contains(tb1)); assertThat(bean.getTestBeanMap().values().contains(tb1)).isTrue();
assertTrue(bean.getTestBeanMap().values().contains(tb2)); assertThat(bean.getTestBeanMap().values().contains(tb2)).isTrue();
} }
@Test @Test
@ -296,16 +291,16 @@ public class InjectAnnotationBeanPostProcessorTests {
bf.registerSingleton("testBean", tb); bf.registerSingleton("testBean", tb);
MapMethodInjectionBean bean = (MapMethodInjectionBean) bf.getBean("annotatedBean"); MapMethodInjectionBean bean = (MapMethodInjectionBean) bf.getBean("annotatedBean");
assertEquals(1, bean.getTestBeanMap().size()); assertThat(bean.getTestBeanMap().size()).isEqualTo(1);
assertTrue(bean.getTestBeanMap().keySet().contains("testBean")); assertThat(bean.getTestBeanMap().keySet().contains("testBean")).isTrue();
assertTrue(bean.getTestBeanMap().values().contains(tb)); assertThat(bean.getTestBeanMap().values().contains(tb)).isTrue();
assertSame(tb, bean.getTestBean()); assertThat(bean.getTestBean()).isSameAs(tb);
bean = (MapMethodInjectionBean) bf.getBean("annotatedBean"); bean = (MapMethodInjectionBean) bf.getBean("annotatedBean");
assertEquals(1, bean.getTestBeanMap().size()); assertThat(bean.getTestBeanMap().size()).isEqualTo(1);
assertTrue(bean.getTestBeanMap().keySet().contains("testBean")); assertThat(bean.getTestBeanMap().keySet().contains("testBean")).isTrue();
assertTrue(bean.getTestBeanMap().values().contains(tb)); assertThat(bean.getTestBeanMap().values().contains(tb)).isTrue();
assertSame(tb, bean.getTestBean()); assertThat(bean.getTestBean()).isSameAs(tb);
} }
@Test @Test
@ -327,10 +322,10 @@ public class InjectAnnotationBeanPostProcessorTests {
MapMethodInjectionBean bean = (MapMethodInjectionBean) bf.getBean("annotatedBean"); MapMethodInjectionBean bean = (MapMethodInjectionBean) bf.getBean("annotatedBean");
TestBean tb = (TestBean) bf.getBean("testBean1"); TestBean tb = (TestBean) bf.getBean("testBean1");
assertEquals(1, bean.getTestBeanMap().size()); assertThat(bean.getTestBeanMap().size()).isEqualTo(1);
assertTrue(bean.getTestBeanMap().keySet().contains("testBean1")); assertThat(bean.getTestBeanMap().keySet().contains("testBean1")).isTrue();
assertTrue(bean.getTestBeanMap().values().contains(tb)); assertThat(bean.getTestBeanMap().values().contains(tb)).isTrue();
assertSame(tb, bean.getTestBean()); assertThat(bean.getTestBean()).isSameAs(tb);
} }
@Test @Test
@ -342,7 +337,7 @@ public class InjectAnnotationBeanPostProcessorTests {
bf.registerBeanDefinition("testBean2", new RootBeanDefinition(TestBean.class)); bf.registerBeanDefinition("testBean2", new RootBeanDefinition(TestBean.class));
ObjectFactoryQualifierFieldInjectionBean bean = (ObjectFactoryQualifierFieldInjectionBean) bf.getBean("annotatedBean"); ObjectFactoryQualifierFieldInjectionBean bean = (ObjectFactoryQualifierFieldInjectionBean) bf.getBean("annotatedBean");
assertSame(bf.getBean("testBean"), bean.getTestBean()); assertThat(bean.getTestBean()).isSameAs(bf.getBean("testBean"));
} }
@Test @Test
@ -353,7 +348,7 @@ public class InjectAnnotationBeanPostProcessorTests {
bf.registerBeanDefinition("testBean", bd); bf.registerBeanDefinition("testBean", bd);
ObjectFactoryQualifierFieldInjectionBean bean = (ObjectFactoryQualifierFieldInjectionBean) bf.getBean("annotatedBean"); ObjectFactoryQualifierFieldInjectionBean bean = (ObjectFactoryQualifierFieldInjectionBean) bf.getBean("annotatedBean");
assertSame(bf.getBean("testBean"), bean.getTestBean()); assertThat(bean.getTestBean()).isSameAs(bf.getBean("testBean"));
} }
@Test @Test
@ -367,10 +362,10 @@ public class InjectAnnotationBeanPostProcessorTests {
bf.registerBeanDefinition("testBean2", new RootBeanDefinition(TestBean.class)); bf.registerBeanDefinition("testBean2", new RootBeanDefinition(TestBean.class));
ObjectFactoryQualifierFieldInjectionBean bean = (ObjectFactoryQualifierFieldInjectionBean) bf.getBean("annotatedBean"); ObjectFactoryQualifierFieldInjectionBean bean = (ObjectFactoryQualifierFieldInjectionBean) bf.getBean("annotatedBean");
assertSame(bf.getBean("testBean"), bean.getTestBean()); assertThat(bean.getTestBean()).isSameAs(bf.getBean("testBean"));
ObjectFactoryQualifierFieldInjectionBean anotherBean = (ObjectFactoryQualifierFieldInjectionBean) bf.getBean("annotatedBean"); ObjectFactoryQualifierFieldInjectionBean anotherBean = (ObjectFactoryQualifierFieldInjectionBean) bf.getBean("annotatedBean");
assertNotSame(anotherBean, bean); assertThat(bean).isNotSameAs(anotherBean);
assertSame(bf.getBean("testBean"), bean.getTestBean()); assertThat(bean.getTestBean()).isSameAs(bf.getBean("testBean"));
} }
@Test @Test
@ -384,10 +379,10 @@ public class InjectAnnotationBeanPostProcessorTests {
bf.registerBeanDefinition("testBean2", new RootBeanDefinition(TestBean.class)); bf.registerBeanDefinition("testBean2", new RootBeanDefinition(TestBean.class));
ObjectFactoryQualifierMethodInjectionBean bean = (ObjectFactoryQualifierMethodInjectionBean) bf.getBean("annotatedBean"); ObjectFactoryQualifierMethodInjectionBean bean = (ObjectFactoryQualifierMethodInjectionBean) bf.getBean("annotatedBean");
assertSame(bf.getBean("testBean"), bean.getTestBean()); assertThat(bean.getTestBean()).isSameAs(bf.getBean("testBean"));
ObjectFactoryQualifierMethodInjectionBean anotherBean = (ObjectFactoryQualifierMethodInjectionBean) bf.getBean("annotatedBean"); ObjectFactoryQualifierMethodInjectionBean anotherBean = (ObjectFactoryQualifierMethodInjectionBean) bf.getBean("annotatedBean");
assertNotSame(anotherBean, bean); assertThat(bean).isNotSameAs(anotherBean);
assertSame(bf.getBean("testBean"), bean.getTestBean()); assertThat(bean.getTestBean()).isSameAs(bf.getBean("testBean"));
} }
@Test @Test
@ -397,9 +392,9 @@ public class InjectAnnotationBeanPostProcessorTests {
bf.setSerializationId("test"); bf.setSerializationId("test");
ObjectFactoryFieldInjectionBean bean = (ObjectFactoryFieldInjectionBean) bf.getBean("annotatedBean"); ObjectFactoryFieldInjectionBean bean = (ObjectFactoryFieldInjectionBean) bf.getBean("annotatedBean");
assertSame(bf.getBean("testBean"), bean.getTestBean()); assertThat(bean.getTestBean()).isSameAs(bf.getBean("testBean"));
bean = (ObjectFactoryFieldInjectionBean) SerializationTestUtils.serializeAndDeserialize(bean); bean = (ObjectFactoryFieldInjectionBean) SerializationTestUtils.serializeAndDeserialize(bean);
assertSame(bf.getBean("testBean"), bean.getTestBean()); assertThat(bean.getTestBean()).isSameAs(bf.getBean("testBean"));
} }
@Test @Test
@ -409,9 +404,9 @@ public class InjectAnnotationBeanPostProcessorTests {
bf.setSerializationId("test"); bf.setSerializationId("test");
ObjectFactoryMethodInjectionBean bean = (ObjectFactoryMethodInjectionBean) bf.getBean("annotatedBean"); ObjectFactoryMethodInjectionBean bean = (ObjectFactoryMethodInjectionBean) bf.getBean("annotatedBean");
assertSame(bf.getBean("testBean"), bean.getTestBean()); assertThat(bean.getTestBean()).isSameAs(bf.getBean("testBean"));
bean = (ObjectFactoryMethodInjectionBean) SerializationTestUtils.serializeAndDeserialize(bean); bean = (ObjectFactoryMethodInjectionBean) SerializationTestUtils.serializeAndDeserialize(bean);
assertSame(bf.getBean("testBean"), bean.getTestBean()); assertThat(bean.getTestBean()).isSameAs(bf.getBean("testBean"));
} }
@Test @Test
@ -421,9 +416,9 @@ public class InjectAnnotationBeanPostProcessorTests {
bf.setSerializationId("test"); bf.setSerializationId("test");
ObjectFactoryListFieldInjectionBean bean = (ObjectFactoryListFieldInjectionBean) bf.getBean("annotatedBean"); ObjectFactoryListFieldInjectionBean bean = (ObjectFactoryListFieldInjectionBean) bf.getBean("annotatedBean");
assertSame(bf.getBean("testBean"), bean.getTestBean()); assertThat(bean.getTestBean()).isSameAs(bf.getBean("testBean"));
bean = (ObjectFactoryListFieldInjectionBean) SerializationTestUtils.serializeAndDeserialize(bean); bean = (ObjectFactoryListFieldInjectionBean) SerializationTestUtils.serializeAndDeserialize(bean);
assertSame(bf.getBean("testBean"), bean.getTestBean()); assertThat(bean.getTestBean()).isSameAs(bf.getBean("testBean"));
} }
@Test @Test
@ -433,9 +428,9 @@ public class InjectAnnotationBeanPostProcessorTests {
bf.setSerializationId("test"); bf.setSerializationId("test");
ObjectFactoryListMethodInjectionBean bean = (ObjectFactoryListMethodInjectionBean) bf.getBean("annotatedBean"); ObjectFactoryListMethodInjectionBean bean = (ObjectFactoryListMethodInjectionBean) bf.getBean("annotatedBean");
assertSame(bf.getBean("testBean"), bean.getTestBean()); assertThat(bean.getTestBean()).isSameAs(bf.getBean("testBean"));
bean = (ObjectFactoryListMethodInjectionBean) SerializationTestUtils.serializeAndDeserialize(bean); bean = (ObjectFactoryListMethodInjectionBean) SerializationTestUtils.serializeAndDeserialize(bean);
assertSame(bf.getBean("testBean"), bean.getTestBean()); assertThat(bean.getTestBean()).isSameAs(bf.getBean("testBean"));
} }
@Test @Test
@ -445,9 +440,9 @@ public class InjectAnnotationBeanPostProcessorTests {
bf.setSerializationId("test"); bf.setSerializationId("test");
ObjectFactoryMapFieldInjectionBean bean = (ObjectFactoryMapFieldInjectionBean) bf.getBean("annotatedBean"); ObjectFactoryMapFieldInjectionBean bean = (ObjectFactoryMapFieldInjectionBean) bf.getBean("annotatedBean");
assertSame(bf.getBean("testBean"), bean.getTestBean()); assertThat(bean.getTestBean()).isSameAs(bf.getBean("testBean"));
bean = (ObjectFactoryMapFieldInjectionBean) SerializationTestUtils.serializeAndDeserialize(bean); bean = (ObjectFactoryMapFieldInjectionBean) SerializationTestUtils.serializeAndDeserialize(bean);
assertSame(bf.getBean("testBean"), bean.getTestBean()); assertThat(bean.getTestBean()).isSameAs(bf.getBean("testBean"));
} }
@Test @Test
@ -457,9 +452,9 @@ public class InjectAnnotationBeanPostProcessorTests {
bf.setSerializationId("test"); bf.setSerializationId("test");
ObjectFactoryMapMethodInjectionBean bean = (ObjectFactoryMapMethodInjectionBean) bf.getBean("annotatedBean"); ObjectFactoryMapMethodInjectionBean bean = (ObjectFactoryMapMethodInjectionBean) bf.getBean("annotatedBean");
assertSame(bf.getBean("testBean"), bean.getTestBean()); assertThat(bean.getTestBean()).isSameAs(bf.getBean("testBean"));
bean = (ObjectFactoryMapMethodInjectionBean) SerializationTestUtils.serializeAndDeserialize(bean); bean = (ObjectFactoryMapMethodInjectionBean) SerializationTestUtils.serializeAndDeserialize(bean);
assertSame(bf.getBean("testBean"), bean.getTestBean()); assertThat(bean.getTestBean()).isSameAs(bf.getBean("testBean"));
} }
/** /**
@ -475,10 +470,9 @@ public class InjectAnnotationBeanPostProcessorTests {
final StringFactoryBean factoryBean = (StringFactoryBean) bf.getBean("&stringFactoryBean"); final StringFactoryBean factoryBean = (StringFactoryBean) bf.getBean("&stringFactoryBean");
final FactoryBeanDependentBean bean = (FactoryBeanDependentBean) bf.getBean("factoryBeanDependentBean"); final FactoryBeanDependentBean bean = (FactoryBeanDependentBean) bf.getBean("factoryBeanDependentBean");
assertNotNull("The singleton StringFactoryBean should have been registered.", factoryBean); assertThat(factoryBean).as("The singleton StringFactoryBean should have been registered.").isNotNull();
assertNotNull("The factoryBeanDependentBean should have been registered.", bean); assertThat(bean).as("The factoryBeanDependentBean should have been registered.").isNotNull();
assertEquals("The FactoryBeanDependentBean should have been autowired 'by type' with the StringFactoryBean.", assertThat(bean.getFactoryBean()).as("The FactoryBeanDependentBean should have been autowired 'by type' with the StringFactoryBean.").isEqualTo(factoryBean);
factoryBean, bean.getFactoryBean());
} }
@Test @Test
@ -487,7 +481,7 @@ public class InjectAnnotationBeanPostProcessorTests {
bf.registerBeanDefinition("testBean", new RootBeanDefinition(TestBean.class)); bf.registerBeanDefinition("testBean", new RootBeanDefinition(TestBean.class));
NullableFieldInjectionBean bean = (NullableFieldInjectionBean) bf.getBean("annotatedBean"); NullableFieldInjectionBean bean = (NullableFieldInjectionBean) bf.getBean("annotatedBean");
assertSame(bf.getBean("testBean"), bean.getTestBean()); assertThat(bean.getTestBean()).isSameAs(bf.getBean("testBean"));
} }
@Test @Test
@ -495,7 +489,7 @@ public class InjectAnnotationBeanPostProcessorTests {
bf.registerBeanDefinition("annotatedBean", new RootBeanDefinition(NullableFieldInjectionBean.class)); bf.registerBeanDefinition("annotatedBean", new RootBeanDefinition(NullableFieldInjectionBean.class));
NullableFieldInjectionBean bean = (NullableFieldInjectionBean) bf.getBean("annotatedBean"); NullableFieldInjectionBean bean = (NullableFieldInjectionBean) bf.getBean("annotatedBean");
assertNull(bean.getTestBean()); assertThat(bean.getTestBean()).isNull();
} }
@Test @Test
@ -504,7 +498,7 @@ public class InjectAnnotationBeanPostProcessorTests {
bf.registerBeanDefinition("testBean", new RootBeanDefinition(TestBean.class)); bf.registerBeanDefinition("testBean", new RootBeanDefinition(TestBean.class));
NullableMethodInjectionBean bean = (NullableMethodInjectionBean) bf.getBean("annotatedBean"); NullableMethodInjectionBean bean = (NullableMethodInjectionBean) bf.getBean("annotatedBean");
assertSame(bf.getBean("testBean"), bean.getTestBean()); assertThat(bean.getTestBean()).isSameAs(bf.getBean("testBean"));
} }
@Test @Test
@ -512,7 +506,7 @@ public class InjectAnnotationBeanPostProcessorTests {
bf.registerBeanDefinition("annotatedBean", new RootBeanDefinition(NullableMethodInjectionBean.class)); bf.registerBeanDefinition("annotatedBean", new RootBeanDefinition(NullableMethodInjectionBean.class));
NullableMethodInjectionBean bean = (NullableMethodInjectionBean) bf.getBean("annotatedBean"); NullableMethodInjectionBean bean = (NullableMethodInjectionBean) bf.getBean("annotatedBean");
assertNull(bean.getTestBean()); assertThat(bean.getTestBean()).isNull();
} }
@Test @Test
@ -521,8 +515,8 @@ public class InjectAnnotationBeanPostProcessorTests {
bf.registerBeanDefinition("testBean", new RootBeanDefinition(TestBean.class)); bf.registerBeanDefinition("testBean", new RootBeanDefinition(TestBean.class));
OptionalFieldInjectionBean bean = (OptionalFieldInjectionBean) bf.getBean("annotatedBean"); OptionalFieldInjectionBean bean = (OptionalFieldInjectionBean) bf.getBean("annotatedBean");
assertTrue(bean.getTestBean().isPresent()); assertThat(bean.getTestBean().isPresent()).isTrue();
assertSame(bf.getBean("testBean"), bean.getTestBean().get()); assertThat(bean.getTestBean().get()).isSameAs(bf.getBean("testBean"));
} }
@Test @Test
@ -530,7 +524,7 @@ public class InjectAnnotationBeanPostProcessorTests {
bf.registerBeanDefinition("annotatedBean", new RootBeanDefinition(OptionalFieldInjectionBean.class)); bf.registerBeanDefinition("annotatedBean", new RootBeanDefinition(OptionalFieldInjectionBean.class));
OptionalFieldInjectionBean bean = (OptionalFieldInjectionBean) bf.getBean("annotatedBean"); OptionalFieldInjectionBean bean = (OptionalFieldInjectionBean) bf.getBean("annotatedBean");
assertFalse(bean.getTestBean().isPresent()); assertThat(bean.getTestBean().isPresent()).isFalse();
} }
@Test @Test
@ -539,8 +533,8 @@ public class InjectAnnotationBeanPostProcessorTests {
bf.registerBeanDefinition("testBean", new RootBeanDefinition(TestBean.class)); bf.registerBeanDefinition("testBean", new RootBeanDefinition(TestBean.class));
OptionalMethodInjectionBean bean = (OptionalMethodInjectionBean) bf.getBean("annotatedBean"); OptionalMethodInjectionBean bean = (OptionalMethodInjectionBean) bf.getBean("annotatedBean");
assertTrue(bean.getTestBean().isPresent()); assertThat(bean.getTestBean().isPresent()).isTrue();
assertSame(bf.getBean("testBean"), bean.getTestBean().get()); assertThat(bean.getTestBean().get()).isSameAs(bf.getBean("testBean"));
} }
@Test @Test
@ -548,7 +542,7 @@ public class InjectAnnotationBeanPostProcessorTests {
bf.registerBeanDefinition("annotatedBean", new RootBeanDefinition(OptionalMethodInjectionBean.class)); bf.registerBeanDefinition("annotatedBean", new RootBeanDefinition(OptionalMethodInjectionBean.class));
OptionalMethodInjectionBean bean = (OptionalMethodInjectionBean) bf.getBean("annotatedBean"); OptionalMethodInjectionBean bean = (OptionalMethodInjectionBean) bf.getBean("annotatedBean");
assertFalse(bean.getTestBean().isPresent()); assertThat(bean.getTestBean().isPresent()).isFalse();
} }
@Test @Test
@ -557,8 +551,8 @@ public class InjectAnnotationBeanPostProcessorTests {
bf.registerBeanDefinition("testBean", new RootBeanDefinition(TestBean.class)); bf.registerBeanDefinition("testBean", new RootBeanDefinition(TestBean.class));
OptionalListFieldInjectionBean bean = (OptionalListFieldInjectionBean) bf.getBean("annotatedBean"); OptionalListFieldInjectionBean bean = (OptionalListFieldInjectionBean) bf.getBean("annotatedBean");
assertTrue(bean.getTestBean().isPresent()); assertThat(bean.getTestBean().isPresent()).isTrue();
assertSame(bf.getBean("testBean"), bean.getTestBean().get().get(0)); assertThat(bean.getTestBean().get().get(0)).isSameAs(bf.getBean("testBean"));
} }
@Test @Test
@ -566,7 +560,7 @@ public class InjectAnnotationBeanPostProcessorTests {
bf.registerBeanDefinition("annotatedBean", new RootBeanDefinition(OptionalListFieldInjectionBean.class)); bf.registerBeanDefinition("annotatedBean", new RootBeanDefinition(OptionalListFieldInjectionBean.class));
OptionalListFieldInjectionBean bean = (OptionalListFieldInjectionBean) bf.getBean("annotatedBean"); OptionalListFieldInjectionBean bean = (OptionalListFieldInjectionBean) bf.getBean("annotatedBean");
assertFalse(bean.getTestBean().isPresent()); assertThat(bean.getTestBean().isPresent()).isFalse();
} }
@Test @Test
@ -575,8 +569,8 @@ public class InjectAnnotationBeanPostProcessorTests {
bf.registerBeanDefinition("testBean", new RootBeanDefinition(TestBean.class)); bf.registerBeanDefinition("testBean", new RootBeanDefinition(TestBean.class));
OptionalListMethodInjectionBean bean = (OptionalListMethodInjectionBean) bf.getBean("annotatedBean"); OptionalListMethodInjectionBean bean = (OptionalListMethodInjectionBean) bf.getBean("annotatedBean");
assertTrue(bean.getTestBean().isPresent()); assertThat(bean.getTestBean().isPresent()).isTrue();
assertSame(bf.getBean("testBean"), bean.getTestBean().get().get(0)); assertThat(bean.getTestBean().get().get(0)).isSameAs(bf.getBean("testBean"));
} }
@Test @Test
@ -584,7 +578,7 @@ public class InjectAnnotationBeanPostProcessorTests {
bf.registerBeanDefinition("annotatedBean", new RootBeanDefinition(OptionalListMethodInjectionBean.class)); bf.registerBeanDefinition("annotatedBean", new RootBeanDefinition(OptionalListMethodInjectionBean.class));
OptionalListMethodInjectionBean bean = (OptionalListMethodInjectionBean) bf.getBean("annotatedBean"); OptionalListMethodInjectionBean bean = (OptionalListMethodInjectionBean) bf.getBean("annotatedBean");
assertFalse(bean.getTestBean().isPresent()); assertThat(bean.getTestBean().isPresent()).isFalse();
} }
@Test @Test
@ -593,8 +587,8 @@ public class InjectAnnotationBeanPostProcessorTests {
bf.registerBeanDefinition("testBean", new RootBeanDefinition(TestBean.class)); bf.registerBeanDefinition("testBean", new RootBeanDefinition(TestBean.class));
ProviderOfOptionalFieldInjectionBean bean = (ProviderOfOptionalFieldInjectionBean) bf.getBean("annotatedBean"); ProviderOfOptionalFieldInjectionBean bean = (ProviderOfOptionalFieldInjectionBean) bf.getBean("annotatedBean");
assertTrue(bean.getTestBean().isPresent()); assertThat(bean.getTestBean().isPresent()).isTrue();
assertSame(bf.getBean("testBean"), bean.getTestBean().get()); assertThat(bean.getTestBean().get()).isSameAs(bf.getBean("testBean"));
} }
@Test @Test
@ -602,7 +596,7 @@ public class InjectAnnotationBeanPostProcessorTests {
bf.registerBeanDefinition("annotatedBean", new RootBeanDefinition(ProviderOfOptionalFieldInjectionBean.class)); bf.registerBeanDefinition("annotatedBean", new RootBeanDefinition(ProviderOfOptionalFieldInjectionBean.class));
ProviderOfOptionalFieldInjectionBean bean = (ProviderOfOptionalFieldInjectionBean) bf.getBean("annotatedBean"); ProviderOfOptionalFieldInjectionBean bean = (ProviderOfOptionalFieldInjectionBean) bf.getBean("annotatedBean");
assertFalse(bean.getTestBean().isPresent()); assertThat(bean.getTestBean().isPresent()).isFalse();
} }
@Test @Test
@ -611,8 +605,8 @@ public class InjectAnnotationBeanPostProcessorTests {
bf.registerBeanDefinition("testBean", new RootBeanDefinition(TestBean.class)); bf.registerBeanDefinition("testBean", new RootBeanDefinition(TestBean.class));
ProviderOfOptionalMethodInjectionBean bean = (ProviderOfOptionalMethodInjectionBean) bf.getBean("annotatedBean"); ProviderOfOptionalMethodInjectionBean bean = (ProviderOfOptionalMethodInjectionBean) bf.getBean("annotatedBean");
assertTrue(bean.getTestBean().isPresent()); assertThat(bean.getTestBean().isPresent()).isTrue();
assertSame(bf.getBean("testBean"), bean.getTestBean().get()); assertThat(bean.getTestBean().get()).isSameAs(bf.getBean("testBean"));
} }
@Test @Test
@ -620,14 +614,14 @@ public class InjectAnnotationBeanPostProcessorTests {
bf.registerBeanDefinition("annotatedBean", new RootBeanDefinition(ProviderOfOptionalMethodInjectionBean.class)); bf.registerBeanDefinition("annotatedBean", new RootBeanDefinition(ProviderOfOptionalMethodInjectionBean.class));
ProviderOfOptionalMethodInjectionBean bean = (ProviderOfOptionalMethodInjectionBean) bf.getBean("annotatedBean"); ProviderOfOptionalMethodInjectionBean bean = (ProviderOfOptionalMethodInjectionBean) bf.getBean("annotatedBean");
assertFalse(bean.getTestBean().isPresent()); assertThat(bean.getTestBean().isPresent()).isFalse();
} }
@Test @Test
public void testAnnotatedDefaultConstructor() { public void testAnnotatedDefaultConstructor() {
bf.registerBeanDefinition("annotatedBean", new RootBeanDefinition(AnnotatedDefaultConstructorBean.class)); bf.registerBeanDefinition("annotatedBean", new RootBeanDefinition(AnnotatedDefaultConstructorBean.class));
assertNotNull(bf.getBean("annotatedBean")); assertThat(bf.getBean("annotatedBean")).isNotNull();
} }

View File

@ -23,10 +23,8 @@ import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.beans.factory.support.RootBeanDefinition; import org.springframework.beans.factory.support.RootBeanDefinition;
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.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertSame;
/** /**
* @author Karl Pietrzak * @author Karl Pietrzak
@ -54,59 +52,59 @@ public class LookupAnnotationTests {
@Test @Test
public void testWithoutConstructorArg() { public void testWithoutConstructorArg() {
AbstractBean bean = (AbstractBean) beanFactory.getBean("abstractBean"); AbstractBean bean = (AbstractBean) beanFactory.getBean("abstractBean");
assertNotNull(bean); assertThat(bean).isNotNull();
Object expected = bean.get(); Object expected = bean.get();
assertEquals(TestBean.class, expected.getClass()); assertThat(expected.getClass()).isEqualTo(TestBean.class);
assertSame(bean, beanFactory.getBean(BeanConsumer.class).abstractBean); assertThat(beanFactory.getBean(BeanConsumer.class).abstractBean).isSameAs(bean);
} }
@Test @Test
public void testWithOverloadedArg() { public void testWithOverloadedArg() {
AbstractBean bean = (AbstractBean) beanFactory.getBean("abstractBean"); AbstractBean bean = (AbstractBean) beanFactory.getBean("abstractBean");
assertNotNull(bean); assertThat(bean).isNotNull();
TestBean expected = bean.get("haha"); TestBean expected = bean.get("haha");
assertEquals(TestBean.class, expected.getClass()); assertThat(expected.getClass()).isEqualTo(TestBean.class);
assertEquals("haha", expected.getName()); assertThat(expected.getName()).isEqualTo("haha");
assertSame(bean, beanFactory.getBean(BeanConsumer.class).abstractBean); assertThat(beanFactory.getBean(BeanConsumer.class).abstractBean).isSameAs(bean);
} }
@Test @Test
public void testWithOneConstructorArg() { public void testWithOneConstructorArg() {
AbstractBean bean = (AbstractBean) beanFactory.getBean("abstractBean"); AbstractBean bean = (AbstractBean) beanFactory.getBean("abstractBean");
assertNotNull(bean); assertThat(bean).isNotNull();
TestBean expected = bean.getOneArgument("haha"); TestBean expected = bean.getOneArgument("haha");
assertEquals(TestBean.class, expected.getClass()); assertThat(expected.getClass()).isEqualTo(TestBean.class);
assertEquals("haha", expected.getName()); assertThat(expected.getName()).isEqualTo("haha");
assertSame(bean, beanFactory.getBean(BeanConsumer.class).abstractBean); assertThat(beanFactory.getBean(BeanConsumer.class).abstractBean).isSameAs(bean);
} }
@Test @Test
public void testWithTwoConstructorArg() { public void testWithTwoConstructorArg() {
AbstractBean bean = (AbstractBean) beanFactory.getBean("abstractBean"); AbstractBean bean = (AbstractBean) beanFactory.getBean("abstractBean");
assertNotNull(bean); assertThat(bean).isNotNull();
TestBean expected = bean.getTwoArguments("haha", 72); TestBean expected = bean.getTwoArguments("haha", 72);
assertEquals(TestBean.class, expected.getClass()); assertThat(expected.getClass()).isEqualTo(TestBean.class);
assertEquals("haha", expected.getName()); assertThat(expected.getName()).isEqualTo("haha");
assertEquals(72, expected.getAge()); assertThat(expected.getAge()).isEqualTo(72);
assertSame(bean, beanFactory.getBean(BeanConsumer.class).abstractBean); assertThat(beanFactory.getBean(BeanConsumer.class).abstractBean).isSameAs(bean);
} }
@Test @Test
public void testWithThreeArgsShouldFail() { public void testWithThreeArgsShouldFail() {
AbstractBean bean = (AbstractBean) beanFactory.getBean("abstractBean"); AbstractBean bean = (AbstractBean) beanFactory.getBean("abstractBean");
assertNotNull(bean); assertThat(bean).isNotNull();
assertThatExceptionOfType(AbstractMethodError.class).as("TestBean has no three arg constructor").isThrownBy(() -> assertThatExceptionOfType(AbstractMethodError.class).as("TestBean has no three arg constructor").isThrownBy(() ->
bean.getThreeArguments("name", 1, 2)); bean.getThreeArguments("name", 1, 2));
assertSame(bean, beanFactory.getBean(BeanConsumer.class).abstractBean); assertThat(beanFactory.getBean(BeanConsumer.class).abstractBean).isSameAs(bean);
} }
@Test @Test
public void testWithEarlyInjection() { public void testWithEarlyInjection() {
AbstractBean bean = beanFactory.getBean("beanConsumer", BeanConsumer.class).abstractBean; AbstractBean bean = beanFactory.getBean("beanConsumer", BeanConsumer.class).abstractBean;
assertNotNull(bean); assertThat(bean).isNotNull();
Object expected = bean.get(); Object expected = bean.get();
assertEquals(TestBean.class, expected.getClass()); assertThat(expected.getClass()).isEqualTo(TestBean.class);
assertSame(bean, beanFactory.getBean(BeanConsumer.class).abstractBean); assertThat(beanFactory.getBean(BeanConsumer.class).abstractBean).isSameAs(bean);
} }

View File

@ -27,10 +27,8 @@ import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
import org.springframework.beans.factory.config.DependencyDescriptor; import org.springframework.beans.factory.config.DependencyDescriptor;
import org.springframework.util.ClassUtils; import org.springframework.util.ClassUtils;
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.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.isNull; import static org.mockito.ArgumentMatchers.isNull;
import static org.mockito.BDDMockito.given; import static org.mockito.BDDMockito.given;
@ -67,7 +65,7 @@ public class ParameterResolutionTests {
@Test @Test
public void annotatedParametersInInnerClassConstructorAreCandidatesForAutowiring() throws Exception { public void annotatedParametersInInnerClassConstructorAreCandidatesForAutowiring() throws Exception {
Class<?> innerClass = AutowirableClass.InnerAutowirableClass.class; Class<?> innerClass = AutowirableClass.InnerAutowirableClass.class;
assertTrue(ClassUtils.isInnerClass(innerClass)); assertThat(ClassUtils.isInnerClass(innerClass)).isTrue();
Constructor<?> constructor = innerClass.getConstructor(AutowirableClass.class, String.class, String.class); Constructor<?> constructor = innerClass.getConstructor(AutowirableClass.class, String.class, String.class);
assertAutowirableParameters(constructor); assertAutowirableParameters(constructor);
} }
@ -78,8 +76,7 @@ public class ParameterResolutionTests {
Parameter[] parameters = executable.getParameters(); Parameter[] parameters = executable.getParameters();
for (int parameterIndex = startIndex; parameterIndex < parameters.length; parameterIndex++) { for (int parameterIndex = startIndex; parameterIndex < parameters.length; parameterIndex++) {
Parameter parameter = parameters[parameterIndex]; Parameter parameter = parameters[parameterIndex];
assertTrue("Parameter " + parameter + " must be autowirable", assertThat(ParameterResolutionDelegate.isAutowirable(parameter, parameterIndex)).as("Parameter " + parameter + " must be autowirable").isTrue();
ParameterResolutionDelegate.isAutowirable(parameter, parameterIndex));
} }
} }
@ -90,8 +87,7 @@ public class ParameterResolutionTests {
Parameter[] parameters = notAutowirableConstructor.getParameters(); Parameter[] parameters = notAutowirableConstructor.getParameters();
for (int parameterIndex = 0; parameterIndex < parameters.length; parameterIndex++) { for (int parameterIndex = 0; parameterIndex < parameters.length; parameterIndex++) {
Parameter parameter = parameters[parameterIndex]; Parameter parameter = parameters[parameterIndex];
assertFalse("Parameter " + parameter + " must not be autowirable", assertThat(ParameterResolutionDelegate.isAutowirable(parameter, parameterIndex)).as("Parameter " + parameter + " must not be autowirable").isFalse();
ParameterResolutionDelegate.isAutowirable(parameter, parameterIndex));
} }
} }
@ -135,8 +131,8 @@ public class ParameterResolutionTests {
Parameter parameter = parameters[parameterIndex]; Parameter parameter = parameters[parameterIndex];
DependencyDescriptor intermediateDependencyDescriptor = (DependencyDescriptor) ParameterResolutionDelegate.resolveDependency( DependencyDescriptor intermediateDependencyDescriptor = (DependencyDescriptor) ParameterResolutionDelegate.resolveDependency(
parameter, parameterIndex, AutowirableClass.class, beanFactory); parameter, parameterIndex, AutowirableClass.class, beanFactory);
assertEquals(constructor, intermediateDependencyDescriptor.getAnnotatedElement()); assertThat(intermediateDependencyDescriptor.getAnnotatedElement()).isEqualTo(constructor);
assertEquals(parameter, intermediateDependencyDescriptor.getMethodParameter().getParameter()); assertThat(intermediateDependencyDescriptor.getMethodParameter().getParameter()).isEqualTo(parameter);
} }
} }

View File

@ -32,8 +32,8 @@ import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.DefaultListableBeanFactory; import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.beans.factory.support.RootBeanDefinition; import org.springframework.beans.factory.support.RootBeanDefinition;
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.junit.Assert.assertEquals;
/** /**
* @author Rob Harrop * @author Rob Harrop
@ -92,8 +92,8 @@ public class RequiredAnnotationBeanPostProcessorTests {
factory.addBeanPostProcessor(new RequiredAnnotationBeanPostProcessor()); factory.addBeanPostProcessor(new RequiredAnnotationBeanPostProcessor());
factory.preInstantiateSingletons(); factory.preInstantiateSingletons();
RequiredTestBean bean = (RequiredTestBean) factory.getBean("testBean"); RequiredTestBean bean = (RequiredTestBean) factory.getBean("testBean");
assertEquals(24, bean.getAge()); assertThat(bean.getAge()).isEqualTo(24);
assertEquals("Blue", bean.getFavouriteColour()); assertThat(bean.getFavouriteColour()).isEqualTo("Blue");
} }
@Test @Test
@ -146,8 +146,8 @@ public class RequiredAnnotationBeanPostProcessorTests {
factory.addBeanPostProcessor(new RequiredAnnotationBeanPostProcessor()); factory.addBeanPostProcessor(new RequiredAnnotationBeanPostProcessor());
factory.preInstantiateSingletons(); factory.preInstantiateSingletons();
RequiredTestBean bean = (RequiredTestBean) factory.getBean("testBean"); RequiredTestBean bean = (RequiredTestBean) factory.getBean("testBean");
assertEquals(24, bean.getAge()); assertThat(bean.getAge()).isEqualTo(24);
assertEquals("Blue", bean.getFavouriteColour()); assertThat(bean.getFavouriteColour()).isEqualTo("Blue");
} }
@Test @Test

View File

@ -35,8 +35,7 @@ import org.springframework.beans.factory.support.RootBeanDefinition;
import org.springframework.beans.propertyeditors.CustomDateEditor; import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.tests.sample.beans.TestBean; import org.springframework.tests.sample.beans.TestBean;
import static org.junit.Assert.assertEquals; import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertTrue;
/** /**
* @author Juergen Hoeller * @author Juergen Hoeller
@ -71,9 +70,9 @@ public class CustomEditorConfigurerTests {
bf.registerBeanDefinition("tb2", bd2); bf.registerBeanDefinition("tb2", bd2);
TestBean tb1 = (TestBean) bf.getBean("tb1"); TestBean tb1 = (TestBean) bf.getBean("tb1");
assertEquals(df.parse("2.12.1975"), tb1.getDate()); assertThat(tb1.getDate()).isEqualTo(df.parse("2.12.1975"));
TestBean tb2 = (TestBean) bf.getBean("tb2"); TestBean tb2 = (TestBean) bf.getBean("tb2");
assertEquals(df.parse("2.12.1975"), tb2.getSomeMap().get("myKey")); assertThat(tb2.getSomeMap().get("myKey")).isEqualTo(df.parse("2.12.1975"));
} }
@Test @Test
@ -93,7 +92,7 @@ public class CustomEditorConfigurerTests {
TestBean tb = (TestBean) bf.getBean("tb"); TestBean tb = (TestBean) bf.getBean("tb");
DateFormat df = DateFormat.getDateInstance(DateFormat.SHORT, Locale.GERMAN); DateFormat df = DateFormat.getDateInstance(DateFormat.SHORT, Locale.GERMAN);
assertEquals(df.parse("2.12.1975"), tb.getDate()); assertThat(tb.getDate()).isEqualTo(df.parse("2.12.1975"));
} }
@Test @Test
@ -112,8 +111,8 @@ public class CustomEditorConfigurerTests {
bf.registerBeanDefinition("tb", bd); bf.registerBeanDefinition("tb", bd);
TestBean tb = (TestBean) bf.getBean("tb"); TestBean tb = (TestBean) bf.getBean("tb");
assertTrue(tb.getStringArray() != null && tb.getStringArray().length == 1); assertThat(tb.getStringArray() != null && tb.getStringArray().length == 1).isTrue();
assertEquals("test", tb.getStringArray()[0]); assertThat(tb.getStringArray()[0]).isEqualTo("test");
} }

View File

@ -23,9 +23,9 @@ import org.junit.Test;
import org.springframework.beans.factory.support.DefaultListableBeanFactory; import org.springframework.beans.factory.support.DefaultListableBeanFactory;
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.junit.Assert.assertTrue;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
/** /**
@ -66,7 +66,8 @@ public class CustomScopeConfigurerTests {
CustomScopeConfigurer figurer = new CustomScopeConfigurer(); CustomScopeConfigurer figurer = new CustomScopeConfigurer();
figurer.setScopes(scopes); figurer.setScopes(scopes);
figurer.postProcessBeanFactory(factory); figurer.postProcessBeanFactory(factory);
assertTrue(factory.getRegisteredScope(FOO_SCOPE) instanceof NoOpScope); boolean condition = factory.getRegisteredScope(FOO_SCOPE) instanceof NoOpScope;
assertThat(condition).isTrue();
} }
@Test @Test
@ -76,7 +77,8 @@ public class CustomScopeConfigurerTests {
CustomScopeConfigurer figurer = new CustomScopeConfigurer(); CustomScopeConfigurer figurer = new CustomScopeConfigurer();
figurer.setScopes(scopes); figurer.setScopes(scopes);
figurer.postProcessBeanFactory(factory); figurer.postProcessBeanFactory(factory);
assertTrue(factory.getRegisteredScope(FOO_SCOPE) instanceof NoOpScope); boolean condition = factory.getRegisteredScope(FOO_SCOPE) instanceof NoOpScope;
assertThat(condition).isTrue();
} }
@Test @Test

View File

@ -21,7 +21,7 @@ import org.junit.Test;
import org.springframework.beans.factory.support.DefaultListableBeanFactory; import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.beans.factory.support.RootBeanDefinition; import org.springframework.beans.factory.support.RootBeanDefinition;
import static org.junit.Assert.assertEquals; import static org.assertj.core.api.Assertions.assertThat;
/** /**
* @author Arjen Poutsma * @author Arjen Poutsma
@ -43,8 +43,8 @@ public class DeprecatedBeanWarnerTests {
DeprecatedBeanWarner warner = new MyDeprecatedBeanWarner(); DeprecatedBeanWarner warner = new MyDeprecatedBeanWarner();
warner.postProcessBeanFactory(beanFactory); warner.postProcessBeanFactory(beanFactory);
assertEquals(beanName, this.beanName); assertThat(this.beanName).isEqualTo(beanName);
assertEquals(def, this.beanDefinition); assertThat(this.beanDefinition).isEqualTo(def);
} }

View File

@ -24,7 +24,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.tests.sample.beans.TestBean; import org.springframework.tests.sample.beans.TestBean;
import static org.junit.Assert.assertEquals; import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.tests.TestResourceUtils.qualifiedResource; import static org.springframework.tests.TestResourceUtils.qualifiedResource;
/** /**
@ -41,7 +41,7 @@ public class FieldRetrievingFactoryBeanTests {
FieldRetrievingFactoryBean fr = new FieldRetrievingFactoryBean(); FieldRetrievingFactoryBean fr = new FieldRetrievingFactoryBean();
fr.setStaticField("java.sql.Connection.TRANSACTION_SERIALIZABLE"); fr.setStaticField("java.sql.Connection.TRANSACTION_SERIALIZABLE");
fr.afterPropertiesSet(); fr.afterPropertiesSet();
assertEquals(new Integer(Connection.TRANSACTION_SERIALIZABLE), fr.getObject()); assertThat(fr.getObject()).isEqualTo(new Integer(Connection.TRANSACTION_SERIALIZABLE));
} }
@Test @Test
@ -49,7 +49,7 @@ public class FieldRetrievingFactoryBeanTests {
FieldRetrievingFactoryBean fr = new FieldRetrievingFactoryBean(); FieldRetrievingFactoryBean fr = new FieldRetrievingFactoryBean();
fr.setStaticField(" java.sql.Connection.TRANSACTION_SERIALIZABLE "); fr.setStaticField(" java.sql.Connection.TRANSACTION_SERIALIZABLE ");
fr.afterPropertiesSet(); fr.afterPropertiesSet();
assertEquals(new Integer(Connection.TRANSACTION_SERIALIZABLE), fr.getObject()); assertThat(fr.getObject()).isEqualTo(new Integer(Connection.TRANSACTION_SERIALIZABLE));
} }
@Test @Test
@ -58,7 +58,7 @@ public class FieldRetrievingFactoryBeanTests {
fr.setTargetClass(Connection.class); fr.setTargetClass(Connection.class);
fr.setTargetField("TRANSACTION_SERIALIZABLE"); fr.setTargetField("TRANSACTION_SERIALIZABLE");
fr.afterPropertiesSet(); fr.afterPropertiesSet();
assertEquals(new Integer(Connection.TRANSACTION_SERIALIZABLE), fr.getObject()); assertThat(fr.getObject()).isEqualTo(new Integer(Connection.TRANSACTION_SERIALIZABLE));
} }
@Test @Test
@ -68,7 +68,7 @@ public class FieldRetrievingFactoryBeanTests {
fr.setTargetObject(target); fr.setTargetObject(target);
fr.setTargetField("publicField"); fr.setTargetField("publicField");
fr.afterPropertiesSet(); fr.afterPropertiesSet();
assertEquals(target.publicField, fr.getObject()); assertThat(fr.getObject()).isEqualTo(target.publicField);
} }
@Test @Test
@ -76,7 +76,7 @@ public class FieldRetrievingFactoryBeanTests {
FieldRetrievingFactoryBean fr = new FieldRetrievingFactoryBean(); FieldRetrievingFactoryBean fr = new FieldRetrievingFactoryBean();
fr.setBeanName("java.sql.Connection.TRANSACTION_SERIALIZABLE"); fr.setBeanName("java.sql.Connection.TRANSACTION_SERIALIZABLE");
fr.afterPropertiesSet(); fr.afterPropertiesSet();
assertEquals(new Integer(Connection.TRANSACTION_SERIALIZABLE), fr.getObject()); assertThat(fr.getObject()).isEqualTo(new Integer(Connection.TRANSACTION_SERIALIZABLE));
} }
@Test @Test
@ -117,7 +117,7 @@ public class FieldRetrievingFactoryBeanTests {
FieldRetrievingFactoryBean fr = new FieldRetrievingFactoryBean(); FieldRetrievingFactoryBean fr = new FieldRetrievingFactoryBean();
fr.setBeanName("org.springframework.tests.sample.beans.PackageLevelVisibleBean.CONSTANT"); fr.setBeanName("org.springframework.tests.sample.beans.PackageLevelVisibleBean.CONSTANT");
fr.afterPropertiesSet(); fr.afterPropertiesSet();
assertEquals("Wuby", fr.getObject()); assertThat(fr.getObject()).isEqualTo("Wuby");
} }
@Test @Test
@ -127,8 +127,8 @@ public class FieldRetrievingFactoryBeanTests {
qualifiedResource(FieldRetrievingFactoryBeanTests.class, "context.xml")); qualifiedResource(FieldRetrievingFactoryBeanTests.class, "context.xml"));
TestBean testBean = (TestBean) bf.getBean("testBean"); TestBean testBean = (TestBean) bf.getBean("testBean");
assertEquals(new Integer(Connection.TRANSACTION_SERIALIZABLE), testBean.getSomeIntegerArray()[0]); assertThat(testBean.getSomeIntegerArray()[0]).isEqualTo(new Integer(Connection.TRANSACTION_SERIALIZABLE));
assertEquals(new Integer(Connection.TRANSACTION_SERIALIZABLE), testBean.getSomeIntegerArray()[1]); assertThat(testBean.getSomeIntegerArray()[1]).isEqualTo(new Integer(Connection.TRANSACTION_SERIALIZABLE));
} }

View File

@ -26,12 +26,9 @@ import org.springframework.beans.propertyeditors.StringTrimmerEditor;
import org.springframework.beans.support.ArgumentConvertingMethodInvoker; import org.springframework.beans.support.ArgumentConvertingMethodInvoker;
import org.springframework.util.MethodInvoker; import org.springframework.util.MethodInvoker;
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.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
/** /**
* Unit tests for {@link MethodInvokingFactoryBean} and {@link MethodInvokingBean}. * Unit tests for {@link MethodInvokingFactoryBean} and {@link MethodInvokingBean}.
@ -45,7 +42,6 @@ public class MethodInvokingFactoryBeanTests {
@Test @Test
public void testParameterValidation() throws Exception { public void testParameterValidation() throws Exception {
String validationError = "improper validation of input properties";
// assert that only static OR non static are set, but not both or none // assert that only static OR non static are set, but not both or none
MethodInvokingFactoryBean mcfb = new MethodInvokingFactoryBean(); MethodInvokingFactoryBean mcfb = new MethodInvokingFactoryBean();
@ -102,14 +98,14 @@ public class MethodInvokingFactoryBeanTests {
mcfb.setTargetObject(tc1); mcfb.setTargetObject(tc1);
mcfb.setTargetMethod("method1"); mcfb.setTargetMethod("method1");
mcfb.afterPropertiesSet(); mcfb.afterPropertiesSet();
assertTrue(int.class.equals(mcfb.getObjectType())); assertThat(int.class.equals(mcfb.getObjectType())).isTrue();
mcfb = new MethodInvokingFactoryBean(); mcfb = new MethodInvokingFactoryBean();
mcfb.setTargetClass(TestClass1.class); mcfb.setTargetClass(TestClass1.class);
mcfb.setTargetMethod("voidRetvalMethod"); mcfb.setTargetMethod("voidRetvalMethod");
mcfb.afterPropertiesSet(); mcfb.afterPropertiesSet();
Class<?> objType = mcfb.getObjectType(); Class<?> objType = mcfb.getObjectType();
assertSame(objType, void.class); assertThat(void.class).isSameAs(objType);
// verify that we can call a method with args that are subtypes of the // verify that we can call a method with args that are subtypes of the
// target method arg types // target method arg types
@ -139,9 +135,9 @@ public class MethodInvokingFactoryBeanTests {
mcfb.setTargetMethod("method1"); mcfb.setTargetMethod("method1");
mcfb.afterPropertiesSet(); mcfb.afterPropertiesSet();
Integer i = (Integer) mcfb.getObject(); Integer i = (Integer) mcfb.getObject();
assertEquals(1, i.intValue()); assertThat(i.intValue()).isEqualTo(1);
i = (Integer) mcfb.getObject(); i = (Integer) mcfb.getObject();
assertEquals(1, i.intValue()); assertThat(i.intValue()).isEqualTo(1);
// non-singleton, non-static // non-singleton, non-static
tc1 = new TestClass1(); tc1 = new TestClass1();
@ -151,9 +147,9 @@ public class MethodInvokingFactoryBeanTests {
mcfb.setSingleton(false); mcfb.setSingleton(false);
mcfb.afterPropertiesSet(); mcfb.afterPropertiesSet();
i = (Integer) mcfb.getObject(); i = (Integer) mcfb.getObject();
assertEquals(1, i.intValue()); assertThat(i.intValue()).isEqualTo(1);
i = (Integer) mcfb.getObject(); i = (Integer) mcfb.getObject();
assertEquals(2, i.intValue()); assertThat(i.intValue()).isEqualTo(2);
// singleton, static // singleton, static
TestClass1._staticField1 = 0; TestClass1._staticField1 = 0;
@ -162,9 +158,9 @@ public class MethodInvokingFactoryBeanTests {
mcfb.setTargetMethod("staticMethod1"); mcfb.setTargetMethod("staticMethod1");
mcfb.afterPropertiesSet(); mcfb.afterPropertiesSet();
i = (Integer) mcfb.getObject(); i = (Integer) mcfb.getObject();
assertEquals(1, i.intValue()); assertThat(i.intValue()).isEqualTo(1);
i = (Integer) mcfb.getObject(); i = (Integer) mcfb.getObject();
assertEquals(1, i.intValue()); assertThat(i.intValue()).isEqualTo(1);
// non-singleton, static // non-singleton, static
TestClass1._staticField1 = 0; TestClass1._staticField1 = 0;
@ -173,16 +169,16 @@ public class MethodInvokingFactoryBeanTests {
mcfb.setSingleton(false); mcfb.setSingleton(false);
mcfb.afterPropertiesSet(); mcfb.afterPropertiesSet();
i = (Integer) mcfb.getObject(); i = (Integer) mcfb.getObject();
assertEquals(1, i.intValue()); assertThat(i.intValue()).isEqualTo(1);
i = (Integer) mcfb.getObject(); i = (Integer) mcfb.getObject();
assertEquals(2, i.intValue()); assertThat(i.intValue()).isEqualTo(2);
// void return value // void return value
mcfb = new MethodInvokingFactoryBean(); mcfb = new MethodInvokingFactoryBean();
mcfb.setTargetClass(TestClass1.class); mcfb.setTargetClass(TestClass1.class);
mcfb.setTargetMethod("voidRetvalMethod"); mcfb.setTargetMethod("voidRetvalMethod");
mcfb.afterPropertiesSet(); mcfb.afterPropertiesSet();
assertNull(mcfb.getObject()); assertThat(mcfb.getObject()).isNull();
// now see if we can match methods with arguments that have supertype arguments // now see if we can match methods with arguments that have supertype arguments
mcfb = new MethodInvokingFactoryBean(); mcfb = new MethodInvokingFactoryBean();
@ -216,7 +212,7 @@ public class MethodInvokingFactoryBeanTests {
mcfb.setTargetMethod("supertypes2"); mcfb.setTargetMethod("supertypes2");
mcfb.setArguments(new ArrayList<>(), new ArrayList<Object>(), "hello", "bogus"); mcfb.setArguments(new ArrayList<>(), new ArrayList<Object>(), "hello", "bogus");
mcfb.afterPropertiesSet(); mcfb.afterPropertiesSet();
assertEquals("hello", mcfb.getObject()); assertThat(mcfb.getObject()).isEqualTo("hello");
mcfb = new MethodInvokingFactoryBean(); mcfb = new MethodInvokingFactoryBean();
mcfb.setTargetClass(TestClass1.class); mcfb.setTargetClass(TestClass1.class);

View File

@ -29,10 +29,8 @@ import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.beans.factory.xml.XmlBeanDefinitionReader; import org.springframework.beans.factory.xml.XmlBeanDefinitionReader;
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.junit.Assert.assertEquals;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import static org.mockito.BDDMockito.given; import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
import static org.springframework.tests.TestResourceUtils.qualifiedResource; import static org.springframework.tests.TestResourceUtils.qualifiedResource;
@ -69,7 +67,7 @@ public class ObjectFactoryCreatingFactoryBeanTests {
Date date1 = (Date) objectFactory.getObject(); Date date1 = (Date) objectFactory.getObject();
Date date2 = (Date) objectFactory.getObject(); Date date2 = (Date) objectFactory.getObject();
assertTrue(date1 != date2); assertThat(date1 != date2).isTrue();
} }
@Test @Test
@ -82,7 +80,7 @@ public class ObjectFactoryCreatingFactoryBeanTests {
Date date1 = (Date) objectFactory.getObject(); Date date1 = (Date) objectFactory.getObject();
Date date2 = (Date) objectFactory.getObject(); Date date2 = (Date) objectFactory.getObject();
assertTrue(date1 != date2); assertThat(date1 != date2).isTrue();
} }
@Test @Test
@ -92,7 +90,7 @@ public class ObjectFactoryCreatingFactoryBeanTests {
Date date1 = (Date) provider.get(); Date date1 = (Date) provider.get();
Date date2 = (Date) provider.get(); Date date2 = (Date) provider.get();
assertTrue(date1 != date2); assertThat(date1 != date2).isTrue();
} }
@Test @Test
@ -105,7 +103,7 @@ public class ObjectFactoryCreatingFactoryBeanTests {
Date date1 = (Date) provider.get(); Date date1 = (Date) provider.get();
Date date2 = (Date) provider.get(); Date date2 = (Date) provider.get();
assertTrue(date1 != date2); assertThat(date1 != date2).isTrue();
} }
@Test @Test
@ -122,7 +120,7 @@ public class ObjectFactoryCreatingFactoryBeanTests {
factory.afterPropertiesSet(); factory.afterPropertiesSet();
ObjectFactory<?> objectFactory = factory.getObject(); ObjectFactory<?> objectFactory = factory.getObject();
Object actualSingleton = objectFactory.getObject(); Object actualSingleton = objectFactory.getObject();
assertSame(expectedSingleton, actualSingleton); assertThat(actualSingleton).isSameAs(expectedSingleton);
} }
@Test @Test
@ -152,8 +150,7 @@ public class ObjectFactoryCreatingFactoryBeanTests {
@Test @Test
public void testEnsureOFBFBReportsThatItActuallyCreatesObjectFactoryInstances() { public void testEnsureOFBFBReportsThatItActuallyCreatesObjectFactoryInstances() {
assertEquals("Must be reporting that it creates ObjectFactory instances (as per class contract).", assertThat(new ObjectFactoryCreatingFactoryBean().getObjectType()).as("Must be reporting that it creates ObjectFactory instances (as per class contract).").isEqualTo(ObjectFactory.class);
ObjectFactory.class, new ObjectFactoryCreatingFactoryBean().getObjectType());
} }

View File

@ -22,8 +22,7 @@ import org.junit.Test;
import org.springframework.core.io.Resource; import org.springframework.core.io.Resource;
import static org.junit.Assert.assertEquals; import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertTrue;
import static org.springframework.tests.TestResourceUtils.qualifiedResource; import static org.springframework.tests.TestResourceUtils.qualifiedResource;
/** /**
@ -45,7 +44,7 @@ public class PropertiesFactoryBeanTests {
pfb.setLocation(TEST_PROPS); pfb.setLocation(TEST_PROPS);
pfb.afterPropertiesSet(); pfb.afterPropertiesSet();
Properties props = pfb.getObject(); Properties props = pfb.getObject();
assertEquals("99", props.getProperty("tb.array[0].age")); assertThat(props.getProperty("tb.array[0].age")).isEqualTo("99");
} }
@Test @Test
@ -54,7 +53,7 @@ public class PropertiesFactoryBeanTests {
pfb.setLocation(TEST_PROPS_XML); pfb.setLocation(TEST_PROPS_XML);
pfb.afterPropertiesSet(); pfb.afterPropertiesSet();
Properties props = pfb.getObject(); Properties props = pfb.getObject();
assertEquals("99", props.getProperty("tb.array[0].age")); assertThat(props.getProperty("tb.array[0].age")).isEqualTo("99");
} }
@Test @Test
@ -65,7 +64,7 @@ public class PropertiesFactoryBeanTests {
pfb.setProperties(localProps); pfb.setProperties(localProps);
pfb.afterPropertiesSet(); pfb.afterPropertiesSet();
Properties props = pfb.getObject(); Properties props = pfb.getObject();
assertEquals("value2", props.getProperty("key2")); assertThat(props.getProperty("key2")).isEqualTo("value2");
} }
@Test @Test
@ -78,8 +77,8 @@ public class PropertiesFactoryBeanTests {
pfb.setProperties(localProps); pfb.setProperties(localProps);
pfb.afterPropertiesSet(); pfb.afterPropertiesSet();
Properties props = pfb.getObject(); Properties props = pfb.getObject();
assertEquals("99", props.getProperty("tb.array[0].age")); assertThat(props.getProperty("tb.array[0].age")).isEqualTo("99");
assertEquals("value2", props.getProperty("key2")); assertThat(props.getProperty("key2")).isEqualTo("value2");
} }
@Test @Test
@ -103,12 +102,12 @@ public class PropertiesFactoryBeanTests {
pfb.afterPropertiesSet(); pfb.afterPropertiesSet();
Properties props = pfb.getObject(); Properties props = pfb.getObject();
assertEquals("99", props.getProperty("tb.array[0].age")); assertThat(props.getProperty("tb.array[0].age")).isEqualTo("99");
assertEquals("value2", props.getProperty("key2")); assertThat(props.getProperty("key2")).isEqualTo("value2");
assertEquals("framework", props.getProperty("spring")); assertThat(props.getProperty("spring")).isEqualTo("framework");
assertEquals("Mattingly", props.getProperty("Don")); assertThat(props.getProperty("Don")).isEqualTo("Mattingly");
assertEquals("man", props.getProperty("spider")); assertThat(props.getProperty("spider")).isEqualTo("man");
assertEquals("man", props.getProperty("bat")); assertThat(props.getProperty("bat")).isEqualTo("man");
} }
@Test @Test
@ -122,8 +121,8 @@ public class PropertiesFactoryBeanTests {
pfb.setLocalOverride(true); pfb.setLocalOverride(true);
pfb.afterPropertiesSet(); pfb.afterPropertiesSet();
Properties props = pfb.getObject(); Properties props = pfb.getObject();
assertEquals("0", props.getProperty("tb.array[0].age")); assertThat(props.getProperty("tb.array[0].age")).isEqualTo("0");
assertEquals("value2", props.getProperty("key2")); assertThat(props.getProperty("key2")).isEqualTo("value2");
} }
@Test @Test
@ -136,12 +135,12 @@ public class PropertiesFactoryBeanTests {
pfb.setProperties(localProps); pfb.setProperties(localProps);
pfb.afterPropertiesSet(); pfb.afterPropertiesSet();
Properties props = pfb.getObject(); Properties props = pfb.getObject();
assertEquals("99", props.getProperty("tb.array[0].age")); assertThat(props.getProperty("tb.array[0].age")).isEqualTo("99");
assertEquals("value2", props.getProperty("key2")); assertThat(props.getProperty("key2")).isEqualTo("value2");
Properties newProps = pfb.getObject(); Properties newProps = pfb.getObject();
assertTrue(props != newProps); assertThat(props != newProps).isTrue();
assertEquals("99", newProps.getProperty("tb.array[0].age")); assertThat(newProps.getProperty("tb.array[0].age")).isEqualTo("99");
assertEquals("value2", newProps.getProperty("key2")); assertThat(newProps.getProperty("key2")).isEqualTo("value2");
} }
} }

View File

@ -24,10 +24,7 @@ import org.springframework.core.io.Resource;
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.junit.Assert.assertEquals; import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import static org.springframework.tests.TestResourceUtils.qualifiedResource; import static org.springframework.tests.TestResourceUtils.qualifiedResource;
/** /**
@ -46,43 +43,47 @@ public class PropertyPathFactoryBeanTests {
public void testPropertyPathFactoryBeanWithSingletonResult() { public void testPropertyPathFactoryBeanWithSingletonResult() {
DefaultListableBeanFactory xbf = new DefaultListableBeanFactory(); DefaultListableBeanFactory xbf = new DefaultListableBeanFactory();
new XmlBeanDefinitionReader(xbf).loadBeanDefinitions(CONTEXT); new XmlBeanDefinitionReader(xbf).loadBeanDefinitions(CONTEXT);
assertEquals(new Integer(12), xbf.getBean("propertyPath1")); assertThat(xbf.getBean("propertyPath1")).isEqualTo(new Integer(12));
assertEquals(new Integer(11), xbf.getBean("propertyPath2")); assertThat(xbf.getBean("propertyPath2")).isEqualTo(new Integer(11));
assertEquals(new Integer(10), xbf.getBean("tb.age")); assertThat(xbf.getBean("tb.age")).isEqualTo(new Integer(10));
assertEquals(ITestBean.class, xbf.getType("otb.spouse")); assertThat(xbf.getType("otb.spouse")).isEqualTo(ITestBean.class);
Object result1 = xbf.getBean("otb.spouse"); Object result1 = xbf.getBean("otb.spouse");
Object result2 = xbf.getBean("otb.spouse"); Object result2 = xbf.getBean("otb.spouse");
assertTrue(result1 instanceof TestBean); boolean condition = result1 instanceof TestBean;
assertTrue(result1 == result2); assertThat(condition).isTrue();
assertEquals(99, ((TestBean) result1).getAge()); assertThat(result1 == result2).isTrue();
assertThat(((TestBean) result1).getAge()).isEqualTo(99);
} }
@Test @Test
public void testPropertyPathFactoryBeanWithPrototypeResult() { public void testPropertyPathFactoryBeanWithPrototypeResult() {
DefaultListableBeanFactory xbf = new DefaultListableBeanFactory(); DefaultListableBeanFactory xbf = new DefaultListableBeanFactory();
new XmlBeanDefinitionReader(xbf).loadBeanDefinitions(CONTEXT); new XmlBeanDefinitionReader(xbf).loadBeanDefinitions(CONTEXT);
assertNull(xbf.getType("tb.spouse")); assertThat(xbf.getType("tb.spouse")).isNull();
assertEquals(TestBean.class, xbf.getType("propertyPath3")); assertThat(xbf.getType("propertyPath3")).isEqualTo(TestBean.class);
Object result1 = xbf.getBean("tb.spouse"); Object result1 = xbf.getBean("tb.spouse");
Object result2 = xbf.getBean("propertyPath3"); Object result2 = xbf.getBean("propertyPath3");
Object result3 = xbf.getBean("propertyPath3"); Object result3 = xbf.getBean("propertyPath3");
assertTrue(result1 instanceof TestBean); boolean condition2 = result1 instanceof TestBean;
assertTrue(result2 instanceof TestBean); assertThat(condition2).isTrue();
assertTrue(result3 instanceof TestBean); boolean condition1 = result2 instanceof TestBean;
assertEquals(11, ((TestBean) result1).getAge()); assertThat(condition1).isTrue();
assertEquals(11, ((TestBean) result2).getAge()); boolean condition = result3 instanceof TestBean;
assertEquals(11, ((TestBean) result3).getAge()); assertThat(condition).isTrue();
assertTrue(result1 != result2); assertThat(((TestBean) result1).getAge()).isEqualTo(11);
assertTrue(result1 != result3); assertThat(((TestBean) result2).getAge()).isEqualTo(11);
assertTrue(result2 != result3); assertThat(((TestBean) result3).getAge()).isEqualTo(11);
assertThat(result1 != result2).isTrue();
assertThat(result1 != result3).isTrue();
assertThat(result2 != result3).isTrue();
} }
@Test @Test
public void testPropertyPathFactoryBeanWithNullResult() { public void testPropertyPathFactoryBeanWithNullResult() {
DefaultListableBeanFactory xbf = new DefaultListableBeanFactory(); DefaultListableBeanFactory xbf = new DefaultListableBeanFactory();
new XmlBeanDefinitionReader(xbf).loadBeanDefinitions(CONTEXT); new XmlBeanDefinitionReader(xbf).loadBeanDefinitions(CONTEXT);
assertNull(xbf.getType("tb.spouse.spouse")); assertThat(xbf.getType("tb.spouse.spouse")).isNull();
assertEquals("null", xbf.getBean("tb.spouse.spouse").toString()); assertThat(xbf.getBean("tb.spouse.spouse").toString()).isEqualTo("null");
} }
@Test @Test
@ -91,23 +92,24 @@ public class PropertyPathFactoryBeanTests {
new XmlBeanDefinitionReader(xbf).loadBeanDefinitions(CONTEXT); new XmlBeanDefinitionReader(xbf).loadBeanDefinitions(CONTEXT);
TestBean spouse = (TestBean) xbf.getBean("otb.spouse"); TestBean spouse = (TestBean) xbf.getBean("otb.spouse");
TestBean tbWithInner = (TestBean) xbf.getBean("tbWithInner"); TestBean tbWithInner = (TestBean) xbf.getBean("tbWithInner");
assertSame(spouse, tbWithInner.getSpouse()); assertThat(tbWithInner.getSpouse()).isSameAs(spouse);
assertTrue(!tbWithInner.getFriends().isEmpty()); boolean condition = !tbWithInner.getFriends().isEmpty();
assertSame(spouse, tbWithInner.getFriends().iterator().next()); assertThat(condition).isTrue();
assertThat(tbWithInner.getFriends().iterator().next()).isSameAs(spouse);
} }
@Test @Test
public void testPropertyPathFactoryBeanAsNullReference() { public void testPropertyPathFactoryBeanAsNullReference() {
DefaultListableBeanFactory xbf = new DefaultListableBeanFactory(); DefaultListableBeanFactory xbf = new DefaultListableBeanFactory();
new XmlBeanDefinitionReader(xbf).loadBeanDefinitions(CONTEXT); new XmlBeanDefinitionReader(xbf).loadBeanDefinitions(CONTEXT);
assertNull(xbf.getBean("tbWithNullReference", TestBean.class).getSpouse()); assertThat(xbf.getBean("tbWithNullReference", TestBean.class).getSpouse()).isNull();
} }
@Test @Test
public void testPropertyPathFactoryBeanAsInnerNull() { public void testPropertyPathFactoryBeanAsInnerNull() {
DefaultListableBeanFactory xbf = new DefaultListableBeanFactory(); DefaultListableBeanFactory xbf = new DefaultListableBeanFactory();
new XmlBeanDefinitionReader(xbf).loadBeanDefinitions(CONTEXT); new XmlBeanDefinitionReader(xbf).loadBeanDefinitions(CONTEXT);
assertNull(xbf.getBean("tbWithInnerNull", TestBean.class).getSpouse()); assertThat(xbf.getBean("tbWithInnerNull", TestBean.class).getSpouse()).isNull();
} }
} }

View File

@ -44,12 +44,8 @@ import org.springframework.tests.sample.beans.IndexedTestBean;
import org.springframework.tests.sample.beans.TestBean; import org.springframework.tests.sample.beans.TestBean;
import org.springframework.util.StringUtils; import org.springframework.util.StringUtils;
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.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import static org.springframework.beans.factory.support.BeanDefinitionBuilder.genericBeanDefinition; import static org.springframework.beans.factory.support.BeanDefinitionBuilder.genericBeanDefinition;
import static org.springframework.tests.TestResourceUtils.qualifiedResource; import static org.springframework.tests.TestResourceUtils.qualifiedResource;
@ -113,10 +109,10 @@ public class PropertyResourceConfigurerTests {
TestBean tb1 = (TestBean) factory.getBean("tb1"); TestBean tb1 = (TestBean) factory.getBean("tb1");
TestBean tb2 = (TestBean) factory.getBean("tb2"); TestBean tb2 = (TestBean) factory.getBean("tb2");
assertEquals(99, tb1.getAge()); assertThat(tb1.getAge()).isEqualTo(99);
assertEquals(99, tb2.getAge()); assertThat(tb2.getAge()).isEqualTo(99);
assertEquals(null, tb1.getName()); assertThat(tb1.getName()).isEqualTo(null);
assertEquals("test", tb2.getName()); assertThat(tb2.getName()).isEqualTo("test");
} }
@Test @Test
@ -133,8 +129,8 @@ public class PropertyResourceConfigurerTests {
poc.postProcessBeanFactory(factory); poc.postProcessBeanFactory(factory);
IndexedTestBean tb = (IndexedTestBean) factory.getBean("tb"); IndexedTestBean tb = (IndexedTestBean) factory.getBean("tb");
assertEquals(99, tb.getArray()[0].getAge()); assertThat(tb.getArray()[0].getAge()).isEqualTo(99);
assertEquals("test", ((TestBean) tb.getList().get(1)).getName()); assertThat(((TestBean) tb.getList().get(1)).getName()).isEqualTo("test");
} }
@Test @Test
@ -152,8 +148,8 @@ public class PropertyResourceConfigurerTests {
poc.postProcessBeanFactory(factory); poc.postProcessBeanFactory(factory);
IndexedTestBean tb = (IndexedTestBean) factory.getBean("my.tb"); IndexedTestBean tb = (IndexedTestBean) factory.getBean("my.tb");
assertEquals(99, tb.getArray()[0].getAge()); assertThat(tb.getArray()[0].getAge()).isEqualTo(99);
assertEquals("test", ((TestBean) tb.getList().get(1)).getName()); assertThat(((TestBean) tb.getList().get(1)).getName()).isEqualTo("test");
} }
@Test @Test
@ -170,8 +166,8 @@ public class PropertyResourceConfigurerTests {
poc.postProcessBeanFactory(factory); poc.postProcessBeanFactory(factory);
IndexedTestBean tb = (IndexedTestBean) factory.getBean("tb"); IndexedTestBean tb = (IndexedTestBean) factory.getBean("tb");
assertEquals("99", tb.getMap().get("key1")); assertThat(tb.getMap().get("key1")).isEqualTo("99");
assertEquals("test", tb.getMap().get("key2.ext")); assertThat(tb.getMap().get("key2.ext")).isEqualTo("test");
} }
@Test @Test
@ -187,7 +183,7 @@ public class PropertyResourceConfigurerTests {
poc.postProcessBeanFactory(factory); poc.postProcessBeanFactory(factory);
PropertiesHolder tb = (PropertiesHolder) factory.getBean("tb"); PropertiesHolder tb = (PropertiesHolder) factory.getBean("tb");
assertEquals("true", tb.getHeldProperties().getProperty("mail.smtp.auth")); assertThat(tb.getHeldProperties().getProperty("mail.smtp.auth")).isEqualTo("true");
} }
@Test @Test
@ -200,8 +196,8 @@ public class PropertyResourceConfigurerTests {
poc.postProcessBeanFactory(factory); poc.postProcessBeanFactory(factory);
IndexedTestBean tb = (IndexedTestBean) factory.getBean("tb"); IndexedTestBean tb = (IndexedTestBean) factory.getBean("tb");
assertEquals(99, tb.getArray()[0].getAge()); assertThat(tb.getArray()[0].getAge()).isEqualTo(99);
assertEquals("test", ((TestBean) tb.getList().get(1)).getName()); assertThat(((TestBean) tb.getList().get(1)).getName()).isEqualTo("test");
} }
@Test @Test
@ -215,8 +211,8 @@ public class PropertyResourceConfigurerTests {
poc.postProcessBeanFactory(factory); poc.postProcessBeanFactory(factory);
IndexedTestBean tb = (IndexedTestBean) factory.getBean("tb"); IndexedTestBean tb = (IndexedTestBean) factory.getBean("tb");
assertEquals(99, tb.getArray()[0].getAge()); assertThat(tb.getArray()[0].getAge()).isEqualTo(99);
assertEquals("test", ((TestBean) tb.getList().get(1)).getName()); assertThat(((TestBean) tb.getList().get(1)).getName()).isEqualTo("test");
} }
@Test @Test
@ -229,8 +225,8 @@ public class PropertyResourceConfigurerTests {
poc.postProcessBeanFactory(factory); poc.postProcessBeanFactory(factory);
IndexedTestBean tb = (IndexedTestBean) factory.getBean("tb"); IndexedTestBean tb = (IndexedTestBean) factory.getBean("tb");
assertEquals(99, tb.getArray()[0].getAge()); assertThat(tb.getArray()[0].getAge()).isEqualTo(99);
assertEquals("test", ((TestBean) tb.getList().get(1)).getName()); assertThat(((TestBean) tb.getList().get(1)).getName()).isEqualTo("test");
} }
@Test @Test
@ -246,8 +242,8 @@ public class PropertyResourceConfigurerTests {
bfpp.postProcessBeanFactory(factory); bfpp.postProcessBeanFactory(factory);
IndexedTestBean tb = (IndexedTestBean) factory.getBean("tb"); IndexedTestBean tb = (IndexedTestBean) factory.getBean("tb");
assertEquals("X99", tb.getArray()[0].getName()); assertThat(tb.getArray()[0].getName()).isEqualTo("X99");
assertEquals("Xtest", ((TestBean) tb.getList().get(1)).getName()); assertThat(((TestBean) tb.getList().get(1)).getName()).isEqualTo("Xtest");
} }
@Test @Test
@ -265,7 +261,7 @@ public class PropertyResourceConfigurerTests {
props.setProperty("tb3.name", "test"); props.setProperty("tb3.name", "test");
poc.setProperties(props); poc.setProperties(props);
poc.postProcessBeanFactory(factory); poc.postProcessBeanFactory(factory);
assertEquals("test", factory.getBean("tb2", TestBean.class).getName()); assertThat(factory.getBean("tb2", TestBean.class).getName()).isEqualTo("test");
} }
{ {
PropertyOverrideConfigurer poc = new PropertyOverrideConfigurer(); PropertyOverrideConfigurer poc = new PropertyOverrideConfigurer();
@ -280,7 +276,7 @@ public class PropertyResourceConfigurerTests {
} }
catch (BeanInitializationException ex) { catch (BeanInitializationException ex) {
// prove that the processor chokes on the invalid key // prove that the processor chokes on the invalid key
assertTrue(ex.getMessage().toLowerCase().contains("argh")); assertThat(ex.getMessage().toLowerCase().contains("argh")).isTrue();
} }
} }
} }
@ -312,10 +308,10 @@ public class PropertyResourceConfigurerTests {
TestBean tb1 = (TestBean) factory.getBean("tb1"); TestBean tb1 = (TestBean) factory.getBean("tb1");
TestBean tb2 = (TestBean) factory.getBean("tb2"); TestBean tb2 = (TestBean) factory.getBean("tb2");
assertEquals(99, tb1.getAge()); assertThat(tb1.getAge()).isEqualTo(99);
assertEquals(99, tb2.getAge()); assertThat(tb2.getAge()).isEqualTo(99);
assertEquals(null, tb1.getName()); assertThat(tb1.getName()).isEqualTo(null);
assertEquals("test", tb2.getName()); assertThat(tb2.getName()).isEqualTo("test");
} }
@Test @Test
@ -402,36 +398,36 @@ public class PropertyResourceConfigurerTests {
TestBean tb1 = (TestBean) factory.getBean("tb1"); TestBean tb1 = (TestBean) factory.getBean("tb1");
TestBean tb2 = (TestBean) factory.getBean("tb2"); TestBean tb2 = (TestBean) factory.getBean("tb2");
assertEquals(98, tb1.getAge()); assertThat(tb1.getAge()).isEqualTo(98);
assertEquals(98, tb2.getAge()); assertThat(tb2.getAge()).isEqualTo(98);
assertEquals("namemyvarmyvar${", tb1.getName()); assertThat(tb1.getName()).isEqualTo("namemyvarmyvar${");
assertEquals("myvarname98", tb2.getName()); assertThat(tb2.getName()).isEqualTo("myvarname98");
assertEquals(tb2, tb1.getSpouse()); assertThat(tb1.getSpouse()).isEqualTo(tb2);
assertEquals(1, tb1.getSomeMap().size()); assertThat(tb1.getSomeMap().size()).isEqualTo(1);
assertEquals("myValue", tb1.getSomeMap().get("myKey")); assertThat(tb1.getSomeMap().get("myKey")).isEqualTo("myValue");
assertEquals(2, tb2.getStringArray().length); assertThat(tb2.getStringArray().length).isEqualTo(2);
assertEquals(System.getProperty("os.name"), tb2.getStringArray()[0]); assertThat(tb2.getStringArray()[0]).isEqualTo(System.getProperty("os.name"));
assertEquals("98", tb2.getStringArray()[1]); assertThat(tb2.getStringArray()[1]).isEqualTo("98");
assertEquals(2, tb2.getFriends().size()); assertThat(tb2.getFriends().size()).isEqualTo(2);
assertEquals("na98me", tb2.getFriends().iterator().next()); assertThat(tb2.getFriends().iterator().next()).isEqualTo("na98me");
assertEquals(tb2, tb2.getFriends().toArray()[1]); assertThat(tb2.getFriends().toArray()[1]).isEqualTo(tb2);
assertEquals(3, tb2.getSomeSet().size()); assertThat(tb2.getSomeSet().size()).isEqualTo(3);
assertTrue(tb2.getSomeSet().contains("na98me")); assertThat(tb2.getSomeSet().contains("na98me")).isTrue();
assertTrue(tb2.getSomeSet().contains(tb2)); assertThat(tb2.getSomeSet().contains(tb2)).isTrue();
assertTrue(tb2.getSomeSet().contains(new Integer(98))); assertThat(tb2.getSomeSet().contains(new Integer(98))).isTrue();
assertEquals(6, tb2.getSomeMap().size()); assertThat(tb2.getSomeMap().size()).isEqualTo(6);
assertEquals("98", tb2.getSomeMap().get("key98")); assertThat(tb2.getSomeMap().get("key98")).isEqualTo("98");
assertEquals(tb2, tb2.getSomeMap().get("key98ref")); assertThat(tb2.getSomeMap().get("key98ref")).isEqualTo(tb2);
assertEquals(tb2, tb2.getSomeMap().get("key1")); assertThat(tb2.getSomeMap().get("key1")).isEqualTo(tb2);
assertEquals("98name", tb2.getSomeMap().get("key2")); assertThat(tb2.getSomeMap().get("key2")).isEqualTo("98name");
TestBean inner1 = (TestBean) tb2.getSomeMap().get("key3"); TestBean inner1 = (TestBean) tb2.getSomeMap().get("key3");
TestBean inner2 = (TestBean) tb2.getSomeMap().get("mykey4"); TestBean inner2 = (TestBean) tb2.getSomeMap().get("mykey4");
assertEquals(0, inner1.getAge()); assertThat(inner1.getAge()).isEqualTo(0);
assertEquals(null, inner1.getName()); assertThat(inner1.getName()).isEqualTo(null);
assertEquals(System.getProperty("os.name"), inner1.getCountry()); assertThat(inner1.getCountry()).isEqualTo(System.getProperty("os.name"));
assertEquals(98, inner2.getAge()); assertThat(inner2.getAge()).isEqualTo(98);
assertEquals("namemyvarmyvar${", inner2.getName()); assertThat(inner2.getName()).isEqualTo("namemyvarmyvar${");
assertEquals(System.getProperty("os.name"), inner2.getCountry()); assertThat(inner2.getCountry()).isEqualTo(System.getProperty("os.name"));
} }
@Test @Test
@ -443,7 +439,7 @@ public class PropertyResourceConfigurerTests {
ppc.postProcessBeanFactory(factory); ppc.postProcessBeanFactory(factory);
TestBean tb = (TestBean) factory.getBean("tb"); TestBean tb = (TestBean) factory.getBean("tb");
assertEquals(System.getProperty("os.name"), tb.getCountry()); assertThat(tb.getCountry()).isEqualTo(System.getProperty("os.name"));
} }
@Test @Test
@ -458,7 +454,7 @@ public class PropertyResourceConfigurerTests {
ppc.postProcessBeanFactory(factory); ppc.postProcessBeanFactory(factory);
TestBean tb = (TestBean) factory.getBean("tb"); TestBean tb = (TestBean) factory.getBean("tb");
assertEquals("myos", tb.getCountry()); assertThat(tb.getCountry()).isEqualTo("myos");
} }
@Test @Test
@ -474,7 +470,7 @@ public class PropertyResourceConfigurerTests {
ppc.postProcessBeanFactory(factory); ppc.postProcessBeanFactory(factory);
TestBean tb = (TestBean) factory.getBean("tb"); TestBean tb = (TestBean) factory.getBean("tb");
assertEquals(System.getProperty("os.name"), tb.getCountry()); assertThat(tb.getCountry()).isEqualTo(System.getProperty("os.name"));
} }
@Test @Test
@ -508,7 +504,7 @@ public class PropertyResourceConfigurerTests {
ppc.postProcessBeanFactory(factory); ppc.postProcessBeanFactory(factory);
TestBean tb = (TestBean) factory.getBean("tb"); TestBean tb = (TestBean) factory.getBean("tb");
assertEquals("${ref}", tb.getName()); assertThat(tb.getName()).isEqualTo("${ref}");
} }
@Test @Test
@ -521,7 +517,7 @@ public class PropertyResourceConfigurerTests {
ppc.postProcessBeanFactory(factory); ppc.postProcessBeanFactory(factory);
TestBean tb = (TestBean) factory.getBean("tb"); TestBean tb = (TestBean) factory.getBean("tb");
assertNull(tb.getName()); assertThat(tb.getName()).isNull();
} }
@Test @Test
@ -537,7 +533,7 @@ public class PropertyResourceConfigurerTests {
ppc.postProcessBeanFactory(factory); ppc.postProcessBeanFactory(factory);
TestBean tb = (TestBean) factory.getBean("tb"); TestBean tb = (TestBean) factory.getBean("tb");
assertNull(tb.getName()); assertThat(tb.getName()).isNull();
} }
@Test @Test
@ -553,7 +549,7 @@ public class PropertyResourceConfigurerTests {
ppc.postProcessBeanFactory(factory); ppc.postProcessBeanFactory(factory);
TestBean tb = (TestBean) factory.getBean("tb"); TestBean tb = (TestBean) factory.getBean("tb");
assertEquals("myname", tb.getName()); assertThat(tb.getName()).isEqualTo("myname");
} }
@Test @Test
@ -569,7 +565,7 @@ public class PropertyResourceConfigurerTests {
TestBean tb = (TestBean) factory.getBean("tb"); TestBean tb = (TestBean) factory.getBean("tb");
TestBean tb2 = (TestBean) factory.getBean("tb2"); TestBean tb2 = (TestBean) factory.getBean("tb2");
assertSame(tb, tb2); assertThat(tb2).isSameAs(tb);
} }
@Test @Test
@ -584,8 +580,8 @@ public class PropertyResourceConfigurerTests {
ppc.postProcessBeanFactory(factory); ppc.postProcessBeanFactory(factory);
TestBean tb = (TestBean) factory.getBean("tb"); TestBean tb = (TestBean) factory.getBean("tb");
assertNotNull(tb); assertThat(tb).isNotNull();
assertEquals(0, factory.getAliases("tb").length); assertThat(factory.getAliases("tb").length).isEqualTo(0);
} }
@Test @Test
@ -617,7 +613,7 @@ public class PropertyResourceConfigurerTests {
ppc.postProcessBeanFactory(factory); ppc.postProcessBeanFactory(factory);
TestBean tb = (TestBean) factory.getBean("tb"); TestBean tb = (TestBean) factory.getBean("tb");
assertEquals("mytest", tb.getTouchy()); assertThat(tb.getTouchy()).isEqualTo("mytest");
} }
@Test @Test
@ -629,7 +625,7 @@ public class PropertyResourceConfigurerTests {
ppc.postProcessBeanFactory(factory); ppc.postProcessBeanFactory(factory);
TestBean tb = (TestBean) factory.getBean("tb"); TestBean tb = (TestBean) factory.getBean("tb");
assertEquals("mytest", tb.getTouchy()); assertThat(tb.getTouchy()).isEqualTo("mytest");
} }
@Test @Test
@ -649,11 +645,11 @@ public class PropertyResourceConfigurerTests {
ppc.postProcessBeanFactory(factory); ppc.postProcessBeanFactory(factory);
TestBean tb = (TestBean) factory.getBean("tb"); TestBean tb = (TestBean) factory.getBean("tb");
assertEquals("mytest", tb.getTouchy()); assertThat(tb.getTouchy()).isEqualTo("mytest");
tb = (TestBean) factory.getBean("alias"); tb = (TestBean) factory.getBean("alias");
assertEquals("mytest", tb.getTouchy()); assertThat(tb.getTouchy()).isEqualTo("mytest");
tb = (TestBean) factory.getBean("alias2"); tb = (TestBean) factory.getBean("alias2");
assertEquals("mytest", tb.getTouchy()); assertThat(tb.getTouchy()).isEqualTo("mytest");
} }
@Test @Test
@ -675,9 +671,9 @@ public class PropertyResourceConfigurerTests {
ppc.postProcessBeanFactory(factory); ppc.postProcessBeanFactory(factory);
TestBean tb = (TestBean) factory.getBean("tb"); TestBean tb = (TestBean) factory.getBean("tb");
assertEquals("myNameValue", tb.getName()); assertThat(tb.getName()).isEqualTo("myNameValue");
assertEquals(99, tb.getAge()); assertThat(tb.getAge()).isEqualTo(99);
assertEquals("myOtherTouchyValue", tb.getTouchy()); assertThat(tb.getTouchy()).isEqualTo("myOtherTouchyValue");
Preferences.userRoot().remove("myTouchy"); Preferences.userRoot().remove("myTouchy");
Preferences.systemRoot().remove("myTouchy"); Preferences.systemRoot().remove("myTouchy");
Preferences.systemRoot().remove("myName"); Preferences.systemRoot().remove("myName");
@ -704,9 +700,9 @@ public class PropertyResourceConfigurerTests {
ppc.postProcessBeanFactory(factory); ppc.postProcessBeanFactory(factory);
TestBean tb = (TestBean) factory.getBean("tb"); TestBean tb = (TestBean) factory.getBean("tb");
assertEquals("myNameValue", tb.getName()); assertThat(tb.getName()).isEqualTo("myNameValue");
assertEquals(99, tb.getAge()); assertThat(tb.getAge()).isEqualTo(99);
assertEquals("myOtherTouchyValue", tb.getTouchy()); assertThat(tb.getTouchy()).isEqualTo("myOtherTouchyValue");
Preferences.userRoot().node("myUserPath").remove("myTouchy"); Preferences.userRoot().node("myUserPath").remove("myTouchy");
Preferences.systemRoot().node("mySystemPath").remove("myTouchy"); Preferences.systemRoot().node("mySystemPath").remove("myTouchy");
Preferences.systemRoot().node("mySystemPath").remove("myName"); Preferences.systemRoot().node("mySystemPath").remove("myName");
@ -733,9 +729,9 @@ public class PropertyResourceConfigurerTests {
ppc.postProcessBeanFactory(factory); ppc.postProcessBeanFactory(factory);
TestBean tb = (TestBean) factory.getBean("tb"); TestBean tb = (TestBean) factory.getBean("tb");
assertEquals("myNameValue", tb.getName()); assertThat(tb.getName()).isEqualTo("myNameValue");
assertEquals(99, tb.getAge()); assertThat(tb.getAge()).isEqualTo(99);
assertEquals("myOtherTouchyValue", tb.getTouchy()); assertThat(tb.getTouchy()).isEqualTo("myOtherTouchyValue");
Preferences.userRoot().node("myUserPath/myotherpath").remove("myTouchy"); Preferences.userRoot().node("myUserPath/myotherpath").remove("myTouchy");
Preferences.systemRoot().node("mySystemPath/myotherpath").remove("myTouchy"); Preferences.systemRoot().node("mySystemPath/myotherpath").remove("myTouchy");
Preferences.systemRoot().node("mySystemPath/mypath").remove("myName"); Preferences.systemRoot().node("mySystemPath/mypath").remove("myName");

View File

@ -27,12 +27,9 @@ import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.core.NestedCheckedException; import org.springframework.core.NestedCheckedException;
import org.springframework.core.NestedRuntimeException; import org.springframework.core.NestedRuntimeException;
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.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNotSame;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
import static org.springframework.beans.factory.support.BeanDefinitionBuilder.genericBeanDefinition; import static org.springframework.beans.factory.support.BeanDefinitionBuilder.genericBeanDefinition;
@ -62,7 +59,7 @@ public class ServiceLocatorFactoryBeanTests {
TestServiceLocator factory = (TestServiceLocator) bf.getBean("factory"); TestServiceLocator factory = (TestServiceLocator) bf.getBean("factory");
TestService testService = factory.getTestService(); TestService testService = factory.getTestService();
assertNotNull(testService); assertThat(testService).isNotNull();
} }
@Test @Test
@ -161,14 +158,14 @@ public class ServiceLocatorFactoryBeanTests {
TestService testBean2 = factory.getTestService("testService"); TestService testBean2 = factory.getTestService("testService");
TestService testBean3 = factory.getTestService(1); TestService testBean3 = factory.getTestService(1);
TestService testBean4 = factory.someFactoryMethod(); TestService testBean4 = factory.someFactoryMethod();
assertNotSame(testBean1, testBean2); assertThat(testBean2).isNotSameAs(testBean1);
assertNotSame(testBean1, testBean3); assertThat(testBean3).isNotSameAs(testBean1);
assertNotSame(testBean1, testBean4); assertThat(testBean4).isNotSameAs(testBean1);
assertNotSame(testBean2, testBean3); assertThat(testBean3).isNotSameAs(testBean2);
assertNotSame(testBean2, testBean4); assertThat(testBean4).isNotSameAs(testBean2);
assertNotSame(testBean3, testBean4); assertThat(testBean4).isNotSameAs(testBean3);
assertTrue(factory.toString().contains("TestServiceLocator3")); assertThat(factory.toString().contains("TestServiceLocator3")).isTrue();
} }
@Ignore @Test // worked when using an ApplicationContext (see commented), fails when using BeanFactory @Ignore @Test // worked when using an ApplicationContext (see commented), fails when using BeanFactory
@ -195,16 +192,20 @@ public class ServiceLocatorFactoryBeanTests {
TestService testBean2 = factory.getTestService("testService1"); TestService testBean2 = factory.getTestService("testService1");
TestService testBean3 = factory.getTestService(1); TestService testBean3 = factory.getTestService(1);
TestService testBean4 = factory.getTestService(2); TestService testBean4 = factory.getTestService(2);
assertNotSame(testBean1, testBean2); assertThat(testBean2).isNotSameAs(testBean1);
assertNotSame(testBean1, testBean3); assertThat(testBean3).isNotSameAs(testBean1);
assertNotSame(testBean1, testBean4); assertThat(testBean4).isNotSameAs(testBean1);
assertNotSame(testBean2, testBean3); assertThat(testBean3).isNotSameAs(testBean2);
assertNotSame(testBean2, testBean4); assertThat(testBean4).isNotSameAs(testBean2);
assertNotSame(testBean3, testBean4); assertThat(testBean4).isNotSameAs(testBean3);
assertFalse(testBean1 instanceof ExtendedTestService); boolean condition3 = testBean1 instanceof ExtendedTestService;
assertFalse(testBean2 instanceof ExtendedTestService); assertThat(condition3).isFalse();
assertFalse(testBean3 instanceof ExtendedTestService); boolean condition2 = testBean2 instanceof ExtendedTestService;
assertTrue(testBean4 instanceof ExtendedTestService); assertThat(condition2).isFalse();
boolean condition1 = testBean3 instanceof ExtendedTestService;
assertThat(condition1).isFalse();
boolean condition = testBean4 instanceof ExtendedTestService;
assertThat(condition).isTrue();
} }
@Test @Test

View File

@ -27,9 +27,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.tests.sample.beans.TestBean; import org.springframework.tests.sample.beans.TestBean;
import static org.junit.Assert.assertEquals; import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertNotSame;
import static org.junit.Assert.assertSame;
import static org.springframework.tests.TestResourceUtils.qualifiedResource; import static org.springframework.tests.TestResourceUtils.qualifiedResource;
/** /**
@ -65,9 +63,9 @@ public class SimpleScopeTests {
beanFactory.registerScope("myScope", scope); beanFactory.registerScope("myScope", scope);
String[] scopeNames = beanFactory.getRegisteredScopeNames(); String[] scopeNames = beanFactory.getRegisteredScopeNames();
assertEquals(1, scopeNames.length); assertThat(scopeNames.length).isEqualTo(1);
assertEquals("myScope", scopeNames[0]); assertThat(scopeNames[0]).isEqualTo("myScope");
assertSame(scope, beanFactory.getRegisteredScope("myScope")); assertThat(beanFactory.getRegisteredScope("myScope")).isSameAs(scope);
new XmlBeanDefinitionReader(beanFactory).loadBeanDefinitions( new XmlBeanDefinitionReader(beanFactory).loadBeanDefinitions(
qualifiedResource(SimpleScopeTests.class, "context.xml")); qualifiedResource(SimpleScopeTests.class, "context.xml"));
@ -78,9 +76,9 @@ public class SimpleScopeTests {
public void testCanGetScopedObject() { public void testCanGetScopedObject() {
TestBean tb1 = (TestBean) beanFactory.getBean("usesScope"); TestBean tb1 = (TestBean) beanFactory.getBean("usesScope");
TestBean tb2 = (TestBean) beanFactory.getBean("usesScope"); TestBean tb2 = (TestBean) beanFactory.getBean("usesScope");
assertNotSame(tb1, tb2); assertThat(tb2).isNotSameAs(tb1);
TestBean tb3 = (TestBean) beanFactory.getBean("usesScope"); TestBean tb3 = (TestBean) beanFactory.getBean("usesScope");
assertSame(tb3, tb1); assertThat(tb1).isSameAs(tb3);
} }
} }

View File

@ -28,10 +28,9 @@ import org.springframework.core.io.AbstractResource;
import org.springframework.core.io.ByteArrayResource; import org.springframework.core.io.ByteArrayResource;
import org.springframework.core.io.FileSystemResource; import org.springframework.core.io.FileSystemResource;
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.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
/** /**
* Tests for {@link YamlMapFactoryBean}. * Tests for {@link YamlMapFactoryBean}.
@ -48,7 +47,7 @@ public class YamlMapFactoryBeanTests {
public void testSetIgnoreResourceNotFound() { public void testSetIgnoreResourceNotFound() {
this.factory.setResolutionMethod(YamlMapFactoryBean.ResolutionMethod.OVERRIDE_AND_IGNORE); this.factory.setResolutionMethod(YamlMapFactoryBean.ResolutionMethod.OVERRIDE_AND_IGNORE);
this.factory.setResources(new FileSystemResource("non-exsitent-file.yml")); this.factory.setResources(new FileSystemResource("non-exsitent-file.yml"));
assertEquals(0, this.factory.getObject().size()); assertThat(this.factory.getObject().size()).isEqualTo(0);
} }
@Test @Test
@ -62,7 +61,7 @@ public class YamlMapFactoryBeanTests {
@Test @Test
public void testGetObject() { public void testGetObject() {
this.factory.setResources(new ByteArrayResource("foo: bar".getBytes())); this.factory.setResources(new ByteArrayResource("foo: bar".getBytes()));
assertEquals(1, this.factory.getObject().size()); assertThat(this.factory.getObject().size()).isEqualTo(1);
} }
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
@ -71,8 +70,8 @@ public class YamlMapFactoryBeanTests {
this.factory.setResources(new ByteArrayResource("foo:\n bar: spam".getBytes()), this.factory.setResources(new ByteArrayResource("foo:\n bar: spam".getBytes()),
new ByteArrayResource("foo:\n spam: bar".getBytes())); new ByteArrayResource("foo:\n spam: bar".getBytes()));
assertEquals(1, this.factory.getObject().size()); assertThat(this.factory.getObject().size()).isEqualTo(1);
assertEquals(2, ((Map<String, Object>) this.factory.getObject().get("foo")).size()); assertThat(((Map<String, Object>) this.factory.getObject().get("foo")).size()).isEqualTo(2);
} }
@Test @Test
@ -89,7 +88,7 @@ public class YamlMapFactoryBeanTests {
} }
}, new ByteArrayResource("foo:\n spam: bar".getBytes())); }, new ByteArrayResource("foo:\n spam: bar".getBytes()));
assertEquals(1, this.factory.getObject().size()); assertThat(this.factory.getObject().size()).isEqualTo(1);
} }
@Test @Test
@ -97,14 +96,15 @@ public class YamlMapFactoryBeanTests {
this.factory.setResources(new ByteArrayResource("foo:\n ? key1.key2\n : value".getBytes())); this.factory.setResources(new ByteArrayResource("foo:\n ? key1.key2\n : value".getBytes()));
Map<String, Object> map = this.factory.getObject(); Map<String, Object> map = this.factory.getObject();
assertEquals(1, map.size()); assertThat(map.size()).isEqualTo(1);
assertTrue(map.containsKey("foo")); assertThat(map.containsKey("foo")).isTrue();
Object object = map.get("foo"); Object object = map.get("foo");
assertTrue(object instanceof LinkedHashMap); boolean condition = object instanceof LinkedHashMap;
assertThat(condition).isTrue();
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
Map<String, Object> sub = (Map<String, Object>) object; Map<String, Object> sub = (Map<String, Object>) object;
assertTrue(sub.containsKey("key1.key2")); assertThat(sub.containsKey("key1.key2")).isTrue();
assertEquals("value", sub.get("key1.key2")); assertThat(sub.get("key1.key2")).isEqualTo("value");
} }
@Test @Test
@ -112,14 +112,15 @@ public class YamlMapFactoryBeanTests {
this.factory.setResources(new ByteArrayResource("foo:\n ? key1.key2\n : 3".getBytes())); this.factory.setResources(new ByteArrayResource("foo:\n ? key1.key2\n : 3".getBytes()));
Map<String, Object> map = this.factory.getObject(); Map<String, Object> map = this.factory.getObject();
assertEquals(1, map.size()); assertThat(map.size()).isEqualTo(1);
assertTrue(map.containsKey("foo")); assertThat(map.containsKey("foo")).isTrue();
Object object = map.get("foo"); Object object = map.get("foo");
assertTrue(object instanceof LinkedHashMap); boolean condition = object instanceof LinkedHashMap;
assertThat(condition).isTrue();
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
Map<String, Object> sub = (Map<String, Object>) object; Map<String, Object> sub = (Map<String, Object>) object;
assertEquals(1, sub.size()); assertThat(sub.size()).isEqualTo(1);
assertEquals(Integer.valueOf(3), sub.get("key1.key2")); assertThat(sub.get("key1.key2")).isEqualTo(Integer.valueOf(3));
} }
@Test @Test

View File

@ -25,9 +25,8 @@ import org.yaml.snakeyaml.scanner.ScannerException;
import org.springframework.core.io.ByteArrayResource; import org.springframework.core.io.ByteArrayResource;
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.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
/** /**
* Tests for {@link YamlProcessor}. * Tests for {@link YamlProcessor}.
@ -44,22 +43,22 @@ public class YamlProcessorTests {
public void arrayConvertedToIndexedBeanReference() { public void arrayConvertedToIndexedBeanReference() {
this.processor.setResources(new ByteArrayResource("foo: bar\nbar: [1,2,3]".getBytes())); this.processor.setResources(new ByteArrayResource("foo: bar\nbar: [1,2,3]".getBytes()));
this.processor.process((properties, map) -> { this.processor.process((properties, map) -> {
assertEquals(4, properties.size()); assertThat(properties.size()).isEqualTo(4);
assertEquals("bar", properties.get("foo")); assertThat(properties.get("foo")).isEqualTo("bar");
assertEquals("bar", properties.getProperty("foo")); assertThat(properties.getProperty("foo")).isEqualTo("bar");
assertEquals(1, properties.get("bar[0]")); assertThat(properties.get("bar[0]")).isEqualTo(1);
assertEquals("1", properties.getProperty("bar[0]")); assertThat(properties.getProperty("bar[0]")).isEqualTo("1");
assertEquals(2, properties.get("bar[1]")); assertThat(properties.get("bar[1]")).isEqualTo(2);
assertEquals("2", properties.getProperty("bar[1]")); assertThat(properties.getProperty("bar[1]")).isEqualTo("2");
assertEquals(3, properties.get("bar[2]")); assertThat(properties.get("bar[2]")).isEqualTo(3);
assertEquals("3", properties.getProperty("bar[2]")); assertThat(properties.getProperty("bar[2]")).isEqualTo("3");
}); });
} }
@Test @Test
public void testStringResource() { public void testStringResource() {
this.processor.setResources(new ByteArrayResource("foo # a document that is a literal".getBytes())); this.processor.setResources(new ByteArrayResource("foo # a document that is a literal".getBytes()));
this.processor.process((properties, map) -> assertEquals("foo", map.get("document"))); this.processor.process((properties, map) -> assertThat(map.get("document")).isEqualTo("foo"));
} }
@Test @Test
@ -82,8 +81,8 @@ public class YamlProcessorTests {
public void mapConvertedToIndexedBeanReference() { public void mapConvertedToIndexedBeanReference() {
this.processor.setResources(new ByteArrayResource("foo: bar\nbar:\n spam: bucket".getBytes())); this.processor.setResources(new ByteArrayResource("foo: bar\nbar:\n spam: bucket".getBytes()));
this.processor.process((properties, map) -> { this.processor.process((properties, map) -> {
assertEquals("bucket", properties.get("bar.spam")); assertThat(properties.get("bar.spam")).isEqualTo("bucket");
assertEquals(2, properties.size()); assertThat(properties.size()).isEqualTo(2);
}); });
} }
@ -91,8 +90,8 @@ public class YamlProcessorTests {
public void integerKeyBehaves() { public void integerKeyBehaves() {
this.processor.setResources(new ByteArrayResource("foo: bar\n1: bar".getBytes())); this.processor.setResources(new ByteArrayResource("foo: bar\n1: bar".getBytes()));
this.processor.process((properties, map) -> { this.processor.process((properties, map) -> {
assertEquals("bar", properties.get("[1]")); assertThat(properties.get("[1]")).isEqualTo("bar");
assertEquals(2, properties.size()); assertThat(properties.size()).isEqualTo(2);
}); });
} }
@ -100,8 +99,8 @@ public class YamlProcessorTests {
public void integerDeepKeyBehaves() { public void integerDeepKeyBehaves() {
this.processor.setResources(new ByteArrayResource("foo:\n 1: bar".getBytes())); this.processor.setResources(new ByteArrayResource("foo:\n 1: bar".getBytes()));
this.processor.process((properties, map) -> { this.processor.process((properties, map) -> {
assertEquals("bar", properties.get("foo[1]")); assertThat(properties.get("foo[1]")).isEqualTo("bar");
assertEquals(1, properties.size()); assertThat(properties.size()).isEqualTo(1);
}); });
} }
@ -110,14 +109,15 @@ public class YamlProcessorTests {
public void flattenedMapIsSameAsPropertiesButOrdered() { public void flattenedMapIsSameAsPropertiesButOrdered() {
this.processor.setResources(new ByteArrayResource("foo: bar\nbar:\n spam: bucket".getBytes())); this.processor.setResources(new ByteArrayResource("foo: bar\nbar:\n spam: bucket".getBytes()));
this.processor.process((properties, map) -> { this.processor.process((properties, map) -> {
assertEquals("bucket", properties.get("bar.spam")); assertThat(properties.get("bar.spam")).isEqualTo("bucket");
assertEquals(2, properties.size()); assertThat(properties.size()).isEqualTo(2);
Map<String, Object> flattenedMap = processor.getFlattenedMap(map); Map<String, Object> flattenedMap = processor.getFlattenedMap(map);
assertEquals("bucket", flattenedMap.get("bar.spam")); assertThat(flattenedMap.get("bar.spam")).isEqualTo("bucket");
assertEquals(2, flattenedMap.size()); assertThat(flattenedMap.size()).isEqualTo(2);
assertTrue(flattenedMap instanceof LinkedHashMap); boolean condition = flattenedMap instanceof LinkedHashMap;
assertThat(condition).isTrue();
Map<String, Object> bar = (Map<String, Object>) map.get("bar"); Map<String, Object> bar = (Map<String, Object>) map.get("bar");
assertEquals("bucket", bar.get("spam")); assertThat(bar.get("spam")).isEqualTo("bucket");
}); });
} }

View File

@ -26,8 +26,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.tests.sample.beans.TestBean; import org.springframework.tests.sample.beans.TestBean;
import static org.junit.Assert.assertEquals; import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertNotNull;
import static org.springframework.tests.TestResourceUtils.qualifiedResource; import static org.springframework.tests.TestResourceUtils.qualifiedResource;
/** /**
@ -56,10 +55,10 @@ public class CustomProblemReporterTests {
@Test @Test
public void testErrorsAreCollated() { public void testErrorsAreCollated() {
this.reader.loadBeanDefinitions(qualifiedResource(CustomProblemReporterTests.class, "context.xml")); this.reader.loadBeanDefinitions(qualifiedResource(CustomProblemReporterTests.class, "context.xml"));
assertEquals("Incorrect number of errors collated", 4, this.problemReporter.getErrors().length); assertThat(this.problemReporter.getErrors().length).as("Incorrect number of errors collated").isEqualTo(4);
TestBean bean = (TestBean) this.beanFactory.getBean("validBean"); TestBean bean = (TestBean) this.beanFactory.getBean("validBean");
assertNotNull(bean); assertThat(bean).isNotNull();
} }

View File

@ -18,7 +18,7 @@ package org.springframework.beans.factory.parsing;
import org.junit.Test; import org.junit.Test;
import static org.junit.Assert.assertNull; import static org.assertj.core.api.Assertions.assertThat;
/** /**
* @author Rick Evans * @author Rick Evans
@ -30,13 +30,13 @@ public class NullSourceExtractorTests {
public void testPassThroughContract() throws Exception { public void testPassThroughContract() throws Exception {
Object source = new Object(); Object source = new Object();
Object extractedSource = new NullSourceExtractor().extractSource(source, null); Object extractedSource = new NullSourceExtractor().extractSource(source, null);
assertNull("The contract of NullSourceExtractor states that the extraction *always* return null", extractedSource); assertThat(extractedSource).as("The contract of NullSourceExtractor states that the extraction *always* return null").isNull();
} }
@Test @Test
public void testPassThroughContractEvenWithNull() throws Exception { public void testPassThroughContractEvenWithNull() throws Exception {
Object extractedSource = new NullSourceExtractor().extractSource(null, null); Object extractedSource = new NullSourceExtractor().extractSource(null, null);
assertNull("The contract of NullSourceExtractor states that the extraction *always* return null", extractedSource); assertThat(extractedSource).as("The contract of NullSourceExtractor states that the extraction *always* return null").isNull();
} }
} }

View File

@ -18,8 +18,7 @@ package org.springframework.beans.factory.parsing;
import org.junit.Test; import org.junit.Test;
import static org.junit.Assert.assertEquals; import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertNull;
/** /**
* @author Rob Harrop * @author Rob Harrop
@ -34,9 +33,9 @@ public class ParseStateTests {
ParseState parseState = new ParseState(); ParseState parseState = new ParseState();
parseState.push(entry); parseState.push(entry);
assertEquals("Incorrect peek value.", entry, parseState.peek()); assertThat(parseState.peek()).as("Incorrect peek value.").isEqualTo(entry);
parseState.pop(); parseState.pop();
assertNull("Should get null on peek()", parseState.peek()); assertThat(parseState.peek()).as("Should get null on peek()").isNull();
} }
@Test @Test
@ -47,16 +46,16 @@ public class ParseStateTests {
ParseState parseState = new ParseState(); ParseState parseState = new ParseState();
parseState.push(one); parseState.push(one);
assertEquals(one, parseState.peek()); assertThat(parseState.peek()).isEqualTo(one);
parseState.push(two); parseState.push(two);
assertEquals(two, parseState.peek()); assertThat(parseState.peek()).isEqualTo(two);
parseState.push(three); parseState.push(three);
assertEquals(three, parseState.peek()); assertThat(parseState.peek()).isEqualTo(three);
parseState.pop(); parseState.pop();
assertEquals(two, parseState.peek()); assertThat(parseState.peek()).isEqualTo(two);
parseState.pop(); parseState.pop();
assertEquals(one, parseState.peek()); assertThat(parseState.peek()).isEqualTo(one);
} }
@Test @Test
@ -68,7 +67,7 @@ public class ParseStateTests {
ParseState snapshot = original.snapshot(); ParseState snapshot = original.snapshot();
original.push(new MockEntry()); original.push(new MockEntry());
assertEquals("Snapshot should not have been modified.", entry, snapshot.peek()); assertThat(snapshot.peek()).as("Snapshot should not have been modified.").isEqualTo(entry);
} }

View File

@ -18,8 +18,7 @@ package org.springframework.beans.factory.parsing;
import org.junit.Test; import org.junit.Test;
import static org.junit.Assert.assertNull; import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertSame;
/** /**
* Unit tests for {@link PassThroughSourceExtractor}. * Unit tests for {@link PassThroughSourceExtractor}.
@ -33,15 +32,15 @@ public class PassThroughSourceExtractorTests {
public void testPassThroughContract() throws Exception { public void testPassThroughContract() throws Exception {
Object source = new Object(); Object source = new Object();
Object extractedSource = new PassThroughSourceExtractor().extractSource(source, null); Object extractedSource = new PassThroughSourceExtractor().extractSource(source, null);
assertSame("The contract of PassThroughSourceExtractor states that the supplied " + assertThat(extractedSource).as("The contract of PassThroughSourceExtractor states that the supplied " +
"source object *must* be returned as-is", source, extractedSource); "source object *must* be returned as-is").isSameAs(source);
} }
@Test @Test
public void testPassThroughContractEvenWithNull() throws Exception { public void testPassThroughContractEvenWithNull() throws Exception {
Object extractedSource = new PassThroughSourceExtractor().extractSource(null, null); Object extractedSource = new PassThroughSourceExtractor().extractSource(null, null);
assertNull("The contract of PassThroughSourceExtractor states that the supplied " + assertThat(extractedSource).as("The contract of PassThroughSourceExtractor states that the supplied " +
"source object *must* be returned as-is (even if null)", extractedSource); "source object *must* be returned as-is (even if null)").isNull();
} }
} }

View File

@ -25,7 +25,7 @@ import org.junit.Test;
import org.springframework.beans.factory.support.DefaultListableBeanFactory; import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.beans.factory.support.RootBeanDefinition; import org.springframework.beans.factory.support.RootBeanDefinition;
import static org.junit.Assert.assertTrue; import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assume.assumeTrue; import static org.junit.Assume.assumeTrue;
/** /**
@ -43,7 +43,8 @@ public class ServiceLoaderTests {
bd.getPropertyValues().add("serviceType", DocumentBuilderFactory.class.getName()); bd.getPropertyValues().add("serviceType", DocumentBuilderFactory.class.getName());
bf.registerBeanDefinition("service", bd); bf.registerBeanDefinition("service", bd);
ServiceLoader<?> serviceLoader = (ServiceLoader<?>) bf.getBean("service"); ServiceLoader<?> serviceLoader = (ServiceLoader<?>) bf.getBean("service");
assertTrue(serviceLoader.iterator().next() instanceof DocumentBuilderFactory); boolean condition = serviceLoader.iterator().next() instanceof DocumentBuilderFactory;
assertThat(condition).isTrue();
} }
@Test @Test
@ -54,7 +55,8 @@ public class ServiceLoaderTests {
RootBeanDefinition bd = new RootBeanDefinition(ServiceFactoryBean.class); RootBeanDefinition bd = new RootBeanDefinition(ServiceFactoryBean.class);
bd.getPropertyValues().add("serviceType", DocumentBuilderFactory.class.getName()); bd.getPropertyValues().add("serviceType", DocumentBuilderFactory.class.getName());
bf.registerBeanDefinition("service", bd); bf.registerBeanDefinition("service", bd);
assertTrue(bf.getBean("service") instanceof DocumentBuilderFactory); boolean condition = bf.getBean("service") instanceof DocumentBuilderFactory;
assertThat(condition).isTrue();
} }
@Test @Test
@ -66,7 +68,8 @@ public class ServiceLoaderTests {
bd.getPropertyValues().add("serviceType", DocumentBuilderFactory.class.getName()); bd.getPropertyValues().add("serviceType", DocumentBuilderFactory.class.getName());
bf.registerBeanDefinition("service", bd); bf.registerBeanDefinition("service", bd);
List<?> serviceList = (List<?>) bf.getBean("service"); List<?> serviceList = (List<?>) bf.getBean("service");
assertTrue(serviceList.get(0) instanceof DocumentBuilderFactory); boolean condition = serviceList.get(0) instanceof DocumentBuilderFactory;
assertThat(condition).isTrue();
} }
} }

View File

@ -24,7 +24,7 @@ import org.junit.Test;
import org.springframework.util.ReflectionUtils; import org.springframework.util.ReflectionUtils;
import static org.junit.Assert.assertEquals; import static org.assertj.core.api.Assertions.assertThat;
/** /**
* Unit tests for {@link AutowireUtils}. * Unit tests for {@link AutowireUtils}.
@ -38,45 +38,36 @@ public class AutowireUtilsTests {
@Test @Test
public void genericMethodReturnTypes() { public void genericMethodReturnTypes() {
Method notParameterized = ReflectionUtils.findMethod(MyTypeWithMethods.class, "notParameterized"); Method notParameterized = ReflectionUtils.findMethod(MyTypeWithMethods.class, "notParameterized");
assertEquals(String.class, Object actual = AutowireUtils.resolveReturnTypeForFactoryMethod(notParameterized, new Object[0], getClass().getClassLoader());
AutowireUtils.resolveReturnTypeForFactoryMethod(notParameterized, new Object[0], getClass().getClassLoader())); assertThat(actual).isEqualTo(String.class);
Method notParameterizedWithArguments = ReflectionUtils.findMethod(MyTypeWithMethods.class, "notParameterizedWithArguments", Integer.class, Boolean.class); Method notParameterizedWithArguments = ReflectionUtils.findMethod(MyTypeWithMethods.class, "notParameterizedWithArguments", Integer.class, Boolean.class);
assertEquals(String.class, assertThat(AutowireUtils.resolveReturnTypeForFactoryMethod(notParameterizedWithArguments, new Object[]{99, true}, getClass().getClassLoader())).isEqualTo(String.class);
AutowireUtils.resolveReturnTypeForFactoryMethod(notParameterizedWithArguments, new Object[] {99, true}, getClass().getClassLoader()));
Method createProxy = ReflectionUtils.findMethod(MyTypeWithMethods.class, "createProxy", Object.class); Method createProxy = ReflectionUtils.findMethod(MyTypeWithMethods.class, "createProxy", Object.class);
assertEquals(String.class, assertThat(AutowireUtils.resolveReturnTypeForFactoryMethod(createProxy, new Object[]{"foo"}, getClass().getClassLoader())).isEqualTo(String.class);
AutowireUtils.resolveReturnTypeForFactoryMethod(createProxy, new Object[] {"foo"}, getClass().getClassLoader()));
Method createNamedProxyWithDifferentTypes = ReflectionUtils.findMethod(MyTypeWithMethods.class, "createNamedProxy", String.class, Object.class); Method createNamedProxyWithDifferentTypes = ReflectionUtils.findMethod(MyTypeWithMethods.class, "createNamedProxy", String.class, Object.class);
assertEquals(Long.class, assertThat(AutowireUtils.resolveReturnTypeForFactoryMethod(createNamedProxyWithDifferentTypes, new Object[]{"enigma", 99L}, getClass().getClassLoader())).isEqualTo(Long.class);
AutowireUtils.resolveReturnTypeForFactoryMethod(createNamedProxyWithDifferentTypes, new Object[] {"enigma", 99L}, getClass().getClassLoader()));
Method createNamedProxyWithDuplicateTypes = ReflectionUtils.findMethod(MyTypeWithMethods.class, "createNamedProxy", String.class, Object.class); Method createNamedProxyWithDuplicateTypes = ReflectionUtils.findMethod(MyTypeWithMethods.class, "createNamedProxy", String.class, Object.class);
assertEquals(String.class, assertThat(AutowireUtils.resolveReturnTypeForFactoryMethod(createNamedProxyWithDuplicateTypes, new Object[]{"enigma", "foo"}, getClass().getClassLoader())).isEqualTo(String.class);
AutowireUtils.resolveReturnTypeForFactoryMethod(createNamedProxyWithDuplicateTypes, new Object[] {"enigma", "foo"}, getClass().getClassLoader()));
Method createMock = ReflectionUtils.findMethod(MyTypeWithMethods.class, "createMock", Class.class); Method createMock = ReflectionUtils.findMethod(MyTypeWithMethods.class, "createMock", Class.class);
assertEquals(Runnable.class, assertThat(AutowireUtils.resolveReturnTypeForFactoryMethod(createMock, new Object[]{Runnable.class}, getClass().getClassLoader())).isEqualTo(Runnable.class);
AutowireUtils.resolveReturnTypeForFactoryMethod(createMock, new Object[] {Runnable.class}, getClass().getClassLoader())); assertThat(AutowireUtils.resolveReturnTypeForFactoryMethod(createMock, new Object[]{Runnable.class.getName()}, getClass().getClassLoader())).isEqualTo(Runnable.class);
assertEquals(Runnable.class,
AutowireUtils.resolveReturnTypeForFactoryMethod(createMock, new Object[] {Runnable.class.getName()}, getClass().getClassLoader()));
Method createNamedMock = ReflectionUtils.findMethod(MyTypeWithMethods.class, "createNamedMock", String.class, Class.class); Method createNamedMock = ReflectionUtils.findMethod(MyTypeWithMethods.class, "createNamedMock", String.class, Class.class);
assertEquals(Runnable.class, assertThat(AutowireUtils.resolveReturnTypeForFactoryMethod(createNamedMock, new Object[]{"foo", Runnable.class}, getClass().getClassLoader())).isEqualTo(Runnable.class);
AutowireUtils.resolveReturnTypeForFactoryMethod(createNamedMock, new Object[] {"foo", Runnable.class}, getClass().getClassLoader()));
Method createVMock = ReflectionUtils.findMethod(MyTypeWithMethods.class, "createVMock", Object.class, Class.class); Method createVMock = ReflectionUtils.findMethod(MyTypeWithMethods.class, "createVMock", Object.class, Class.class);
assertEquals(Runnable.class, assertThat(AutowireUtils.resolveReturnTypeForFactoryMethod(createVMock, new Object[]{"foo", Runnable.class}, getClass().getClassLoader())).isEqualTo(Runnable.class);
AutowireUtils.resolveReturnTypeForFactoryMethod(createVMock, new Object[] {"foo", Runnable.class}, getClass().getClassLoader()));
// Ideally we would expect String.class instead of Object.class, but // Ideally we would expect String.class instead of Object.class, but
// resolveReturnTypeForFactoryMethod() does not currently support this form of // resolveReturnTypeForFactoryMethod() does not currently support this form of
// look-up. // look-up.
Method extractValueFrom = ReflectionUtils.findMethod(MyTypeWithMethods.class, "extractValueFrom", MyInterfaceType.class); Method extractValueFrom = ReflectionUtils.findMethod(MyTypeWithMethods.class, "extractValueFrom", MyInterfaceType.class);
assertEquals(Object.class, assertThat(AutowireUtils.resolveReturnTypeForFactoryMethod(extractValueFrom, new Object[]{new MySimpleInterfaceType()}, getClass().getClassLoader())).isEqualTo(Object.class);
AutowireUtils.resolveReturnTypeForFactoryMethod(extractValueFrom, new Object[] {new MySimpleInterfaceType()}, getClass().getClassLoader()));
// Ideally we would expect Boolean.class instead of Object.class, but this // Ideally we would expect Boolean.class instead of Object.class, but this
// information is not available at run-time due to type erasure. // information is not available at run-time due to type erasure.
@ -84,7 +75,7 @@ public class AutowireUtilsTests {
map.put(0, false); map.put(0, false);
map.put(1, true); map.put(1, true);
Method extractMagicValue = ReflectionUtils.findMethod(MyTypeWithMethods.class, "extractMagicValue", Map.class); Method extractMagicValue = ReflectionUtils.findMethod(MyTypeWithMethods.class, "extractMagicValue", Map.class);
assertEquals(Object.class, AutowireUtils.resolveReturnTypeForFactoryMethod(extractMagicValue, new Object[] {map}, getClass().getClassLoader())); assertThat(AutowireUtils.resolveReturnTypeForFactoryMethod(extractMagicValue, new Object[]{map}, getClass().getClassLoader())).isEqualTo(Object.class);
} }

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